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.AnnotatedElement; 38 import java.lang.reflect.Constructor; 39 import java.lang.reflect.InvocationTargetException; 40 import java.lang.reflect.Member; 41 import java.lang.reflect.Method; 42 import java.lang.reflect.Modifier; 43 import java.lang.reflect.ParameterizedType; 44 import java.lang.reflect.Type; 45 import java.util.Arrays; 46 import java.util.List; 47 import java.util.concurrent.ConcurrentMap; 48 import junit.framework.Assert; 49 import junit.framework.AssertionFailedError; 50 import org.checkerframework.checker.nullness.compatqual.NullableDecl; 51 52 /** 53 * A test utility that verifies that your methods and constructors throw {@link 54 * NullPointerException} or {@link UnsupportedOperationException} whenever null is passed to a 55 * parameter that isn't annotated with an annotation with the simple name {@code Nullable}, {@lcode 56 * CheckForNull}, {@link NullableType}, or {@link NullableDecl}. 57 * 58 * <p>The tested methods and constructors are invoked -- each time with one parameter being null and 59 * the rest not null -- and the test fails if no expected exception is thrown. {@code 60 * NullPointerTester} uses best effort to pick non-null default values for many common JDK and Guava 61 * types, and also for interfaces and public classes that have public parameter-less constructors. 62 * When the non-null default value for a particular parameter type cannot be provided by {@code 63 * NullPointerTester}, the caller can provide a custom non-null default value for the parameter type 64 * via {@link #setDefault}. 65 * 66 * @author Kevin Bourrillion 67 * @since 10.0 68 */ 69 @Beta 70 @GwtIncompatible 71 public final class NullPointerTester { 72 73 private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create(); 74 private final List<Member> ignoredMembers = Lists.newArrayList(); 75 76 private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE; 77 78 /** 79 * Sets a default value that can be used for any parameter of type {@code type}. Returns this 80 * object. 81 */ setDefault(Class<T> type, T value)82 public <T> NullPointerTester setDefault(Class<T> type, T value) { 83 defaults.putInstance(type, checkNotNull(value)); 84 return this; 85 } 86 87 /** 88 * Ignore {@code method} in the tests that follow. Returns this object. 89 * 90 * @since 13.0 91 */ ignore(Method method)92 public NullPointerTester ignore(Method method) { 93 ignoredMembers.add(checkNotNull(method)); 94 return this; 95 } 96 97 /** 98 * Ignore {@code constructor} in the tests that follow. Returns this object. 99 * 100 * @since 22.0 101 */ ignore(Constructor<?> constructor)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 */ testConstructors(Class<?> c, Visibility minimalVisibility)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}. */ testAllPublicConstructors(Class<?> 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 */ testStaticMethods(Class<?> c, Visibility minimalVisibility)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 */ testAllPublicStaticMethods(Class<?> c)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 */ testInstanceMethods(Object instance, Visibility minimalVisibility)149 public void testInstanceMethods(Object instance, Visibility minimalVisibility) { 150 for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) { 151 testMethod(instance, method); 152 } 153 } 154 getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility)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 */ testAllPublicInstanceMethods(Object instance)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 */ testMethod(@ullableDecl Object instance, Method method)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 */ testConstructor(Constructor<?> ctor)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 */ testMethodParameter( @ullableDecl final Object instance, final Method method, int paramIndex)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 */ testConstructorParameter(Constructor<?> ctor, int paramIndex)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 isVisible(int modifiers)230 boolean isVisible(int modifiers) { 231 return !Modifier.isPrivate(modifiers); 232 } 233 }, 234 235 PROTECTED { 236 @Override isVisible(int modifiers)237 boolean isVisible(int modifiers) { 238 return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers); 239 } 240 }, 241 242 PUBLIC { 243 @Override isVisible(int modifiers)244 boolean isVisible(int modifiers) { 245 return Modifier.isPublic(modifiers); 246 } 247 }; 248 isVisible(int modifiers)249 abstract boolean isVisible(int modifiers); 250 251 /** Returns {@code true} if {@code member} is visible under {@code this} visibility. */ isVisible(Member member)252 final boolean isVisible(Member member) { 253 return isVisible(member.getModifiers()); 254 } 255 getStaticMethods(Class<?> cls)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 getInstanceMethods(Class<?> cls)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 getVisibleMethods(Class<?> cls)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 Signature(Method method)299 Signature(Method method) { 300 this(method.getName(), ImmutableList.copyOf(method.getParameterTypes())); 301 } 302 Signature(String name, ImmutableList<Class<?>> parameterTypes)303 Signature(String name, ImmutableList<Class<?>> parameterTypes) { 304 this.name = name; 305 this.parameterTypes = parameterTypes; 306 } 307 308 @Override equals(Object obj)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 hashCode()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 */ testParameter( Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass)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 buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull)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 getDefaultValue(TypeToken<T> type)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 defaultConverter( final TypeToken<F> convertFromType, final TypeToken<T> convertToType)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 } 552