17
package com.google.common.testing;
19
import static com.google.common.base.Preconditions.checkArgument;
20
import static com.google.common.base.Preconditions.checkNotNull;
22
import com.google.common.annotations.GwtIncompatible;
23
import com.google.common.annotations.J2ktIncompatible;
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 com.google.errorprone.annotations.CanIgnoreReturnValue;
37
import java.lang.annotation.Annotation;
38
import java.lang.reflect.AnnotatedType;
39
import java.lang.reflect.Constructor;
40
import java.lang.reflect.InvocationTargetException;
41
import java.lang.reflect.Member;
42
import java.lang.reflect.Method;
43
import java.lang.reflect.Modifier;
44
import java.lang.reflect.ParameterizedType;
45
import java.lang.reflect.Type;
46
import java.lang.reflect.TypeVariable;
47
import java.util.Arrays;
49
import java.util.concurrent.ConcurrentMap;
50
import junit.framework.Assert;
51
import org.checkerframework.checker.nullness.qual.Nullable;
72
@ElementTypesAreNonnullByDefault
73
public final class NullPointerTester {
75
private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create();
76
private final List<Member> ignoredMembers = Lists.newArrayList();
78
private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE;
80
public NullPointerTester() {
90
ignoredMembers.add(Converter.class.getMethod("apply", Object.class));
91
} catch (NoSuchMethodException shouldBeImpossible) {
100
@CanIgnoreReturnValue
101
public <T> NullPointerTester setDefault(Class<T> type, T value) {
102
defaults.putInstance(type, checkNotNull(value));
111
@CanIgnoreReturnValue
112
public NullPointerTester ignore(Method method) {
113
ignoredMembers.add(checkNotNull(method));
122
@CanIgnoreReturnValue
123
public NullPointerTester ignore(Constructor<?> constructor) {
124
ignoredMembers.add(checkNotNull(constructor));
132
public void testConstructors(Class<?> c, Visibility minimalVisibility) {
133
for (Constructor<?> constructor : c.getDeclaredConstructors()) {
134
if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) {
135
testConstructor(constructor);
141
public void testAllPublicConstructors(Class<?> c) {
142
testConstructors(c, Visibility.PUBLIC);
149
public void testStaticMethods(Class<?> c, Visibility minimalVisibility) {
150
for (Method method : minimalVisibility.getStaticMethods(c)) {
151
if (!isIgnored(method)) {
152
testMethod(null, method);
161
public void testAllPublicStaticMethods(Class<?> c) {
162
testStaticMethods(c, Visibility.PUBLIC);
170
public void testInstanceMethods(Object instance, Visibility minimalVisibility) {
171
for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) {
172
testMethod(instance, method);
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)) {
183
return builder.build();
190
public void testAllPublicInstanceMethods(Object instance) {
191
testInstanceMethods(instance, Visibility.PUBLIC);
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);
211
public void testConstructor(Constructor<?> ctor) {
212
Class<?> declaringClass = ctor.getDeclaringClass();
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);
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());
242
public void testConstructorParameter(Constructor<?> ctor, int paramIndex) {
243
ctor.setAccessible(true);
244
testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass());
248
public enum Visibility {
251
boolean isVisible(int modifiers) {
252
return !Modifier.isPrivate(modifiers);
258
boolean isVisible(int modifiers) {
259
return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
265
boolean isVisible(int modifiers) {
266
return Modifier.isPublic(modifiers);
270
abstract boolean isVisible(int modifiers);
273
final boolean isVisible(Member member) {
274
return isVisible(member.getModifiers());
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()) {
284
return builder.build();
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);
297
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
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)) {
306
for (Method method : type.getDeclaredMethods()) {
307
if (!method.isSynthetic() && isVisible(method)) {
312
return builder.build();
316
private static final class Signature {
317
private final String name;
318
private final ImmutableList<Class<?>> parameterTypes;
320
Signature(Method method) {
321
this(method.getName(), ImmutableList.copyOf(method.getParameterTypes()));
324
Signature(String name, ImmutableList<Class<?>> parameterTypes) {
326
this.parameterTypes = parameterTypes;
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);
339
public int hashCode() {
340
return Objects.hashCode(name, parameterTypes);
352
private void testParameter(
353
@Nullable Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) {
354
if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) {
357
@Nullable Object[] params = buildParamList(invokable, paramIndex);
359
@SuppressWarnings("unchecked")
360
Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable;
361
unsafe.invoke(instance, params);
363
"No exception thrown for parameter at index "
367
+ Arrays.toString(params)
370
} catch (InvocationTargetException e) {
371
Throwable cause = e.getCause();
372
if (policy.isExpectedType(cause)) {
375
throw new AssertionError(
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",
381
invokable.getParameters().get(paramIndex).getType(),
383
Arrays.toString(params),
386
} catch (IllegalAccessException e) {
387
throw new RuntimeException(e);
391
private @Nullable Object[] buildParamList(
392
Invokable<?, ?> invokable, int indexOfParamToSetToNull) {
393
ImmutableList<Parameter> params = invokable.getParameters();
394
@Nullable Object[] args = new Object[params.size()];
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());
401
"Can't find or create a sample instance for type '"
403
+ "'; please provide one using NullPointerTester.setDefault()",
404
args[i] != null || isNullable(param));
410
private <T> @Nullable T getDefaultValue(TypeToken<T> type) {
413
@SuppressWarnings("unchecked")
414
T defaultValue = (T) defaults.getInstance(type.getRawType());
415
if (defaultValue != null) {
418
@SuppressWarnings("unchecked")
419
T arbitrary = (T) ArbitraryInstances.get(type.getRawType());
420
if (arbitrary != null) {
423
if (type.getRawType() == Class.class) {
425
@SuppressWarnings("unchecked")
426
T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType();
429
if (type.getRawType() == TypeToken.class) {
431
@SuppressWarnings("unchecked")
432
T defaultType = (T) getFirstTypeParameter(type.getType());
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")
439
T defaultConverter = (T) defaultConverter(convertFromType, convertToType);
440
return defaultConverter;
442
if (type.getRawType().isInterface()) {
443
return newDefaultReturningProxy(type);
448
private <F, T> Converter<F, T> defaultConverter(
449
final TypeToken<F> convertFromType, final TypeToken<T> convertToType) {
450
return new Converter<F, T>() {
452
protected T doForward(F a) {
453
return doConvert(convertToType);
457
protected F doBackward(T b) {
458
return doConvert(convertFromType);
461
private <S> S doConvert(TypeToken<S> type) {
462
return checkNotNull(getDefaultValue(type));
467
private static TypeToken<?> getFirstTypeParameter(Type type) {
468
if (type instanceof ParameterizedType) {
469
return TypeToken.of(((ParameterizedType) type).getActualTypeArguments()[0]);
471
return TypeToken.of(Object.class);
475
private <T> T newDefaultReturningProxy(final TypeToken<T> type) {
476
return new DummyProxy() {
478
<R> @Nullable R dummyReturnValue(TypeToken<R> returnType) {
479
return getDefaultValue(returnType);
484
private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) {
485
if (instance == null) {
486
return Invokable.from(method);
488
return TypeToken.of(instance.getClass()).method(method);
492
static boolean isPrimitiveOrNullable(Parameter param) {
493
return param.getType().getRawType().isPrimitive() || isNullable(param);
496
private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES =
497
ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType");
499
static boolean isNullable(Invokable<?, ?> invokable) {
500
return NULLNESS_ANNOTATION_READER.isNullable(invokable);
503
static boolean isNullable(Parameter param) {
504
return NULLNESS_ANNOTATION_READER.isNullable(param);
507
private static boolean containsNullable(Annotation[] annotations) {
508
for (Annotation annotation : annotations) {
509
if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) {
516
private boolean isIgnored(Member member) {
517
return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member);
532
private static boolean isEquals(Member member) {
533
if (!(member instanceof Method)) {
536
Method method = (Method) member;
537
if (!method.getName().contentEquals("equals")) {
540
Class<?>[] parameters = method.getParameterTypes();
541
if (parameters.length != 1) {
544
if (!parameters[0].equals(Object.class)) {
551
private enum ExceptionTypePolicy {
558
public boolean isExpectedType(Throwable cause) {
559
return cause instanceof NullPointerException
560
|| cause instanceof UnsupportedOperationException;
570
public boolean isExpectedType(Throwable cause) {
571
return cause instanceof NullPointerException
572
|| cause instanceof IllegalArgumentException
573
|| cause instanceof UnsupportedOperationException;
577
public abstract boolean isExpectedType(Throwable cause);
580
private static boolean annotatedTypeExists() {
582
Class.forName("java.lang.reflect.AnnotatedType");
583
} catch (ClassNotFoundException e) {
589
private static final NullnessAnnotationReader NULLNESS_ANNOTATION_READER =
590
annotatedTypeExists()
591
? NullnessAnnotationReader.FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS
592
: NullnessAnnotationReader.FROM_DECLARATION_ANNOTATIONS_ONLY;
605
private enum NullnessAnnotationReader {
606
@SuppressWarnings("Java7ApiChecker")
607
FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS {
609
boolean isNullable(Invokable<?, ?> invokable) {
610
return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable)
611
|| containsNullable(invokable.getAnnotatedReturnType().getAnnotations());
616
boolean isNullable(Parameter param) {
617
return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param)
618
|| containsNullable(param.getAnnotatedType().getAnnotations())
619
|| isNullableTypeVariable(param.getAnnotatedType().getType());
622
boolean isNullableTypeVariable(Type type) {
623
if (!(type instanceof TypeVariable)) {
626
TypeVariable<?> typeVar = (TypeVariable<?>) type;
627
for (AnnotatedType bound : typeVar.getAnnotatedBounds()) {
630
if (containsNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) {
637
FROM_DECLARATION_ANNOTATIONS_ONLY {
639
boolean isNullable(Invokable<?, ?> invokable) {
640
return containsNullable(invokable.getAnnotations());
644
boolean isNullable(Parameter param) {
645
return containsNullable(param.getAnnotations());
649
abstract boolean isNullable(Invokable<?, ?> invokable);
651
abstract boolean isNullable(Parameter param);