| 1 |
package org.jmock.imposters; |
| 2 |
|
| 3 |
import java.lang.reflect.Constructor; |
| 4 |
import java.lang.reflect.InvocationTargetException; |
| 5 |
import java.lang.reflect.Method; |
| 6 |
import java.lang.reflect.Modifier; |
| 7 |
import java.util.HashSet; |
| 8 |
import java.util.Map; |
| 9 |
import java.util.Set; |
| 10 |
import java.util.concurrent.ConcurrentHashMap; |
| 11 |
import java.util.function.Function; |
| 12 |
|
| 13 |
import org.jmock.api.Imposteriser; |
| 14 |
import org.jmock.api.Invocation; |
| 15 |
import org.jmock.api.Invokable; |
| 16 |
import org.jmock.internal.SearchingClassLoader; |
| 17 |
import org.objenesis.Objenesis; |
| 18 |
import org.objenesis.ObjenesisStd; |
| 19 |
|
| 20 |
import net.bytebuddy.ByteBuddy; |
| 21 |
import net.bytebuddy.NamingStrategy; |
| 22 |
import net.bytebuddy.description.modifier.Visibility; |
| 23 |
import net.bytebuddy.dynamic.DynamicType.Builder; |
| 24 |
import net.bytebuddy.dynamic.loading.ClassInjector; |
| 25 |
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy; |
| 26 |
import net.bytebuddy.implementation.FieldAccessor; |
| 27 |
import net.bytebuddy.implementation.MethodDelegation; |
| 28 |
import net.bytebuddy.implementation.bind.annotation.AllArguments; |
| 29 |
import net.bytebuddy.implementation.bind.annotation.FieldValue; |
| 30 |
import net.bytebuddy.implementation.bind.annotation.Origin; |
| 31 |
import net.bytebuddy.implementation.bind.annotation.RuntimeType; |
| 32 |
import net.bytebuddy.implementation.bind.annotation.This; |
| 33 |
import net.bytebuddy.matcher.ElementMatchers; |
| 34 |
|
| 35 |
/** |
| 36 |
* This class lets you imposterise abstract and concrete classes |
| 37 |
* <em>without</em> calling the constructors of the mocked class. |
| 38 |
* |
| 39 |
* @author olibye |
| 40 |
*/ |
| 41 |
public class ByteBuddyClassImposteriser implements Imposteriser { |
| 42 |
|
| 43 |
public static final Imposteriser INSTANCE = new ByteBuddyClassImposteriser(); |
| 44 |
private static final String JMOCK_KEY = "jMock"; |
| 45 |
|
| 46 |
private final Objenesis objenesis = new ObjenesisStd(); |
| 47 |
private final Map<Set<Class<?>>, Class<?>> types = new ConcurrentHashMap<Set<Class<?>>, Class<?>>(); |
| 48 |
|
| 49 |
private ByteBuddyClassImposteriser() { |
| 50 |
} |
| 51 |
|
| 52 |
public boolean canImposterise(Class<?> type) { |
| 53 |
return !type.isPrimitive() && |
| 54 |
!Modifier.isFinal(type.getModifiers()) && |
| 55 |
(type.isInterface() || !toStringMethodIsFinal(type)); |
| 56 |
} |
| 57 |
|
| 58 |
@Override |
| 59 |
public <T> T imposterise(final Invokable mockObject, Class<T> mockedType, Class<?>... ancilliaryTypes) { |
| 60 |
if (!mockedType.isInterface() && toStringMethodIsFinal(mockedType)) { |
| 61 |
throw new IllegalArgumentException(mockedType.getName() + " has a final toString method"); |
| 62 |
} |
| 63 |
|
| 64 |
try { |
| 65 |
setConstructorsAccessible(mockedType, true); |
| 66 |
return proxy(mockObject, mockedType, ancilliaryTypes); |
| 67 |
} finally { |
| 68 |
setConstructorsAccessible(mockedType, false); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
private boolean toStringMethodIsFinal(Class<?> type) { |
| 73 |
try { |
| 74 |
Method toString = type.getMethod("toString"); |
| 75 |
return Modifier.isFinal(toString.getModifiers()); |
| 76 |
|
| 77 |
} catch (SecurityException e) { |
| 78 |
throw new IllegalStateException("not allowed to reflect on toString method", e); |
| 79 |
} catch (NoSuchMethodException e) { |
| 80 |
throw new Error("no public toString method found", e); |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
private void setConstructorsAccessible(Class<?> mockedType, boolean accessible) { |
| 85 |
for (Constructor<?> constructor : mockedType.getDeclaredConstructors()) { |
| 86 |
constructor.setAccessible(accessible); |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
private <T> T proxy( |
| 91 |
final Invokable mockObject, final Class<T> mockedType, final Class<?>... ancilliaryTypes) { |
| 92 |
|
| 93 |
try { |
| 94 |
Set<Class<?>> mockTypeKey = mockTypeKey(mockedType, ancilliaryTypes); |
| 95 |
Class<?> proxyType = types.computeIfAbsent(mockTypeKey, |
| 96 |
new Function<Object, Class<?>>() { |
| 97 |
@Override |
| 98 |
public Class<?> apply(Object t) { |
| 99 |
try { |
| 100 |
return proxyClass(mockObject, mockedType, ancilliaryTypes); |
| 101 |
} catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException |
| 102 |
| NoSuchMethodException e) { |
| 103 |
throw new RuntimeException(e); |
| 104 |
} |
| 105 |
} |
| 106 |
}); |
| 107 |
|
| 108 |
InjectInvokable invokable = (InjectInvokable) objenesis.newInstance(proxyType); |
| 109 |
invokable.setJMock(mockObject); |
| 110 |
return (T) invokable; |
| 111 |
|
| 112 |
} catch (IllegalArgumentException | SecurityException e) { |
| 113 |
throw new RuntimeException("Exception in code generation strategy available", e); |
| 114 |
} |
| 115 |
} |
| 116 |
|
| 117 |
public interface InjectInvokable { |
| 118 |
void setJMock(Invokable invokable); |
| 119 |
Invokable getJMock(); |
| 120 |
} |
| 121 |
|
| 122 |
public static class Interceptor { |
| 123 |
@RuntimeType |
| 124 |
static public Object intercept( |
| 125 |
@This Object receiver, |
| 126 |
@Origin Method method, |
| 127 |
@FieldValue(value=JMOCK_KEY) Invokable invokable, |
| 128 |
@AllArguments Object[] args |
| 129 |
) throws Throwable { |
| 130 |
return invokable.invoke(new Invocation(receiver, method, args)); |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
private Class<?> proxyClass(final Invokable mockObject, final Class<?> mockedType, Class<?>... ancilliaryTypes) |
| 135 |
throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { |
| 136 |
Builder<?> builder = new ByteBuddy() |
| 137 |
.with(new NamingStrategy.SuffixingRandom(JMOCK_KEY, JMOCK_KEY.toLowerCase())) |
| 138 |
.subclass(mockedType) |
| 139 |
.implement(ancilliaryTypes) |
| 140 |
.defineField(JMOCK_KEY, Invokable.class, Visibility.PRIVATE) |
| 141 |
.implement(InjectInvokable.class).intercept(FieldAccessor.ofField(JMOCK_KEY)) |
| 142 |
.method(ElementMatchers.not(ElementMatchers.isDeclaredBy(InjectInvokable.class))) |
| 143 |
.intercept(MethodDelegation.to(Interceptor.class)); |
| 144 |
/* |
| 145 |
.intercept(InvocationHandlerAdapter.of(new InvocationHandler() { |
| 146 |
public Object invoke(Object receiver, Method method, Object[] args) throws Throwable { |
| 147 |
return mockObject.invoke(new Invocation(receiver, method, args)); |
| 148 |
} |
| 149 |
})); |
| 150 |
*/ |
| 151 |
// From |
| 152 |
// https://mydailyjava.blogspot.com/2018/04/jdk-11-and-proxies-in-world-past.html |
| 153 |
ClassLoadingStrategy<ClassLoader> strategy; |
| 154 |
if (ClassInjector.UsingLookup.isAvailable() && !protectedPackageNameSpaces(mockedType) |
| 155 |
&& !defaultPackage(mockedType) |
| 156 |
&& mockedType.getClassLoader() == this.getClass().getClassLoader()) { |
| 157 |
Class<?> methodHandles = Class.forName("java.lang.invoke.MethodHandles"); |
| 158 |
Object lookup = methodHandles.getMethod("lookup").invoke(null); |
| 159 |
Method privateLookupIn = methodHandles.getMethod("privateLookupIn", |
| 160 |
Class.class, |
| 161 |
Class.forName("java.lang.invoke.MethodHandles$Lookup")); |
| 162 |
Object privateLookup = privateLookupIn.invoke(null, mockedType, lookup); |
| 163 |
strategy = ClassLoadingStrategy.UsingLookup.of(privateLookup); |
| 164 |
} else if (ClassInjector.UsingReflection.isAvailable()) { |
| 165 |
strategy = ClassLoadingStrategy.Default.INJECTION; |
| 166 |
} else { |
| 167 |
throw new IllegalStateException("No code generation strategy available"); |
| 168 |
} |
| 169 |
|
| 170 |
Class<?> proxyType = builder.make() |
| 171 |
.load(SearchingClassLoader.combineLoadersOf(mockedType, ancilliaryTypes), strategy) |
| 172 |
.getLoaded(); |
| 173 |
return proxyType; |
| 174 |
} |
| 175 |
|
| 176 |
private Set<Class<?>> mockTypeKey(final Class<?> mockedType, Class<?>... ancilliaryTypes) { |
| 177 |
Set<Class<?>> types = new HashSet<>(); |
| 178 |
types.add(mockedType); |
| 179 |
for (Class<?> class1 : ancilliaryTypes) { |
| 180 |
types.add(class1); |
| 181 |
} |
| 182 |
return types; |
| 183 |
} |
| 184 |
|
| 185 |
private boolean defaultPackage(Class<?> mockedType) { |
| 186 |
return mockedType.getPackage().getName().isEmpty(); |
| 187 |
} |
| 188 |
|
| 189 |
private boolean protectedPackageNameSpaces(Class<?> mockedType) { |
| 190 |
return mockedType.getName().startsWith("java."); |
| 191 |
} |
| 192 |
} |