• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.testing;
18 
19 import static com.google.common.base.Preconditions.checkArgument;
20 import static com.google.common.base.Preconditions.checkNotNull;
21 
22 import com.google.common.annotations.Beta;
23 import com.google.common.annotations.GwtIncompatible;
24 import com.google.common.base.Converter;
25 import com.google.common.base.Objects;
26 import com.google.common.collect.ClassToInstanceMap;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.ImmutableSet;
29 import com.google.common.collect.Lists;
30 import com.google.common.collect.Maps;
31 import com.google.common.collect.MutableClassToInstanceMap;
32 import com.google.common.reflect.Invokable;
33 import com.google.common.reflect.Parameter;
34 import com.google.common.reflect.Reflection;
35 import com.google.common.reflect.TypeToken;
36 import java.lang.annotation.Annotation;
37 import java.lang.reflect.Constructor;
38 import java.lang.reflect.InvocationTargetException;
39 import java.lang.reflect.Member;
40 import java.lang.reflect.Method;
41 import java.lang.reflect.Modifier;
42 import java.lang.reflect.ParameterizedType;
43 import java.lang.reflect.Type;
44 import java.util.Arrays;
45 import java.util.List;
46 import java.util.concurrent.ConcurrentMap;
47 import junit.framework.Assert;
48 import junit.framework.AssertionFailedError;
49 import org.checkerframework.checker.nullness.qual.Nullable;
50 
51 /**
52  * A test utility that verifies that your methods and constructors throw {@link
53  * NullPointerException} or {@link UnsupportedOperationException} whenever null is passed to a
54  * parameter whose declaration or type isn't annotated with an annotation with the simple name
55  * {@code Nullable}, {@lcode CheckForNull}, {@link NullableType}, or {@link NullableDecl}.
56  *
57  * <p>The tested methods and constructors are invoked -- each time with one parameter being null and
58  * the rest not null -- and the test fails if no expected exception is thrown. {@code
59  * NullPointerTester} uses best effort to pick non-null default values for many common JDK and Guava
60  * types, and also for interfaces and public classes that have public parameter-less constructors.
61  * When the non-null default value for a particular parameter type cannot be provided by {@code
62  * NullPointerTester}, the caller can provide a custom non-null default value for the parameter type
63  * via {@link #setDefault}.
64  *
65  * @author Kevin Bourrillion
66  * @since 10.0
67  */
68 @Beta
69 @GwtIncompatible
70 public final class NullPointerTester {
71 
72   private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create();
73   private final List<Member> ignoredMembers = Lists.newArrayList();
74 
75   private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE;
76 
77   /**
78    * Sets a default value that can be used for any parameter of type {@code type}. Returns this
79    * object.
80    */
setDefault(Class<T> type, T value)81   public <T> NullPointerTester setDefault(Class<T> type, T value) {
82     defaults.putInstance(type, checkNotNull(value));
83     return this;
84   }
85 
86   /**
87    * Ignore {@code method} in the tests that follow. Returns this object.
88    *
89    * @since 13.0
90    */
ignore(Method method)91   public NullPointerTester ignore(Method method) {
92     ignoredMembers.add(checkNotNull(method));
93     return this;
94   }
95 
96   /**
97    * Ignore {@code constructor} in the tests that follow. Returns this object.
98    *
99    * @since 22.0
100    */
ignore(Constructor<?> constructor)101   public NullPointerTester ignore(Constructor<?> constructor) {
102     ignoredMembers.add(checkNotNull(constructor));
103     return this;
104   }
105 
106   /**
107    * Runs {@link #testConstructor} on every constructor in class {@code c} that has at least {@code
108    * minimalVisibility}.
109    */
testConstructors(Class<?> c, Visibility minimalVisibility)110   public void testConstructors(Class<?> c, Visibility minimalVisibility) {
111     for (Constructor<?> constructor : c.getDeclaredConstructors()) {
112       if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) {
113         testConstructor(constructor);
114       }
115     }
116   }
117 
118   /** Runs {@link #testConstructor} on every public constructor in class {@code c}. */
testAllPublicConstructors(Class<?> c)119   public void testAllPublicConstructors(Class<?> c) {
120     testConstructors(c, Visibility.PUBLIC);
121   }
122 
123   /**
124    * Runs {@link #testMethod} on every static method of class {@code c} that has at least {@code
125    * minimalVisibility}, including those "inherited" from superclasses of the same package.
126    */
testStaticMethods(Class<?> c, Visibility minimalVisibility)127   public void testStaticMethods(Class<?> c, Visibility minimalVisibility) {
128     for (Method method : minimalVisibility.getStaticMethods(c)) {
129       if (!isIgnored(method)) {
130         testMethod(null, method);
131       }
132     }
133   }
134 
135   /**
136    * Runs {@link #testMethod} on every public static method of class {@code c}, including those
137    * "inherited" from superclasses of the same package.
138    */
testAllPublicStaticMethods(Class<?> c)139   public void testAllPublicStaticMethods(Class<?> c) {
140     testStaticMethods(c, Visibility.PUBLIC);
141   }
142 
143   /**
144    * Runs {@link #testMethod} on every instance method of the class of {@code instance} with at
145    * least {@code minimalVisibility}, including those inherited from superclasses of the same
146    * package.
147    */
testInstanceMethods(Object instance, Visibility minimalVisibility)148   public void testInstanceMethods(Object instance, Visibility minimalVisibility) {
149     for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) {
150       testMethod(instance, method);
151     }
152   }
153 
getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility)154   ImmutableList<Method> getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility) {
155     ImmutableList.Builder<Method> builder = ImmutableList.builder();
156     for (Method method : minimalVisibility.getInstanceMethods(c)) {
157       if (!isIgnored(method)) {
158         builder.add(method);
159       }
160     }
161     return builder.build();
162   }
163 
164   /**
165    * Runs {@link #testMethod} on every public instance method of the class of {@code instance},
166    * including those inherited from superclasses of the same package.
167    */
testAllPublicInstanceMethods(Object instance)168   public void testAllPublicInstanceMethods(Object instance) {
169     testInstanceMethods(instance, Visibility.PUBLIC);
170   }
171 
172   /**
173    * Verifies that {@code method} produces a {@link NullPointerException} or {@link
174    * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null.
175    *
176    * @param instance the instance to invoke {@code method} on, or null if {@code method} is static
177    */
testMethod(@ullable Object instance, Method method)178   public void testMethod(@Nullable Object instance, Method method) {
179     Class<?>[] types = method.getParameterTypes();
180     for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
181       testMethodParameter(instance, method, nullIndex);
182     }
183   }
184 
185   /**
186    * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link
187    * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null.
188    */
testConstructor(Constructor<?> ctor)189   public void testConstructor(Constructor<?> ctor) {
190     Class<?> declaringClass = ctor.getDeclaringClass();
191     checkArgument(
192         Modifier.isStatic(declaringClass.getModifiers())
193             || declaringClass.getEnclosingClass() == null,
194         "Cannot test constructor of non-static inner class: %s",
195         declaringClass.getName());
196     Class<?>[] types = ctor.getParameterTypes();
197     for (int nullIndex = 0; nullIndex < types.length; nullIndex++) {
198       testConstructorParameter(ctor, nullIndex);
199     }
200   }
201 
202   /**
203    * Verifies that {@code method} produces a {@link NullPointerException} or {@link
204    * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
205    * this parameter is marked nullable, this method does nothing.
206    *
207    * @param instance the instance to invoke {@code method} on, or null if {@code method} is static
208    */
testMethodParameter( @ullable final Object instance, final Method method, int paramIndex)209   public void testMethodParameter(
210       @Nullable final Object instance, final Method method, int paramIndex) {
211     method.setAccessible(true);
212     testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass());
213   }
214 
215   /**
216    * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link
217    * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
218    * this parameter is marked nullable, this method does nothing.
219    */
testConstructorParameter(Constructor<?> ctor, int paramIndex)220   public void testConstructorParameter(Constructor<?> ctor, int paramIndex) {
221     ctor.setAccessible(true);
222     testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass());
223   }
224 
225   /** Visibility of any method or constructor. */
226   public enum Visibility {
227     PACKAGE {
228       @Override
isVisible(int modifiers)229       boolean isVisible(int modifiers) {
230         return !Modifier.isPrivate(modifiers);
231       }
232     },
233 
234     PROTECTED {
235       @Override
isVisible(int modifiers)236       boolean isVisible(int modifiers) {
237         return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
238       }
239     },
240 
241     PUBLIC {
242       @Override
isVisible(int modifiers)243       boolean isVisible(int modifiers) {
244         return Modifier.isPublic(modifiers);
245       }
246     };
247 
isVisible(int modifiers)248     abstract boolean isVisible(int modifiers);
249 
250     /** Returns {@code true} if {@code member} is visible under {@code this} visibility. */
isVisible(Member member)251     final boolean isVisible(Member member) {
252       return isVisible(member.getModifiers());
253     }
254 
getStaticMethods(Class<?> cls)255     final Iterable<Method> getStaticMethods(Class<?> cls) {
256       ImmutableList.Builder<Method> builder = ImmutableList.builder();
257       for (Method method : getVisibleMethods(cls)) {
258         if (Invokable.from(method).isStatic()) {
259           builder.add(method);
260         }
261       }
262       return builder.build();
263     }
264 
getInstanceMethods(Class<?> cls)265     final Iterable<Method> getInstanceMethods(Class<?> cls) {
266       ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap();
267       for (Method method : getVisibleMethods(cls)) {
268         if (!Invokable.from(method).isStatic()) {
269           map.putIfAbsent(new Signature(method), method);
270         }
271       }
272       return map.values();
273     }
274 
getVisibleMethods(Class<?> cls)275     private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
276       // Don't use cls.getPackage() because it does nasty things like reading
277       // a file.
278       String visiblePackage = Reflection.getPackageName(cls);
279       ImmutableList.Builder<Method> builder = ImmutableList.builder();
280       for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
281         if (!Reflection.getPackageName(type).equals(visiblePackage)) {
282           break;
283         }
284         for (Method method : type.getDeclaredMethods()) {
285           if (!method.isSynthetic() && isVisible(method)) {
286             builder.add(method);
287           }
288         }
289       }
290       return builder.build();
291     }
292   }
293 
294   private static final class Signature {
295     private final String name;
296     private final ImmutableList<Class<?>> parameterTypes;
297 
Signature(Method method)298     Signature(Method method) {
299       this(method.getName(), ImmutableList.copyOf(method.getParameterTypes()));
300     }
301 
Signature(String name, ImmutableList<Class<?>> parameterTypes)302     Signature(String name, ImmutableList<Class<?>> parameterTypes) {
303       this.name = name;
304       this.parameterTypes = parameterTypes;
305     }
306 
307     @Override
equals(Object obj)308     public boolean equals(Object obj) {
309       if (obj instanceof Signature) {
310         Signature that = (Signature) obj;
311         return name.equals(that.name) && parameterTypes.equals(that.parameterTypes);
312       }
313       return false;
314     }
315 
316     @Override
hashCode()317     public int hashCode() {
318       return Objects.hashCode(name, parameterTypes);
319     }
320   }
321 
322   /**
323    * Verifies that {@code invokable} produces a {@link NullPointerException} or {@link
324    * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If
325    * this parameter is marked nullable, this method does nothing.
326    *
327    * @param instance the instance to invoke {@code invokable} on, or null if {@code invokable} is
328    *     static
329    */
testParameter( Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass)330   private void testParameter(
331       Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
332     if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
333       return; // there's nothing to test
334     }
335     Object[] params = buildParamList(invokable, paramIndex);
336     try {
337       @SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong.
338       Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
339       unsafe.invoke(instance, params);
340       Assert.fail(
341           "No exception thrown for parameter at index "
342               + paramIndex
343               + " from "
344               + invokable
345               + Arrays.toString(params)
346               + " for "
347               + testedClass);
348     } catch (InvocationTargetException e) {
349       Throwable cause = e.getCause();
350       if (policy.isExpectedType(cause)) {
351         return;
352       }
353       AssertionFailedError error =
354           new AssertionFailedError(
355               String.format(
356                   "wrong exception thrown from %s when passing null to %s parameter at index %s.%n"
357                       + "Full parameters: %s%n"
358                       + "Actual exception message: %s",
359                   invokable,
360                   invokable.getParameters().get(paramIndex).getType(),
361                   paramIndex,
362                   Arrays.toString(params),
363                   cause));
364       error.initCause(cause);
365       throw error;
366     } catch (IllegalAccessException e) {
367       throw new RuntimeException(e);
368     }
369   }
370 
buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull)371   private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
372     ImmutableList<Parameter> params = invokable.getParameters();
373     Object[] args = new Object[params.size()];
374 
375     for (int i = 0; i < args.length; i++) {
376       Parameter param = params.get(i);
377       if (i != indexOfParamToSetToNull) {
378         args[i] = getDefaultValue(param.getType());
379         Assert.assertTrue(
380             "Can't find or create a sample instance for type '"
381                 + param.getType()
382                 + "'; please provide one using NullPointerTester.setDefault()",
383             args[i] != null || isNullable(param));
384       }
385     }
386     return args;
387   }
388 
getDefaultValue(TypeToken<T> type)389   private <T> T getDefaultValue(TypeToken<T> type) {
390     // We assume that all defaults are generics-safe, even if they aren't,
391     // we take the risk.
392     @SuppressWarnings("unchecked")
393     T defaultValue = (T) defaults.getInstance(type.getRawType());
394     if (defaultValue != null) {
395       return defaultValue;
396     }
397     @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe
398     T arbitrary = (T) ArbitraryInstances.get(type.getRawType());
399     if (arbitrary != null) {
400       return arbitrary;
401     }
402     if (type.getRawType() == Class.class) {
403       // If parameter is Class<? extends Foo>, we return Foo.class
404       @SuppressWarnings("unchecked")
405       T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType();
406       return defaultClass;
407     }
408     if (type.getRawType() == TypeToken.class) {
409       // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>.
410       @SuppressWarnings("unchecked")
411       T defaultType = (T) getFirstTypeParameter(type.getType());
412       return defaultType;
413     }
414     if (type.getRawType() == Converter.class) {
415       TypeToken<?> convertFromType = type.resolveType(Converter.class.getTypeParameters()[0]);
416       TypeToken<?> convertToType = type.resolveType(Converter.class.getTypeParameters()[1]);
417       @SuppressWarnings("unchecked") // returns default for both F and T
418       T defaultConverter = (T) defaultConverter(convertFromType, convertToType);
419       return defaultConverter;
420     }
421     if (type.getRawType().isInterface()) {
422       return newDefaultReturningProxy(type);
423     }
424     return null;
425   }
426 
defaultConverter( final TypeToken<F> convertFromType, final TypeToken<T> convertToType)427   private <F, T> Converter<F, T> defaultConverter(
428       final TypeToken<F> convertFromType, final TypeToken<T> convertToType) {
429     return new Converter<F, T>() {
430       @Override
431       protected T doForward(F a) {
432         return doConvert(convertToType);
433       }
434 
435       @Override
436       protected F doBackward(T b) {
437         return doConvert(convertFromType);
438       }
439 
440       private /*static*/ <S> S doConvert(TypeToken<S> type) {
441         return checkNotNull(getDefaultValue(type));
442       }
443     };
444   }
445 
446   private static TypeToken<?> getFirstTypeParameter(Type type) {
447     if (type instanceof ParameterizedType) {
448       return TypeToken.of(((ParameterizedType) type).getActualTypeArguments()[0]);
449     } else {
450       return TypeToken.of(Object.class);
451     }
452   }
453 
454   private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
455     return new DummyProxy() {
456       @Override
457       <R> R dummyReturnValue(TypeToken<R> returnType) {
458         return getDefaultValue(returnType);
459       }
460     }.newProxy(type);
461   }
462 
463   private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
464     if (instance == null) {
465       return Invokable.from(method);
466     } else {
467       return TypeToken.of(instance.getClass()).method(method);
468     }
469   }
470 
471   static boolean isPrimitiveOrNullable(Parameter param) {
472     return param.getType().getRawType().isPrimitive() || isNullable(param);
473   }
474 
475   private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES =
476       ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType");
477 
478   static boolean isNullable(Invokable<?, ?> invokable) {
479     return isNullable(invokable.getAnnotatedReturnType().getAnnotations())
480         || isNullable(invokable.getAnnotations());
481   }
482 
483   static boolean isNullable(Parameter param) {
484     return isNullable(param.getAnnotatedType().getAnnotations())
485         || isNullable(param.getAnnotations());
486   }
487 
488   private static boolean isNullable(Annotation[] annotations) {
489     for (Annotation annotation : annotations) {
490       if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) {
491         return true;
492       }
493     }
494     return false;
495   }
496 
497   private boolean isIgnored(Member member) {
498     return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member);
499   }
500 
501   /**
502    * Returns true if the the given member is a method that overrides {@link Object#equals(Object)}.
503    *
504    * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an
505    * explicit {@code @Nullable} annotation (see <a
506    * href="https://github.com/google/guava/issues/1819">#1819</a>).
507    *
508    * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The
509    * declaration of a method with the same name and formal parameters as {@link Object#equals} that
510    * is not public and boolean-returning, or that declares any type parameters, would be rejected at
511    * compile-time.
512    */
513   private static boolean isEquals(Member member) {
514     if (!(member instanceof Method)) {
515       return false;
516     }
517     Method method = (Method) member;
518     if (!method.getName().contentEquals("equals")) {
519       return false;
520     }
521     Class<?>[] parameters = method.getParameterTypes();
522     if (parameters.length != 1) {
523       return false;
524     }
525     if (!parameters[0].equals(Object.class)) {
526       return false;
527     }
528     return true;
529   }
530 
531   /** Strategy for exception type matching used by {@link NullPointerTester}. */
532   private enum ExceptionTypePolicy {
533 
534     /**
535      * Exceptions should be {@link NullPointerException} or {@link UnsupportedOperationException}.
536      */
537     NPE_OR_UOE() {
538       @Override
539       public boolean isExpectedType(Throwable cause) {
540         return cause instanceof NullPointerException
541             || cause instanceof UnsupportedOperationException;
542       }
543     },
544 
545     /**
546      * Exceptions should be {@link NullPointerException}, {@link IllegalArgumentException}, or
547      * {@link UnsupportedOperationException}.
548      */
549     NPE_IAE_OR_UOE() {
550       @Override
551       public boolean isExpectedType(Throwable cause) {
552         return cause instanceof NullPointerException
553             || cause instanceof IllegalArgumentException
554             || cause instanceof UnsupportedOperationException;
555       }
556     };
557 
558     public abstract boolean isExpectedType(Throwable cause);
559   }
560 }
561