forked from mockk/mockk
/
RecordingState.kt
206 lines (170 loc) · 6.06 KB
/
RecordingState.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
package io.mockk.impl.recording.states
import io.mockk.Invocation
import io.mockk.Matcher
import io.mockk.MockKException
import io.mockk.RecordedCall
import io.mockk.impl.InternalPlatform
import io.mockk.impl.log.Logger
import io.mockk.impl.recording.CallRound
import io.mockk.impl.recording.CallRoundBuilder
import io.mockk.impl.recording.CommonCallRecorder
import kotlin.math.max
import kotlin.reflect.KClass
abstract class RecordingState(recorder: CommonCallRecorder) : CallRecordingState(recorder) {
val log = recorder.safeToString(Logger<RecordingState>())
private var callRoundBuilder: CallRoundBuilder? = null
private val callRounds = mutableListOf<CallRound>()
override fun round(round: Int, total: Int) {
val builder = callRoundBuilder
if (builder != null) {
callRounds.add(builder.build())
}
callRoundBuilder = recorder.factories.callRoundBuilder()
recorder.childHinter = recorder.factories.childHinter()
if (round == total) {
signMatchers()
workaroundBoxedNumbers()
mockPermanently()
}
}
private fun signMatchers() {
val detector = recorder.factories.signatureMatcherDetector()
detector.detect(callRounds)
recorder.calls.clear()
recorder.calls.addAll(detector.calls)
}
override fun <T : Any> matcher(matcher: Matcher<*>, cls: KClass<T>): T {
val signatureValue = recorder.signatureValueGenerator.signatureValue(
cls,
recorder.anyValueGenerator,
recorder.instantiator,
)
val packRef: Any = InternalPlatform.packRef(signatureValue)
?: error("null packRef for $cls signature $signatureValue")
builder().addMatcher(matcher, packRef)
return signatureValue
}
protected fun addWasNotCalled(list: List<Any>) {
builder().addWasNotCalled(list)
}
override fun call(invocation: Invocation): Any? {
val retType = recorder.childHinter.nextChildType { invocation.method.returnType }
var isTemporaryMock = false
val temporaryMock: () -> Any = {
isTemporaryMock = true
recorder.mockFactory.temporaryMock(retType)
}
val retValue = when {
invocation.method.isToString() -> recorder.stubRepo[invocation.self]?.toStr() ?: ""
retType in CollectionTypes -> temporaryMock()
else -> recorder.anyValueGenerator()
.anyValue(retType, invocation.method.returnTypeNullable, orInstantiateVia = temporaryMock)
}
if (retValue == null) {
isTemporaryMock = false
}
builder().addSignedCall(
retValue,
isTemporaryMock,
retType,
invocation
)
return retValue
}
private fun callIsNumberUnboxing(call: RecordedCall): Boolean {
val matcher = call.matcher
return matcher.self is Number &&
matcher.method.name.endsWith("Value") &&
matcher.method.paramTypes.isEmpty()
}
private fun workaroundBoxedNumbers() {
// issue #36
if (recorder.calls.size == 1) {
return
}
val callsWithoutCasts = recorder.calls.filterNot {
callIsNumberUnboxing(it)
}
if (callsWithoutCasts.size != recorder.calls.size) {
val callsWithCasts = recorder.calls.filter {
callIsNumberUnboxing(it)
}
log.debug { "Removed ${callsWithCasts.size} unboxing calls:\n${callsWithCasts.joinToString("\n")}" }
}
recorder.calls.clear()
recorder.calls.addAll(callsWithoutCasts)
}
fun mockPermanently() {
val mocker = recorder.factories.permanentMocker()
val resultCalls = mocker.mock(recorder.calls)
recorder.calls.clear()
recorder.calls.addAll(resultCalls)
}
override fun nCalls(): Int = callRoundBuilder?.signedCalls?.size ?: 0
override fun isLastCallReturnsNothing(): Boolean {
val lastCall = callRoundBuilder?.signedCalls?.lastOrNull()
?: return false
return lastCall.method.returnsNothing
}
/**
* Main idea is to have enough random information
* to create signature for the argument.
*
* Max 40 calls looks like reasonable compromise
*/
@Suppress("DEPRECATION_ERROR")
override fun estimateCallRounds(): Int {
val regularArguments = builder().signedCalls
.flatMap { it.args }
.filterNotNull()
.map(this::typeEstimation)
.maxOfOrNull { it } ?: 1
val varargArguments = builder().signedCalls
.mapNotNull {
if (it.method.varArgsArg != -1) {
it.method.paramTypes[it.method.varArgsArg]
} else {
null
}
}.map(this::varArgTypeEstimation)
.maxOfOrNull { it } ?: 1
return max(regularArguments, varargArguments)
}
private fun typeEstimation(it: Any): Int {
return when (it::class) {
Boolean::class -> 40
Byte::class -> 8
Char::class -> 4
Short::class -> 4
Int::class -> 2
Float::class -> 2
else -> 1
}
}
private fun varArgTypeEstimation(it: KClass<*>): Int {
return when (it) {
BooleanArray::class -> 40
ByteArray::class -> 8
CharArray::class -> 4
ShortArray::class -> 4
IntArray::class -> 2
FloatArray::class -> 2
else -> 1
}
}
override fun discardLastCallRound() {
callRoundBuilder = null
}
private fun builder(): CallRoundBuilder = callRoundBuilder
?: throw MockKException("Call builder is not initialized. Bad state")
private companion object {
private val CollectionTypes = listOf(
List::class,
Map::class,
Set::class,
ArrayList::class,
HashMap::class,
HashSet::class
)
}
}