|
| 1 | +package com.appland.appmap.util; |
| 2 | + |
| 3 | +import java.lang.reflect.Method; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.HashSet; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +import org.tinylog.TaggedLogger; |
| 11 | + |
| 12 | +import com.appland.appmap.config.AppMapConfig; |
| 13 | + |
| 14 | +/** |
| 15 | + * Recognizes mock objects, so that recording them doesn't call their methods. |
| 16 | + * |
| 17 | + * <p> |
| 18 | + * Calling a method on a mock is an interaction as far as the mocking framework |
| 19 | + * is concerned, and mocking frameworks keep thread-local state between one call |
| 20 | + * and the next. Mockito, for example, collects argument matchers on a |
| 21 | + * thread-local stack and binds them to the next invocation it sees. A stray |
| 22 | + * {@code toString()} from the agent binds that matcher to the wrong call, so |
| 23 | + * the stubbing the test set up never applies and the test fails with a value |
| 24 | + * the user never configured. |
| 25 | + * |
| 26 | + * <p> |
| 27 | + * Detection goes through the mocking framework's own API, because the class |
| 28 | + * name isn't a reliable signal: Mockito's inline mock maker mocks a class by |
| 29 | + * retransforming it, so a mock of {@code com.example.Foo} is an instance of |
| 30 | + * {@code com.example.Foo}. |
| 31 | + */ |
| 32 | +public class MockDetector { |
| 33 | + private static final TaggedLogger logger = AppMapConfig.getLogger(null); |
| 34 | + |
| 35 | + /** Placeholder recorded in place of a mock's value. */ |
| 36 | + public static final String MOCK_VALUE = "[mocked]"; |
| 37 | + |
| 38 | + /** |
| 39 | + * Types no mock maker will mock, so an instance of one is never a mock. |
| 40 | + * |
| 41 | + * <p> |
| 42 | + * These are the values AppMap records most often, and skipping the lookup for |
| 43 | + * them keeps the common path as cheap as it was before mock detection |
| 44 | + * existed. The list is deliberately conservative -- a type wrongly listed |
| 45 | + * here would reintroduce the bug this class exists to prevent -- and matches |
| 46 | + * what Mockito's {@code MockMaker.isTypeMockable} rejects. Note that enums |
| 47 | + * are absent on purpose: Mockito mocks those quite happily. |
| 48 | + */ |
| 49 | + private static final Set<Class<?>> NEVER_MOCKABLE = new HashSet<Class<?>>(Arrays.asList( |
| 50 | + String.class, |
| 51 | + Class.class, |
| 52 | + Boolean.class, |
| 53 | + Byte.class, |
| 54 | + Character.class, |
| 55 | + Short.class, |
| 56 | + Integer.class, |
| 57 | + Long.class, |
| 58 | + Float.class, |
| 59 | + Double.class)); |
| 60 | + |
| 61 | + /** |
| 62 | + * Mockito's mock-detection API, or null if it can't be reached for a given |
| 63 | + * class. Cached per class, so applications with no mocking framework on the |
| 64 | + * class path pay one {@link ClassValue} read and nothing else. |
| 65 | + */ |
| 66 | + private static final ClassValue<Method[]> MOCKITO = new ClassValue<Method[]>() { |
| 67 | + @Override |
| 68 | + protected Method[] computeValue(Class<?> type) { |
| 69 | + for (ClassLoader loader : candidateLoaders(type)) { |
| 70 | + Method[] api = resolve(loader); |
| 71 | + if (api != null) { |
| 72 | + return api; |
| 73 | + } |
| 74 | + } |
| 75 | + return null; |
| 76 | + } |
| 77 | + }; |
| 78 | + |
| 79 | + /** |
| 80 | + * Class loaders that might be able to see Mockito, most specific first. |
| 81 | + * |
| 82 | + * <p> |
| 83 | + * The object's own loader isn't enough. The inline mock maker mocks a class |
| 84 | + * by retransforming it, so a mock can be an instance of any mockable type -- |
| 85 | + * including a bootstrap type like {@code java.util.ArrayList}, whose loader |
| 86 | + * can't see Mockito at all. |
| 87 | + * |
| 88 | + * <p> |
| 89 | + * Only loaders that are fixed for the lifetime of the JVM are considered, |
| 90 | + * because the result is cached per class. Including the thread context loader |
| 91 | + * would make the cached answer depend on whichever thread happened to record |
| 92 | + * the first value of that type. |
| 93 | + */ |
| 94 | + private static List<ClassLoader> candidateLoaders(Class<?> type) { |
| 95 | + List<ClassLoader> loaders = new ArrayList<ClassLoader>(3); |
| 96 | + addLoader(loaders, type.getClassLoader()); |
| 97 | + addLoader(loaders, MockDetector.class.getClassLoader()); |
| 98 | + try { |
| 99 | + addLoader(loaders, ClassLoader.getSystemClassLoader()); |
| 100 | + } catch (Throwable t) { |
| 101 | + // Can happen very early in startup, or under a security manager. |
| 102 | + logger.debug(t, "couldn't get the system class loader"); |
| 103 | + } |
| 104 | + return loaders; |
| 105 | + } |
| 106 | + |
| 107 | + /** Adds a loader, skipping the bootstrap loader and duplicates. */ |
| 108 | + private static void addLoader(List<ClassLoader> loaders, ClassLoader loader) { |
| 109 | + // The bootstrap loader can't see a mocking framework, so there's no point |
| 110 | + // asking it. |
| 111 | + if (loader != null && !loaders.contains(loader)) { |
| 112 | + loaders.add(loader); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + private static Method[] resolve(ClassLoader loader) { |
| 117 | + try { |
| 118 | + Method mockingDetails = Class.forName("org.mockito.Mockito", false, loader) |
| 119 | + .getMethod("mockingDetails", Object.class); |
| 120 | + Method isMock = Class.forName("org.mockito.MockingDetails", false, loader) |
| 121 | + .getMethod("isMock"); |
| 122 | + return new Method[] {mockingDetails, isMock}; |
| 123 | + } catch (ClassNotFoundException e) { |
| 124 | + // Mockito isn't visible from this loader. Nothing to do, and not worth |
| 125 | + // logging: it's the normal case outside of tests. |
| 126 | + return null; |
| 127 | + } catch (Throwable t) { |
| 128 | + // A Mockito we don't recognize. Degrade to treating objects as |
| 129 | + // non-mocks rather than failing. |
| 130 | + logger.debug(t, "couldn't find Mockito's mock detection API"); |
| 131 | + return null; |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private MockDetector() { |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Checks whether an object is a mock. Only inspects the mocking framework's |
| 140 | + * bookkeeping; never calls a method on {@code o} itself. |
| 141 | + * |
| 142 | + * @param o the object to check, may be null |
| 143 | + * @return true if {@code o} is known to be a mock |
| 144 | + */ |
| 145 | + public static boolean isMock(Object o) { |
| 146 | + if (o == null) { |
| 147 | + return false; |
| 148 | + } |
| 149 | + |
| 150 | + Class<?> type = o.getClass(); |
| 151 | + if (type.isArray() || NEVER_MOCKABLE.contains(type)) { |
| 152 | + return false; |
| 153 | + } |
| 154 | + |
| 155 | + Method[] api = MOCKITO.get(type); |
| 156 | + if (api == null) { |
| 157 | + return false; |
| 158 | + } |
| 159 | + |
| 160 | + try { |
| 161 | + Object details = api[0].invoke(null, o); |
| 162 | + return details != null && Boolean.TRUE.equals(api[1].invoke(details)); |
| 163 | + } catch (Throwable t) { |
| 164 | + // If we can't tell, say no: recording a value is less important than not |
| 165 | + // guessing wrong about the user's objects. |
| 166 | + logger.debug(t, "failed to check whether {} is a mock", type.getName()); |
| 167 | + return false; |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments