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.jspecify.annotations.NullMarked; 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@NullMarked 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 throw new AssertionError( 381 String.format( 382 "wrong exception thrown from %s when passing null to %s parameter at index %s.%n" 383 + "Full parameters: %s%n" 384 + "Actual exception message: %s", 385 invokable, 386 invokable.getParameters().get(paramIndex).getType(), 387 paramIndex, 388 Arrays.toString(params), 389 cause), 390 cause); 391 } catch (IllegalAccessException e) { 392 throw new RuntimeException(e); 393 } 394 } 395 396 private @Nullable Object[] buildParamList( 397 Invokable<?, ?> invokable, int indexOfParamToSetToNull) { 398 ImmutableList<Parameter> params = invokable.getParameters(); 399 @Nullable Object[] args = new Object[params.size()]; 400 401 for (int i = 0; i < args.length; i++) { 402 Parameter param = params.get(i); 403 if (i != indexOfParamToSetToNull) { 404 args[i] = getDefaultValue(param.getType()); 405 Assert.assertTrue( 406 "Can't find or create a sample instance for type '" 407 + param.getType() 408 + "'; please provide one using NullPointerTester.setDefault()", 409 args[i] != null || isNullable(param)); 410 } 411 } 412 return args; 413 } 414 415 private <T> @Nullable T getDefaultValue(TypeToken<T> type) { 416 // We assume that all defaults are generics-safe, even if they aren't, 417 // we take the risk. 418 @SuppressWarnings("unchecked") 419 T defaultValue = (T) defaults.getInstance(type.getRawType()); 420 if (defaultValue != null) { 421 return defaultValue; 422 } 423 @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe 424 T arbitrary = (T) ArbitraryInstances.get(type.getRawType()); 425 if (arbitrary != null) { 426 return arbitrary; 427 } 428 if (type.getRawType() == Class.class) { 429 // If parameter is Class<? extends Foo>, we return Foo.class 430 @SuppressWarnings("unchecked") 431 T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType(); 432 return defaultClass; 433 } 434 if (type.getRawType() == TypeToken.class) { 435 // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>. 436 @SuppressWarnings("unchecked") 437 T defaultType = (T) getFirstTypeParameter(type.getType()); 438 return defaultType; 439 } 440 if (type.getRawType() == Converter.class) { 441 TypeToken<?> convertFromType = type.resolveType(Converter.class.getTypeParameters()[0]); 442 TypeToken<?> convertToType = type.resolveType(Converter.class.getTypeParameters()[1]); 443 @SuppressWarnings("unchecked") // returns default for both F and T 444 T defaultConverter = (T) defaultConverter(convertFromType, convertToType); 445 return defaultConverter; 446 } 447 if (type.getRawType().isInterface()) { 448 return newDefaultReturningProxy(type); 449 } 450 return null; 451 } 452 453 private <F, T> Converter<F, T> defaultConverter( 454 final TypeToken<F> convertFromType, final TypeToken<T> convertToType) { 455 return new Converter<F, T>() { 456 @Override 457 protected T doForward(F a) { 458 return doConvert(convertToType); 459 } 460 461 @Override 462 protected F doBackward(T b) { 463 return doConvert(convertFromType); 464 } 465 466 private /*static*/ <S> S doConvert(TypeToken<S> type) { 467 return checkNotNull(getDefaultValue(type)); 468 } 469 }; 470 } 471 472 private static TypeToken<?> getFirstTypeParameter(Type type) { 473 if (type instanceof ParameterizedType) { 474 return TypeToken.of(((ParameterizedType) type).getActualTypeArguments()[0]); 475 } else { 476 return TypeToken.of(Object.class); 477 } 478 } 479 480 private <T> T newDefaultReturningProxy(final TypeToken<T> type) { 481 return new DummyProxy() { 482 @Override 483 <R> @Nullable R dummyReturnValue(TypeToken<R> returnType) { 484 return getDefaultValue(returnType); 485 } 486 }.newProxy(type); 487 } 488 489 private static Invokable<?, ?> invokable(@Nullable Object instance, Method method) { 490 if (instance == null) { 491 return Invokable.from(method); 492 } else { 493 return TypeToken.of(instance.getClass()).method(method); 494 } 495 } 496 497 static boolean isPrimitiveOrNullable(Parameter param) { 498 return param.getType().getRawType().isPrimitive() || isNullable(param); 499 } 500 501 private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES = 502 ImmutableSet.of("CheckForNull", "Nullable", "NullableDecl", "NullableType"); 503 504 static boolean isNullable(Invokable<?, ?> invokable) { 505 return NULLNESS_ANNOTATION_READER.isNullable(invokable); 506 } 507 508 static boolean isNullable(Parameter param) { 509 return NULLNESS_ANNOTATION_READER.isNullable(param); 510 } 511 512 private static boolean containsNullable(Annotation[] annotations) { 513 for (Annotation annotation : annotations) { 514 if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) { 515 return true; 516 } 517 } 518 return false; 519 } 520 521 private boolean isIgnored(Member member) { 522 return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member); 523 } 524 525 /** 526 * Returns true if the given member is a method that overrides {@link Object#equals(Object)}. 527 * 528 * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an 529 * explicit {@code @NullableDecl} annotation (see <a 530 * href="https://github.com/google/guava/issues/1819">#1819</a>). 531 * 532 * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The 533 * declaration of a method with the same name and formal parameters as {@link Object#equals} that 534 * is not public and boolean-returning, or that declares any type parameters, would be rejected at 535 * compile-time. 536 */ 537 private static boolean isEquals(Member member) { 538 if (!(member instanceof Method)) { 539 return false; 540 } 541 Method method = (Method) member; 542 if (!method.getName().contentEquals("equals")) { 543 return false; 544 } 545 Class<?>[] parameters = method.getParameterTypes(); 546 if (parameters.length != 1) { 547 return false; 548 } 549 if (!parameters[0].equals(Object.class)) { 550 return false; 551 } 552 return true; 553 } 554 555 /** Strategy for exception type matching used by {@link NullPointerTester}. */ 556 private enum ExceptionTypePolicy { 557 558 /** 559 * Exceptions should be {@link NullPointerException} or {@link UnsupportedOperationException}. 560 */ 561 NPE_OR_UOE() { 562 @Override 563 public boolean isExpectedType(Throwable cause) { 564 return cause instanceof NullPointerException 565 || cause instanceof UnsupportedOperationException; 566 } 567 }, 568 569 /** 570 * Exceptions should be {@link NullPointerException}, {@link IllegalArgumentException}, or 571 * {@link UnsupportedOperationException}. 572 */ 573 NPE_IAE_OR_UOE() { 574 @Override 575 public boolean isExpectedType(Throwable cause) { 576 return cause instanceof NullPointerException 577 || cause instanceof IllegalArgumentException 578 || cause instanceof UnsupportedOperationException; 579 } 580 }; 581 582 public abstract boolean isExpectedType(Throwable cause); 583 } 584 585 private static boolean annotatedTypeExists() { 586 try { 587 Class.forName("java.lang.reflect.AnnotatedType"); 588 } catch (ClassNotFoundException e) { 589 return false; 590 } 591 return true; 592 } 593 594 private static final NullnessAnnotationReader NULLNESS_ANNOTATION_READER = 595 annotatedTypeExists() 596 ? NullnessAnnotationReader.FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS 597 : NullnessAnnotationReader.FROM_DECLARATION_ANNOTATIONS_ONLY; 598 599 /** 600 * Looks for declaration nullness annotations and, if supported, type-use nullness annotations. 601 * 602 * <p>Under Android VMs, the methods for retrieving type-use annotations don't exist. This means 603 * that {@link NullPointerTester} may misbehave under Android when used on classes that rely on 604 * type-use annotations. 605 * 606 * <p>Under j2objc, the necessary APIs exist, but some (perhaps all) return stub values, like 607 * empty arrays. Presumably {@link NullPointerTester} could likewise misbehave under j2objc, but I 608 * don't know that anyone uses it there, anyway. 609 */ 610 private enum NullnessAnnotationReader { 611 @SuppressWarnings("Java7ApiChecker") 612 FROM_DECLARATION_AND_TYPE_USE_ANNOTATIONS { 613 @Override 614 boolean isNullable(Invokable<?, ?> invokable) { 615 return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(invokable) 616 ; 617 // TODO(cpovirk): Should we also check isNullableTypeVariable? 618 } 619 620 @Override 621 boolean isNullable(Parameter param) { 622 return FROM_DECLARATION_ANNOTATIONS_ONLY.isNullable(param) 623 ; 624 } 625 }, 626 FROM_DECLARATION_ANNOTATIONS_ONLY { 627 @Override 628 boolean isNullable(Invokable<?, ?> invokable) { 629 return containsNullable(invokable.getAnnotations()); 630 } 631 632 @Override 633 boolean isNullable(Parameter param) { 634 return containsNullable(param.getAnnotations()); 635 } 636 }; 637 638 abstract boolean isNullable(Invokable<?, ?> invokable); 639 640 abstract boolean isNullable(Parameter param); 641 } 642}