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