Skip to content

Commit

Permalink
Updated Default Example Match Condition To the Top
Browse files Browse the repository at this point in the history
  • Loading branch information
Samy authored and Samy committed Nov 18, 2024
1 parent 63a8fad commit 75079ad
Showing 1 changed file with 18 additions and 18 deletions.
36 changes: 18 additions & 18 deletions core/src/main/kotlin/io/specmatic/core/pattern/StringPattern.kt
Original file line number Diff line number Diff line change
Expand Up @@ -77,29 +77,29 @@ StringPattern (
}

override fun generate(resolver: Resolver): Value {
val defaultExample: Value? = resolver.resolveExample(example, this)
val defaultExample = resolver.resolveExample(example, this)

return if (regex != null) {
handleRegex(defaultExample,resolver)
} else {
defaultExample?.takeIf { it is StringValue }
?: StringValue(randomString(patternMinLength))
// Validate the default example
defaultExample?.let {
if (matches(it, resolver).isSuccess()) {
return it
}
throw ContractException("Schema example ${it.toStringLiteral()} does not match pattern $regex")
}

// Generate a value based on regex or length constraints
return regex?.let { generateFromRegex() } ?: StringValue(randomString(patternMinLength))
}
private fun handleRegex(defaultExample: Value?,resolver: Resolver): Value {
if (defaultExample == null) {
val cleanedRegex = regex!!.removePrefix("^").removeSuffix("$")
val randomValue = maxLength?.let {
Generex(cleanedRegex).random(patternMinLength, it)
} ?: Generex(cleanedRegex).random(patternMinLength)
return StringValue(randomValue)
}
if (matches(defaultExample, resolver).isSuccess()) {
return defaultExample
}
throw ContractException("Schema example ${defaultExample.toStringLiteral()} does not match pattern $regex")

private fun generateFromRegex(): Value {
val cleanedRegex = regex!!.removePrefix("^").removeSuffix("$")
val generatedValue = maxLength?.let {
Generex(cleanedRegex).random(patternMinLength, it)
} ?: Generex(cleanedRegex).random(patternMinLength)
return StringValue(generatedValue)
}


override fun newBasedOn(row: Row, resolver: Resolver): Sequence<ReturnValue<Pattern>> {
val minLengthExample: ReturnValue<Pattern>? = minLength?.let {
HasValue(ExactValuePattern(StringValue(randomString(it))), "minimum length string")
Expand Down

0 comments on commit 75079ad

Please sign in to comment.