/
Matchers.kt
executable file
·353 lines (335 loc) · 13.9 KB
/
Matchers.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package au.com.dius.pact.core.matchers
import au.com.dius.pact.core.matchers.util.IndicesCombination
import au.com.dius.pact.core.matchers.util.LargestKeyValue
import au.com.dius.pact.core.matchers.util.memoizeFixed
import au.com.dius.pact.core.matchers.util.padTo
import au.com.dius.pact.core.model.PathToken
import au.com.dius.pact.core.model.constructPath
import au.com.dius.pact.core.model.matchingrules.ArrayContainsMatcher
import au.com.dius.pact.core.model.matchingrules.EachKeyMatcher
import au.com.dius.pact.core.model.matchingrules.EachValueMatcher
import au.com.dius.pact.core.model.matchingrules.EqualsIgnoreOrderMatcher
import au.com.dius.pact.core.model.matchingrules.EqualsMatcher
import au.com.dius.pact.core.model.matchingrules.MatchingRule
import au.com.dius.pact.core.model.matchingrules.MatchingRuleCategory
import au.com.dius.pact.core.model.matchingrules.MatchingRuleGroup
import au.com.dius.pact.core.model.matchingrules.MaxEqualsIgnoreOrderMatcher
import au.com.dius.pact.core.model.matchingrules.MinEqualsIgnoreOrderMatcher
import au.com.dius.pact.core.model.matchingrules.MinMaxEqualsIgnoreOrderMatcher
import au.com.dius.pact.core.model.matchingrules.ValuesMatcher
import au.com.dius.pact.core.model.parsePath
import au.com.dius.pact.core.support.Either
import io.github.oshai.kotlinlogging.KLogging
import java.math.BigInteger
import java.util.Comparator
@Suppress("TooManyFunctions")
object Matchers : KLogging() {
private fun matchesToken(pathElement: String, token: PathToken): Int {
return when (token) {
is PathToken.Root -> if (pathElement == "$") 2 else 0
is PathToken.Field -> if (pathElement == token.name) 2 else 0
is PathToken.Index -> if (pathElement.toIntOrNull() == token.index) 2 else 0
is PathToken.StarIndex -> if (pathElement.toIntOrNull() != null) 1 else 0
is PathToken.Star -> 1
else -> 0
}
}
fun matchesPath(pathExp: String, path: List<String>): Int {
return matchesPath(parsePath(pathExp), path)
}
private fun matchesPath(pathTokens: List<PathToken>, path: List<String>): Int {
val matchesPath = pathTokens.size <= path.size && pathTokens.indices
.none { index -> matchesToken(path[index], pathTokens[index]) == 0 }
return if (matchesPath) pathTokens.size else 0
}
fun calculatePathWeight(pathExp: String, path: List<String>): Int {
return calculatePathWeight(parsePath(pathExp), path)
}
fun calculatePathWeight(pathTokens: List<PathToken>, path: List<String>): Int {
return path
.zip(pathTokens) { pathElement, pathToken -> matchesToken(pathElement, pathToken) }
.reduce { acc, i -> acc * i }
}
@JvmStatic
@JvmOverloads
@Suppress("LongParameterList")
fun <M : Mismatch> domatch(
context: MatchingContext,
path: List<String>,
expected: Any?,
actual: Any?,
mismatchFn: MismatchFactory<M>,
pathComparator: Comparator<String> = Comparator.naturalOrder()
): List<M> {
val matcherDef = context.selectBestMatcher(path, pathComparator)
return domatch(matcherDef, path, expected, actual, mismatchFn)
}
/**
* Compares the expected and actual maps using the provided matching rule
*/
@Suppress("LongParameterList")
fun <T> compareMaps(
path: List<String>,
matcher: MatchingRule,
expectedEntries: Map<String, T>,
actualEntries: Map<String, T>,
context: MatchingContext,
generateDiff: () -> String,
callback: (List<String>, T?, T?) -> List<BodyItemMatchResult>
): List<BodyItemMatchResult> {
val result = mutableListOf<BodyItemMatchResult>()
if (matcher is ValuesMatcher || matcher is EachValueMatcher) {
actualEntries.entries.forEach { (key, value) ->
if (expectedEntries.containsKey(key)) {
result.addAll(callback(path + key, expectedEntries[key]!!, value))
} else {
result.addAll(callback(path + key, expectedEntries.values.firstOrNull(), value))
}
}
} else {
result.addAll(context.matchKeys(path, expectedEntries, actualEntries, generateDiff))
if (matcher !is EachKeyMatcher) {
expectedEntries.entries.forEach { (key, value) ->
if (actualEntries.containsKey(key)) {
result.addAll(callback(path + key, value, actualEntries[key]))
}
}
}
}
return result
}
@Suppress("LongMethod", "LongParameterList")
fun <T> compareLists(
path: List<String>,
matcher: MatchingRule,
expectedList: List<T>,
actualList: List<T>,
context: MatchingContext,
generateDiff: () -> String,
cascaded: Boolean,
callback: (List<String>, T, T, MatchingContext) -> List<BodyItemMatchResult>
): List<BodyItemMatchResult> {
val result = mutableListOf<BodyItemMatchResult>()
val matchResult = domatch(matcher, path, expectedList, actualList, BodyMismatchFactory, cascaded)
if (matchResult.isNotEmpty()) {
result.add(BodyItemMatchResult(constructPath(path), matchResult))
}
if (expectedList.isNotEmpty()) {
when (matcher) {
is EqualsIgnoreOrderMatcher,
is MinEqualsIgnoreOrderMatcher,
is MaxEqualsIgnoreOrderMatcher,
is MinMaxEqualsIgnoreOrderMatcher -> {
// match unordered list
logger.debug { "compareLists: ignore-order matcher defined for path $path" }
// No need to pad 'expected' as we already visit all 'actual' values
result.addAll(compareListContentUnordered(expectedList, actualList, path, context, generateDiff, callback))
}
is ArrayContainsMatcher -> {
val variants = matcher.variants.ifEmpty {
expectedList.mapIndexed { index, _ ->
Triple(
index,
MatchingRuleCategory("body", mutableMapOf("" to MatchingRuleGroup(mutableListOf(EqualsMatcher)))),
emptyMap()
)
}
}
for ((index, variant) in variants.withIndex()) {
if (index < expectedList.size) {
val expectedValue = expectedList[index]
val newContext = MatchingContext(variant.second, context.allowUnexpectedKeys, context.pluginConfiguration)
val noneMatched = actualList.withIndex().all { (actualIndex, value) ->
val variantResult = callback(listOf("$"), expectedValue, value, newContext)
val mismatches = variantResult.flatMap { it.result }
logger.debug {
"Comparing list item $actualIndex with value '$value' to '$expectedValue' -> " +
"${mismatches.size} mismatches"
}
mismatches.isNotEmpty()
}
if (noneMatched) {
result.add(BodyItemMatchResult(constructPath(path),
listOf(BodyMismatch(expectedValue, actualList,
"Variant at index $index ($expectedValue) was not found in the actual list",
constructPath(path), generateDiff()
))
))
}
} else {
result.add(BodyItemMatchResult(constructPath(path),
listOf(BodyMismatch(expectedList, actualList,
"ArrayContains: variant $index is missing from the expected list, which has " +
"${expectedList.size} items", constructPath(path), generateDiff()
))
))
}
}
}
is EachValueMatcher -> if (!cascaded) {
logger.debug { "Matching $path with EachValue" }
val associatedRules = matcher.definition.rules.mapNotNull {
when (it) {
is Either.A -> it.value
is Either.B -> {
result.add(
BodyItemMatchResult(
constructPath(path),
listOf(
BodyMismatch(
expectedList, actualList,
"Found an un-resolved reference ${it.value.name}", constructPath(path), generateDiff()
)
)
)
)
null
}
}
}
val matcherPath = constructPath(path) + ".*"
val newContext = MatchingContext(
MatchingRuleCategory("body", mutableMapOf(
matcherPath to MatchingRuleGroup(associatedRules.toMutableList())
)),
context.allowUnexpectedKeys,
context.pluginConfiguration
)
result.addAll(compareListContent(expectedList.padTo(actualList.size, expectedList.first()),
actualList, path, newContext, generateDiff, callback))
}
else -> {
result.addAll(compareListContent(expectedList.padTo(actualList.size, expectedList.first()),
actualList, path, context, generateDiff, callback))
}
}
}
return result
}
/**
* Compares any "extra" actual elements to expected
*/
@Suppress("LongParameterList")
private fun <T> compareActualElements(
path: List<String>,
actualIndex: Int,
expectedValues: List<T>,
actual: T,
context: MatchingContext,
callback: (List<String>, T, T, MatchingContext) -> List<BodyItemMatchResult>
): List<BodyItemMatchResult> {
val indexPath = path + actualIndex.toString()
return if (context.directMatcherDefined(indexPath)) {
callback(indexPath, expectedValues[0], actual, context)
} else {
emptyList()
}
}
/**
* Compares every permutation of actual against expected.
*/
@Suppress("LongParameterList")
fun <T> compareListContentUnordered(
expectedList: List<T>,
actualList: List<T>,
path: List<String>,
context: MatchingContext,
generateDiff: () -> String,
callback: (List<String>, T, T, MatchingContext) -> List<BodyItemMatchResult>
): List<BodyItemMatchResult> {
val memoizedActualCompare = { actualIndex: Int ->
compareActualElements(path, actualIndex, expectedList, actualList[actualIndex], context, callback)
}.memoizeFixed(actualList.size)
val memoizedCompare = { expectedIndex: Int, actualIndex: Int ->
callback(path + expectedIndex.toString(), expectedList[expectedIndex], actualList[actualIndex], context)
}.memoizeFixed(expectedList.size, actualList.size)
val longestMatch = LargestKeyValue<Int, IndicesCombination>()
val examinedActualIndicesCombos = HashSet<BigInteger>()
/**
* Determines if a matching permutation exists.
*
* Note: this algorithm seems to have a worst case O(n*2^n) time and O(2^n) space complexity
* if a lot of the actuals match a lot of the expected (e.g., if expected uses regex matching
* with something like [3|2|1, 2|1, 1]). Without the caching, the time complexity jumps to
* around O(2^2n). Caching/memoization is also used above for compare, to effectively achieve
* just O(n^2) calls instead of O(2^n).
*
* For most normal cases, average performance should be closer to O(n^2) time and O(n) space
* complexity if there aren't many duplicate matches. Best case is O(n)/O(n) if its already
* in order.
*
* @param expectedIndex index of expected being compared against
* @param actualIndices combination of remaining actual indices to compare
*/
fun hasMatchingPermutation(
expectedIndex: Int = 0,
actualIndices: IndicesCombination = IndicesCombination.of(actualList.size)
): Boolean {
return if (actualIndices.comboId in examinedActualIndicesCombos) {
false
} else {
examinedActualIndicesCombos.add(actualIndices.comboId)
longestMatch.useIfLarger(expectedIndex, actualIndices)
when {
expectedIndex < expectedList.size -> {
actualIndices.indices().any { actualIndex ->
memoizedCompare(expectedIndex, actualIndex).all {
it.result.isEmpty()
} && hasMatchingPermutation(expectedIndex + 1, actualIndices - actualIndex)
}
}
actualList.size > expectedList.size -> {
actualIndices.indices().all { actualIndex ->
memoizedActualCompare(actualIndex).all {
it.result.isEmpty()
}
}
}
else -> true
}
}
}
return if (hasMatchingPermutation()) {
emptyList()
} else {
val smallestCombo = longestMatch.value ?: IndicesCombination.of(actualList.size)
val longestMatch = longestMatch.key ?: 0
val remainingErrors = smallestCombo.indices().map { actualIndex ->
(longestMatch until expectedList.size).map { expectedIndex ->
memoizedCompare(expectedIndex, actualIndex).flatMap { it.result }
}.flatten() + if (actualList.size > expectedList.size) {
memoizedActualCompare(actualIndex).flatMap { it.result }
} else emptyList()
}.toList().flatten()
.groupBy { it.path }
.map { (path, mismatches) -> BodyItemMatchResult(path, mismatches) }
listOf(BodyItemMatchResult(constructPath(path),
listOf(BodyMismatch(expectedList, actualList,
"Expected $expectedList to match $actualList ignoring order of elements",
constructPath(path), generateDiff()
))
)) + remainingErrors
}
}
fun <T> compareListContent(
expectedList: List<T>,
actualList: List<T>,
path: List<String>,
context: MatchingContext,
generateDiff: () -> String,
callback: (List<String>, T, T, MatchingContext) -> List<BodyItemMatchResult>
): List<BodyItemMatchResult> {
val result = mutableListOf<BodyItemMatchResult>()
for ((index, value) in expectedList.withIndex()) {
if (index < actualList.size) {
result.addAll(callback(path + index.toString(), value, actualList[index], context))
} else if (!context.matcherDefined(path)) {
result.add(BodyItemMatchResult(constructPath(path),
listOf(BodyMismatch(expectedList, actualList,
"Expected $value but was missing",
constructPath(path), generateDiff()))))
}
}
return result
}
}