Escapes any special chars; fixes gh-1635

This commit is contained in:
Marcin Grzejszczak
2021-11-23 09:35:29 +01:00
parent 4b44f300b5
commit 6da8e89a39
3 changed files with 49 additions and 2 deletions

View File

@@ -36,7 +36,7 @@ abstract class PatternValueDslProperty<T extends DslProperty> implements RegexCr
boolean matches = pattern.matcher(generatedValue).matches();
if (!matches) {
throw new IllegalStateException("The generated value [" + generatedValue
+ "] doesn\'t match the pattern [" + pattern.pattern() + "]");
+ "] doesn't match the pattern [" + pattern.pattern() + "]");
}
return createProperty(pattern, object);

View File

@@ -23,6 +23,8 @@ import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.contract.spec.util.RegexpUtils;
/**
* Contains most common regular expression patterns.
*
@@ -87,7 +89,7 @@ public final class RegexPatterns {
"([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\\.\\d+)?(Z|[+-][01]\\d:[0-5]\\d)");
protected static Pattern anyOf(String... values) {
return Pattern.compile(Arrays.stream(values).map(it -> '^' + it + '$').collect(Collectors.joining("|")));
return Pattern.compile(Arrays.stream(values).map(it -> '^' + RegexpUtils.escapeSpecialRegexWithSingleEscape(it) + '$').collect(Collectors.joining("|")));
}
public static String multipartParam(Object name, Object value) {

View File

@@ -21,6 +21,7 @@ import org.junit.Rule
import org.spockframework.runtime.extension.builtin.PreconditionContext
import spock.lang.IgnoreIf
import spock.lang.Issue
import spock.lang.Retry
import spock.lang.Shared
import spock.lang.Specification
@@ -2127,4 +2128,48 @@ response:
}
}
@Issue("1635")
def 'should work with anyOf that contains special chars'() {
given:
Contract contractDsl = Contract.make {
name 'anyOf test'
request {
method 'POST'
url ("hello")
body(
type: anyOf("VAL", "VAL+VAL")
)
}
response {
status OK()
}
}
methodBuilder()
when:
String test = singleTestGenerator(contractDsl)
then:
SyntaxChecker.tryToCompileWithoutCompileStatic(methodBuilderName, test)
and:
!test.contains('singleValue')
and:
stubMappingIsValidWireMockStub(contractDsl)
where:
methodBuilderName | methodBuilder
"spock" | {
properties.testFramework = TestFramework.SPOCK
}
"mockmvc" | {
properties.testMode = TestMode.MOCKMVC
}
"jaxrs-spock" | {
properties.testFramework = TestFramework.SPOCK; properties.testMode = TestMode.JAXRSCLIENT
}
"jaxrs" | {
properties.testFramework = TestFramework.JUNIT; properties.testMode = TestMode.JAXRSCLIENT
}
"testNG" | {
properties.testFramework = TestFramework.TESTNG
}
}
}