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.base.Converter; 024import com.google.common.base.Objects; 025import com.google.common.collect.ClassToInstanceMap; 026import com.google.common.collect.ImmutableList; 027import com.google.common.collect.ImmutableSet; 028import com.google.common.collect.Lists; 029import com.google.common.collect.Maps; 030import com.google.common.collect.MutableClassToInstanceMap; 031import com.google.common.reflect.Invokable; 032import com.google.common.reflect.Parameter; 033import com.google.common.reflect.Reflection; 034import com.google.common.reflect.TypeToken; 035import java.lang.annotation.Annotation; 036import java.lang.reflect.AnnotatedType; 037import java.lang.reflect.Constructor; 038import java.lang.reflect.InvocationTargetException; 039import java.lang.reflect.Member; 040import java.lang.reflect.Method; 041import java.lang.reflect.Modifier; 042import java.lang.reflect.ParameterizedType; 043import java.lang.reflect.Type; 044import java.lang.reflect.TypeVariable; 045import java.util.Arrays; 046import java.util.List; 047import java.util.concurrent.ConcurrentMap; 048import java.util.function.Function; 049import junit.framework.Assert; 050import junit.framework.AssertionFailedError; 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}, {@link NullableType}, or {@link 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 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(@Nullable 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 @Nullable 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(@Nullable 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( 478 "CheckForNull", "Nullable", "NullableDecl", "NullableType", "ParametricNullness"); 479 480 static boolean isNullable(Invokable<?, ?> invokable) { 481 return isNullable(invokable.getAnnotatedReturnType().getAnnotations()) 482 || isNullable(invokable.getAnnotations()); 483 } 484 485 static boolean isNullable(Parameter param) { 486 return isNullable(param.getAnnotatedType().getAnnotations()) 487 || isNullable(param.getAnnotations()) 488 || isNullableTypeVariable(param.getAnnotatedType().getType()); 489 } 490 491 private static boolean isNullableTypeVariable(Type type) { 492 if (!(type instanceof TypeVariable)) { 493 return false; 494 } 495 TypeVariable<?> var = (TypeVariable<?>) type; 496 AnnotatedType[] bounds = GET_ANNOTATED_BOUNDS.apply(var); 497 for (AnnotatedType bound : bounds) { 498 // Until Java 15, the isNullableTypeVariable case here won't help: 499 // https://bugs.openjdk.java.net/browse/JDK-8202469 500 if (isNullable(bound.getAnnotations()) || isNullableTypeVariable(bound.getType())) { 501 return true; 502 } 503 } 504 return false; 505 } 506 507 private static boolean isNullable(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 // This is currently required because of j2objc restrictions. 517 private static final Function<TypeVariable<?>, AnnotatedType[]> GET_ANNOTATED_BOUNDS = 518 initGetAnnotatedBounds(); 519 520 private static Function<TypeVariable<?>, AnnotatedType[]> initGetAnnotatedBounds() { 521 AnnotatedType[] noBounds = new AnnotatedType[0]; 522 Method getAnnotatedBounds; 523 try { 524 getAnnotatedBounds = TypeVariable.class.getMethod("getAnnotatedBounds"); 525 } catch (ReflectiveOperationException e) { 526 return v -> noBounds; 527 } 528 return v -> { 529 try { 530 return (AnnotatedType[]) getAnnotatedBounds.invoke(v); 531 } catch (ReflectiveOperationException e) { 532 return noBounds; 533 } 534 }; 535 } 536 537 private boolean isIgnored(Member member) { 538 return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member); 539 } 540 541 /** 542 * Returns true if the given member is a method that overrides {@link Object#equals(Object)}. 543 * 544 * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an 545 * explicit {@code @Nullable} annotation (see <a 546 * href="https://github.com/google/guava/issues/1819">#1819</a>). 547 * 548 * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The 549 * declaration of a method with the same name and formal parameters as {@link Object#equals} that 550 * is not public and boolean-returning, or that declares any type parameters, would be rejected at 551 * compile-time. 552 */ 553 private static boolean isEquals(Member member) { 554 if (!(member instanceof Method)) { 555 return false; 556 } 557 Method method = (Method) member; 558 if (!method.getName().contentEquals("equals")) { 559 return false; 560 } 561 Class<?>[] parameters = method.getParameterTypes(); 562 if (parameters.length != 1) { 563 return false; 564 } 565 if (!parameters[0].equals(Object.class)) { 566 return false; 567 } 568 return true; 569 } 570 571 /** Strategy for exception type matching used by {@link NullPointerTester}. */ 572 private enum ExceptionTypePolicy { 573 574 /** 575 * Exceptions should be {@link NullPointerException} or {@link UnsupportedOperationException}. 576 */ 577 NPE_OR_UOE() { 578 @Override 579 public boolean isExpectedType(Throwable cause) { 580 return cause instanceof NullPointerException 581 || cause instanceof UnsupportedOperationException; 582 } 583 }, 584 585 /** 586 * Exceptions should be {@link NullPointerException}, {@link IllegalArgumentException}, or 587 * {@link UnsupportedOperationException}. 588 */ 589 NPE_IAE_OR_UOE() { 590 @Override 591 public boolean isExpectedType(Throwable cause) { 592 return cause instanceof NullPointerException 593 || cause instanceof IllegalArgumentException 594 || cause instanceof UnsupportedOperationException; 595 } 596 }; 597 598 public abstract boolean isExpectedType(Throwable cause); 599 } 600}