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