-
-
Notifications
You must be signed in to change notification settings - Fork 332
/
ProxyMaker.kt
220 lines (190 loc) · 7.15 KB
/
ProxyMaker.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package io.mockk.proxy.jvm
import io.mockk.proxy.*
import io.mockk.proxy.common.CancelableResult
import io.mockk.proxy.common.transformation.InlineInstrumentation
import io.mockk.proxy.common.transformation.TransformationRequest
import io.mockk.proxy.common.transformation.TransformationType.SIMPLE
import io.mockk.proxy.jvm.transformation.SubclassInstrumentation
import java.lang.reflect.Method
import java.lang.reflect.Modifier
internal class ProxyMaker(
private val log: MockKAgentLogger,
private val inliner: InlineInstrumentation?,
private val subclasser: SubclassInstrumentation,
private val instantiator: MockKInstantiatior,
private val handlers: MutableMap<Any, MockKInvocationHandler>
) : MockKProxyMaker {
override fun <T : Any> proxy(
clazz: Class<T>,
interfaces: Array<Class<*>>,
handler: MockKInvocationHandler,
useDefaultConstructor: Boolean,
instance: Any?
): Cancelable<T> {
throwIfNotPossibleToProxy(clazz, interfaces)
val cancellation = inline(clazz)
val result = CancelableResult<T>(cancelBlock = cancellation)
val proxyClass = try {
subclass(clazz, interfaces)
} catch (ex: Exception) {
result.cancel()
throw MockKAgentException("Failed to subclass $clazz", ex)
}
try {
val proxy = instantiate(clazz, proxyClass, useDefaultConstructor, instance)
handlers[proxy] = handler
return result
.withValue(proxy)
.alsoOnCancel {
handlers.remove(proxy)
}
} catch (e: Exception) {
result.cancel()
throw MockKAgentException("Instantiation exception", e)
}
}
private fun <T : Any> instantiate(
clazz: Class<T>,
proxyClass: Class<T>,
useDefaultConstructor: Boolean,
instance: Any?
): T {
return when {
instance != null -> {
log.trace("Attaching to object mock for $clazz")
clazz.cast(instance)
}
useDefaultConstructor -> {
log.trace("Instantiating proxy for $clazz via default constructor")
clazz.cast(newInstanceViaDefaultConstructor(proxyClass))
}
else -> {
log.trace("Instantiating proxy for $clazz via instantiator")
instantiator.instance(proxyClass)
}
}
}
private fun <T : Any> inline(
clazz: Class<T>
): () -> Unit {
val superclasses = getAllSuperclasses(clazz)
return if (inliner != null) {
val transformRequest = TransformationRequest(superclasses, SIMPLE)
inliner.execute(transformRequest)
} else {
if (!Modifier.isFinal(clazz.modifiers)) {
warnOnFinalMethods(clazz)
}
{}
}
}
private fun <T : Any> subclass(
clazz: Class<T>,
interfaces: Array<Class<*>>
): Class<T> {
val kClass = clazz.kotlin
return if (kClass.isFinal) {
log.trace("Taking instance of $clazz itself because it is final.")
clazz
} else if (interfaces.isEmpty() && !kClass.isAbstract && inliner != null) {
log.trace("Taking instance of $clazz itself because it is not abstract and no additional interfaces specified.")
clazz
} else if (kClass.isSealed) {
log.trace("Taking instance of subclass of $clazz because it is sealed.")
kClass.sealedSubclasses.firstNotNullOfOrNull {
@Suppress("UNCHECKED_CAST")
subclass(it.java, interfaces) as Class<T>
} ?: error("Unable to create proxy for sealed class $clazz, available subclasses: ${kClass.sealedSubclasses}")
} else {
log.trace(
"Building subclass proxy for $clazz with " +
"additional interfaces ${interfaces.toList()}"
)
subclasser.subclass(clazz, interfaces)
}
}
private fun <T : Any> throwIfNotPossibleToProxy(
clazz: Class<T>,
interfaces: Array<Class<*>>
) {
when {
clazz.isPrimitive ->
throw MockKAgentException(
"Failed to create proxy for $clazz.\n$clazz is a primitive"
)
clazz.isArray ->
throw MockKAgentException(
"Failed to create proxy for $clazz.\n$clazz is an array"
)
clazz as Class<*> in notMockableClasses ->
throw MockKAgentException(
"Failed to create proxy for $clazz.\n$clazz is one of excluded classes"
)
interfaces.isNotEmpty() && Modifier.isFinal(clazz.modifiers) ->
throw MockKAgentException(
"Failed to create proxy for $clazz.\nMore interfaces requested and class is final."
)
}
}
private fun newInstanceViaDefaultConstructor(cls: Class<*>): Any {
try {
val defaultConstructor = cls.getDeclaredConstructor()
try {
defaultConstructor.isAccessible = true
} catch (ignored: Exception) {
// skip
}
return defaultConstructor.newInstance()
} catch (e: Exception) {
throw MockKAgentException("Default constructor instantiation exception", e)
}
}
private fun warnOnFinalMethods(clazz: Class<*>) {
for (method in gatherAllMethods(clazz)) {
val modifiers = method.modifiers
if (!Modifier.isPrivate(modifiers) && Modifier.isFinal(modifiers)) {
log.debug(
"It is impossible to intercept calls to $method " +
"for ${method.declaringClass} because it is final"
)
}
}
}
companion object {
private val notMockableClasses = setOf(
Class::class.java,
Boolean::class.java,
Byte::class.java,
Short::class.java,
Char::class.java,
Int::class.java,
Long::class.java,
Float::class.java,
Double::class.java,
String::class.java
)
private fun gatherAllMethods(clazz: Class<*>): Array<Method> =
if (clazz.superclass == null) {
clazz.declaredMethods
} else {
gatherAllMethods(clazz.superclass) + clazz.declaredMethods
}
private fun getAllSuperclasses(cls: Class<*>): Set<Class<*>> {
val result = mutableSetOf<Class<*>>()
var clazz = cls
while (true) {
result.add(clazz)
addInterfaces(result, clazz)
clazz = clazz.superclass ?: break
}
return result
}
private fun addInterfaces(result: MutableSet<Class<*>>, clazz: Class<*>) {
for (intf in clazz.interfaces) {
if (result.add(intf)) {
addInterfaces(result, intf)
}
}
}
}
}