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.AnnotatedElement; 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.util.Arrays; 045import java.util.List; 046import java.util.concurrent.ConcurrentMap; 047import javax.annotation.CheckForNull; 048import junit.framework.Assert; 049import junit.framework.AssertionFailedError; 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 that isn't annotated with an annotation with the simple name {@code Nullable}, {@code 055 * CheckForNull}, {@link NullableType}, or {@link 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 069public final class NullPointerTester { 070 071 private final ClassToInstanceMap<Object> defaults = MutableClassToInstanceMap.create(); 072 private final List<Member> ignoredMembers = Lists.newArrayList(); 073 074 private ExceptionTypePolicy policy = ExceptionTypePolicy.NPE_OR_UOE; 075 076 /** 077 * Sets a default value that can be used for any parameter of type {@code type}. Returns this 078 * object. 079 */ 080 public <T> NullPointerTester setDefault(Class<T> type, T value) { 081 defaults.putInstance(type, checkNotNull(value)); 082 return this; 083 } 084 085 /** 086 * Ignore {@code method} in the tests that follow. Returns this object. 087 * 088 * @since 13.0 089 */ 090 public NullPointerTester ignore(Method method) { 091 ignoredMembers.add(checkNotNull(method)); 092 return this; 093 } 094 095 /** 096 * Ignore {@code constructor} in the tests that follow. Returns this object. 097 * 098 * @since 22.0 099 */ 100 public NullPointerTester ignore(Constructor<?> constructor) { 101 ignoredMembers.add(checkNotNull(constructor)); 102 return this; 103 } 104 105 /** 106 * Runs {@link #testConstructor} on every constructor in class {@code c} that has at least {@code 107 * minimalVisibility}. 108 */ 109 public void testConstructors(Class<?> c, Visibility minimalVisibility) { 110 for (Constructor<?> constructor : c.getDeclaredConstructors()) { 111 if (minimalVisibility.isVisible(constructor) && !isIgnored(constructor)) { 112 testConstructor(constructor); 113 } 114 } 115 } 116 117 /** Runs {@link #testConstructor} on every public constructor in class {@code c}. */ 118 public void testAllPublicConstructors(Class<?> c) { 119 testConstructors(c, Visibility.PUBLIC); 120 } 121 122 /** 123 * Runs {@link #testMethod} on every static method of class {@code c} that has at least {@code 124 * minimalVisibility}, including those "inherited" from superclasses of the same package. 125 */ 126 public void testStaticMethods(Class<?> c, Visibility minimalVisibility) { 127 for (Method method : minimalVisibility.getStaticMethods(c)) { 128 if (!isIgnored(method)) { 129 testMethod(null, method); 130 } 131 } 132 } 133 134 /** 135 * Runs {@link #testMethod} on every public static method of class {@code c}, including those 136 * "inherited" from superclasses of the same package. 137 */ 138 public void testAllPublicStaticMethods(Class<?> c) { 139 testStaticMethods(c, Visibility.PUBLIC); 140 } 141 142 /** 143 * Runs {@link #testMethod} on every instance method of the class of {@code instance} with at 144 * least {@code minimalVisibility}, including those inherited from superclasses of the same 145 * package. 146 */ 147 public void testInstanceMethods(Object instance, Visibility minimalVisibility) { 148 for (Method method : getInstanceMethodsToTest(instance.getClass(), minimalVisibility)) { 149 testMethod(instance, method); 150 } 151 } 152 153 ImmutableList<Method> getInstanceMethodsToTest(Class<?> c, Visibility minimalVisibility) { 154 ImmutableList.Builder<Method> builder = ImmutableList.builder(); 155 for (Method method : minimalVisibility.getInstanceMethods(c)) { 156 if (!isIgnored(method)) { 157 builder.add(method); 158 } 159 } 160 return builder.build(); 161 } 162 163 /** 164 * Runs {@link #testMethod} on every public instance method of the class of {@code instance}, 165 * including those inherited from superclasses of the same package. 166 */ 167 public void testAllPublicInstanceMethods(Object instance) { 168 testInstanceMethods(instance, Visibility.PUBLIC); 169 } 170 171 /** 172 * Verifies that {@code method} produces a {@link NullPointerException} or {@link 173 * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null. 174 * 175 * @param instance the instance to invoke {@code method} on, or null if {@code method} is static 176 */ 177 public void testMethod(@CheckForNull Object instance, Method method) { 178 Class<?>[] types = method.getParameterTypes(); 179 for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { 180 testMethodParameter(instance, method, nullIndex); 181 } 182 } 183 184 /** 185 * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link 186 * UnsupportedOperationException} whenever <i>any</i> of its non-nullable parameters are null. 187 */ 188 public void testConstructor(Constructor<?> ctor) { 189 Class<?> declaringClass = ctor.getDeclaringClass(); 190 checkArgument( 191 Modifier.isStatic(declaringClass.getModifiers()) 192 || declaringClass.getEnclosingClass() == null, 193 "Cannot test constructor of non-static inner class: %s", 194 declaringClass.getName()); 195 Class<?>[] types = ctor.getParameterTypes(); 196 for (int nullIndex = 0; nullIndex < types.length; nullIndex++) { 197 testConstructorParameter(ctor, nullIndex); 198 } 199 } 200 201 /** 202 * Verifies that {@code method} produces a {@link NullPointerException} or {@link 203 * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If 204 * this parameter is marked nullable, this method does nothing. 205 * 206 * @param instance the instance to invoke {@code method} on, or null if {@code method} is static 207 */ 208 public void testMethodParameter( 209 @CheckForNull final Object instance, final Method method, int paramIndex) { 210 method.setAccessible(true); 211 testParameter(instance, invokable(instance, method), paramIndex, method.getDeclaringClass()); 212 } 213 214 /** 215 * Verifies that {@code ctor} produces a {@link NullPointerException} or {@link 216 * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If 217 * this parameter is marked nullable, this method does nothing. 218 */ 219 public void testConstructorParameter(Constructor<?> ctor, int paramIndex) { 220 ctor.setAccessible(true); 221 testParameter(null, Invokable.from(ctor), paramIndex, ctor.getDeclaringClass()); 222 } 223 224 /** Visibility of any method or constructor. */ 225 public enum Visibility { 226 PACKAGE { 227 @Override 228 boolean isVisible(int modifiers) { 229 return !Modifier.isPrivate(modifiers); 230 } 231 }, 232 233 PROTECTED { 234 @Override 235 boolean isVisible(int modifiers) { 236 return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers); 237 } 238 }, 239 240 PUBLIC { 241 @Override 242 boolean isVisible(int modifiers) { 243 return Modifier.isPublic(modifiers); 244 } 245 }; 246 247 abstract boolean isVisible(int modifiers); 248 249 /** Returns {@code true} if {@code member} is visible under {@code this} visibility. */ 250 final boolean isVisible(Member member) { 251 return isVisible(member.getModifiers()); 252 } 253 254 final Iterable<Method> getStaticMethods(Class<?> cls) { 255 ImmutableList.Builder<Method> builder = ImmutableList.builder(); 256 for (Method method : getVisibleMethods(cls)) { 257 if (Invokable.from(method).isStatic()) { 258 builder.add(method); 259 } 260 } 261 return builder.build(); 262 } 263 264 final Iterable<Method> getInstanceMethods(Class<?> cls) { 265 ConcurrentMap<Signature, Method> map = Maps.newConcurrentMap(); 266 for (Method method : getVisibleMethods(cls)) { 267 if (!Invokable.from(method).isStatic()) { 268 map.putIfAbsent(new Signature(method), method); 269 } 270 } 271 return map.values(); 272 } 273 274 private ImmutableList<Method> getVisibleMethods(Class<?> cls) { 275 // Don't use cls.getPackage() because it does nasty things like reading 276 // a file. 277 String visiblePackage = Reflection.getPackageName(cls); 278 ImmutableList.Builder<Method> builder = ImmutableList.builder(); 279 for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) { 280 if (!Reflection.getPackageName(type).equals(visiblePackage)) { 281 break; 282 } 283 for (Method method : type.getDeclaredMethods()) { 284 if (!method.isSynthetic() && isVisible(method)) { 285 builder.add(method); 286 } 287 } 288 } 289 return builder.build(); 290 } 291 } 292 293 private static final class Signature { 294 private final String name; 295 private final ImmutableList<Class<?>> parameterTypes; 296 297 Signature(Method method) { 298 this(method.getName(), ImmutableList.copyOf(method.getParameterTypes())); 299 } 300 301 Signature(String name, ImmutableList<Class<?>> parameterTypes) { 302 this.name = name; 303 this.parameterTypes = parameterTypes; 304 } 305 306 @Override 307 public boolean equals(Object obj) { 308 if (obj instanceof Signature) { 309 Signature that = (Signature) obj; 310 return name.equals(that.name) && parameterTypes.equals(that.parameterTypes); 311 } 312 return false; 313 } 314 315 @Override 316 public int hashCode() { 317 return Objects.hashCode(name, parameterTypes); 318 } 319 } 320 321 /** 322 * Verifies that {@code invokable} produces a {@link NullPointerException} or {@link 323 * UnsupportedOperationException} when the parameter in position {@code paramIndex} is null. If 324 * this parameter is marked nullable, this method does nothing. 325 * 326 * @param instance the instance to invoke {@code invokable} on, or null if {@code invokable} is 327 * static 328 */ 329 private void testParameter( 330 Object instance, Invokable<?, ?> invokable, int paramIndex, Class<?> testedClass) { 331 if (isPrimitiveOrNullable(invokable.getParameters().get(paramIndex))) { 332 return; // there's nothing to test 333 } 334 Object[] params = buildParamList(invokable, paramIndex); 335 try { 336 @SuppressWarnings("unchecked") // We'll get a runtime exception if the type is wrong. 337 Invokable<Object, ?> unsafe = (Invokable<Object, ?>) invokable; 338 unsafe.invoke(instance, params); 339 Assert.fail( 340 "No exception thrown for parameter at index " 341 + paramIndex 342 + " from " 343 + invokable 344 + Arrays.toString(params) 345 + " for " 346 + testedClass); 347 } catch (InvocationTargetException e) { 348 Throwable cause = e.getCause(); 349 if (policy.isExpectedType(cause)) { 350 return; 351 } 352 AssertionFailedError error = 353 new AssertionFailedError( 354 String.format( 355 "wrong exception thrown from %s when passing null to %s parameter at index %s.%n" 356 + "Full parameters: %s%n" 357 + "Actual exception message: %s", 358 invokable, 359 invokable.getParameters().get(paramIndex).getType(), 360 paramIndex, 361 Arrays.toString(params), 362 cause)); 363 error.initCause(cause); 364 throw error; 365 } catch (IllegalAccessException e) { 366 throw new RuntimeException(e); 367 } 368 } 369 370 private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) { 371 ImmutableList<Parameter> params = invokable.getParameters(); 372 Object[] args = new Object[params.size()]; 373 374 for (int i = 0; i < args.length; i++) { 375 Parameter param = params.get(i); 376 if (i != indexOfParamToSetToNull) { 377 args[i] = getDefaultValue(param.getType()); 378 Assert.assertTrue( 379 "Can't find or create a sample instance for type '" 380 + param.getType() 381 + "'; please provide one using NullPointerTester.setDefault()", 382 args[i] != null || isNullable(param)); 383 } 384 } 385 return args; 386 } 387 388 private <T> T getDefaultValue(TypeToken<T> type) { 389 // We assume that all defaults are generics-safe, even if they aren't, 390 // we take the risk. 391 @SuppressWarnings("unchecked") 392 T defaultValue = (T) defaults.getInstance(type.getRawType()); 393 if (defaultValue != null) { 394 return defaultValue; 395 } 396 @SuppressWarnings("unchecked") // All arbitrary instances are generics-safe 397 T arbitrary = (T) ArbitraryInstances.get(type.getRawType()); 398 if (arbitrary != null) { 399 return arbitrary; 400 } 401 if (type.getRawType() == Class.class) { 402 // If parameter is Class<? extends Foo>, we return Foo.class 403 @SuppressWarnings("unchecked") 404 T defaultClass = (T) getFirstTypeParameter(type.getType()).getRawType(); 405 return defaultClass; 406 } 407 if (type.getRawType() == TypeToken.class) { 408 // If parameter is TypeToken<? extends Foo>, we return TypeToken<Foo>. 409 @SuppressWarnings("unchecked") 410 T defaultType = (T) getFirstTypeParameter(type.getType()); 411 return defaultType; 412 } 413 if (type.getRawType() == Converter.class) { 414 TypeToken<?> convertFromType = type.resolveType(Converter.class.getTypeParameters()[0]); 415 TypeToken<?> convertToType = type.resolveType(Converter.class.getTypeParameters()[1]); 416 @SuppressWarnings("unchecked") // returns default for both F and T 417 T defaultConverter = (T) defaultConverter(convertFromType, convertToType); 418 return defaultConverter; 419 } 420 if (type.getRawType().isInterface()) { 421 return newDefaultReturningProxy(type); 422 } 423 return null; 424 } 425 426 private <F, T> Converter<F, T> defaultConverter( 427 final TypeToken<F> convertFromType, final TypeToken<T> convertToType) { 428 return new Converter<F, T>() { 429 @Override 430 protected T doForward(F a) { 431 return doConvert(convertToType); 432 } 433 434 @Override 435 protected F doBackward(T b) { 436 return doConvert(convertFromType); 437 } 438 439 private /*static*/ <S> S doConvert(TypeToken<S> type) { 440 return checkNotNull(getDefaultValue(type)); 441 } 442 }; 443 } 444 445 private static TypeToken<?> getFirstTypeParameter(Type type) { 446 if (type instanceof ParameterizedType) { 447 return TypeToken.of(((ParameterizedType) type).getActualTypeArguments()[0]); 448 } else { 449 return TypeToken.of(Object.class); 450 } 451 } 452 453 private <T> T newDefaultReturningProxy(final TypeToken<T> type) { 454 return new DummyProxy() { 455 @Override 456 <R> R dummyReturnValue(TypeToken<R> returnType) { 457 return getDefaultValue(returnType); 458 } 459 }.newProxy(type); 460 } 461 462 private static Invokable<?, ?> invokable(@CheckForNull Object instance, Method method) { 463 if (instance == null) { 464 return Invokable.from(method); 465 } else { 466 return TypeToken.of(instance.getClass()).method(method); 467 } 468 } 469 470 static boolean isPrimitiveOrNullable(Parameter param) { 471 return param.getType().getRawType().isPrimitive() || isNullable(param); 472 } 473 474 private static final ImmutableSet<String> NULLABLE_ANNOTATION_SIMPLE_NAMES = 475 ImmutableSet.of( 476 "CheckForNull", "Nullable", "NullableDecl", "NullableType", "ParametricNullness"); 477 478 static boolean isNullable(AnnotatedElement e) { 479 for (Annotation annotation : e.getAnnotations()) { 480 if (NULLABLE_ANNOTATION_SIMPLE_NAMES.contains(annotation.annotationType().getSimpleName())) { 481 return true; 482 } 483 } 484 return false; 485 } 486 487 private boolean isIgnored(Member member) { 488 return member.isSynthetic() || ignoredMembers.contains(member) || isEquals(member); 489 } 490 491 /** 492 * Returns true if the given member is a method that overrides {@link Object#equals(Object)}. 493 * 494 * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an 495 * explicit {@code @NullableDecl} annotation (see <a 496 * href="https://github.com/google/guava/issues/1819">#1819</a>). 497 * 498 * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The 499 * declaration of a method with the same name and formal parameters as {@link Object#equals} that 500 * is not public and boolean-returning, or that declares any type parameters, would be rejected at 501 * compile-time. 502 */ 503 private static boolean isEquals(Member member) { 504 if (!(member instanceof Method)) { 505 return false; 506 } 507 Method method = (Method) member; 508 if (!method.getName().contentEquals("equals")) { 509 return false; 510 } 511 Class<?>[] parameters = method.getParameterTypes(); 512 if (parameters.length != 1) { 513 return false; 514 } 515 if (!parameters[0].equals(Object.class)) { 516 return false; 517 } 518 return true; 519 } 520 521 /** Strategy for exception type matching used by {@link NullPointerTester}. */ 522 private enum ExceptionTypePolicy { 523 524 /** 525 * Exceptions should be {@link NullPointerException} or {@link UnsupportedOperationException}. 526 */ 527 NPE_OR_UOE() { 528 @Override 529 public boolean isExpectedType(Throwable cause) { 530 return cause instanceof NullPointerException 531 || cause instanceof UnsupportedOperationException; 532 } 533 }, 534 535 /** 536 * Exceptions should be {@link NullPointerException}, {@link IllegalArgumentException}, or 537 * {@link UnsupportedOperationException}. 538 */ 539 NPE_IAE_OR_UOE() { 540 @Override 541 public boolean isExpectedType(Throwable cause) { 542 return cause instanceof NullPointerException 543 || cause instanceof IllegalArgumentException 544 || cause instanceof UnsupportedOperationException; 545 } 546 }; 547 548 public abstract boolean isExpectedType(Throwable cause); 549 } 550}