From 75079add6232ed40d2dccb97f622d56f8359e2ce Mon Sep 17 00:00:00 2001 From: Samy Date: Mon, 18 Nov 2024 18:18:12 +0530 Subject: [PATCH] Updated Default Example Match Condition To the Top --- .../specmatic/core/pattern/StringPattern.kt | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/core/src/main/kotlin/io/specmatic/core/pattern/StringPattern.kt b/core/src/main/kotlin/io/specmatic/core/pattern/StringPattern.kt index 317d90b01..3c1f35029 100644 --- a/core/src/main/kotlin/io/specmatic/core/pattern/StringPattern.kt +++ b/core/src/main/kotlin/io/specmatic/core/pattern/StringPattern.kt @@ -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> { val minLengthExample: ReturnValue? = minLength?.let { HasValue(ExactValuePattern(StringValue(randomString(it))), "minimum length string")