io.specmatic.core.CheckOnlyPatternKeys.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of specmatic-core Show documentation
Show all versions of specmatic-core Show documentation
Turn your contracts into executable specifications. Contract Driven Development - Collaboratively Design & Independently Deploy MicroServices & MicroFrontends.
package io.specmatic.core
import io.specmatic.core.pattern.Pattern
import io.specmatic.core.pattern.isOptional
import io.specmatic.core.value.StringValue
internal object CheckOnlyPatternKeys: KeyErrorCheck {
override fun validate(pattern: Map, actual: Map): KeyError? {
return validateList(pattern, actual).firstOrNull()
}
override fun validateList(pattern: Map, actual: Map): List {
return pattern.minus("...").keys.filter { key ->
isMissingKey(actual, key)
}.map { it.toMissingKeyError() }
}
override fun validateListCaseInsensitive(
pattern: Map,
actual: Map
): List {
return pattern.minus("...").keys.filter { key ->
isMissingKeyCaseInsensitive(actual, key)
}.map { it.toMissingKeyError() }
}
}
internal fun String.toMissingKeyError(): MissingKeyError {
return MissingKeyError(this)
}
internal fun isMissingKey(jsonObject: Map, key: String) =
when {
isOptional(key) -> false
else -> key !in jsonObject && "$key?" !in jsonObject && "$key:" !in jsonObject
}
internal fun isMissingKeyCaseInsensitive(jsonObject: Map, key: String) =
when {
isOptional(key) -> false
else -> {
val objectWithLowerCaseKeys = jsonObject.mapKeys { it.key.lowercase() }
val lowerCaseKey = key.lowercase()
lowerCaseKey !in objectWithLowerCaseKeys && "$lowerCaseKey?" !in objectWithLowerCaseKeys && "$lowerCaseKey:" !in objectWithLowerCaseKeys
}
}