Skip to content

Commit

Permalink
karatelabs#1533 add a condition to avoid removal of '?' in regex vali…
Browse files Browse the repository at this point in the history
…dation
  • Loading branch information
Alessandro Ruzzon committed Mar 22, 2021
1 parent dd7a65c commit c504a1a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
*/
public class MatchOperation {

public static final String REGEX = "regex";

final Match.Context context;
final Match.Type type;
final Match.Value actual;
Expand Down Expand Up @@ -317,7 +319,8 @@ private boolean macroEqualsExpected(String expStr) {
} else { // '#? _ != 0' | '#string' | '#number? _ > 0'
int questionPos = macro.indexOf('?');
String validatorName = null;
if (questionPos != -1) {
// in case of regex we don't want to remove the '?'
if (questionPos != -1 && !macro.startsWith(REGEX)) {
validatorName = macro.substring(0, questionPos);
if (macro.length() > questionPos + 1) {
macro = StringUtils.trimToEmpty(macro.substring(questionPos + 1));
Expand All @@ -332,7 +335,7 @@ private boolean macroEqualsExpected(String expStr) {
if (validatorName != null) {
Match.Validator validator = null;

if (validatorName.startsWith("regex")) {
if (validatorName.startsWith(REGEX)) {
String regex = validatorName.substring(5).trim();
validator = new Match.RegexValidator(regex);
} else {
Expand All @@ -352,7 +355,7 @@ private boolean macroEqualsExpected(String expStr) {
return fail(mr.message);
}
}
} else if (!validatorName.startsWith("regex")) { // expected is a string that happens to start with "#"
} else if (!validatorName.startsWith(REGEX)) { // expected is a string that happens to start with "#"
String actualValue = actual.getValue();
switch (type) {
case CONTAINS:
Expand Down
7 changes: 7 additions & 0 deletions karate-core/src/test/java/com/intuit/karate/MatchTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,13 @@ void testApiUsage() {
Match.that("{ a: 1, b: 2, c: { d: 3, e: 4} }").containsDeep("{ b: 2, c: { e: 4 } }");
}

@Test
void testRegex() {
match("{ number: '/en/search?q=test' }", EQUALS, "{ number: '#regex /\\\\w{2}/search\\\\?q=(.*)+' }");
match("{ number: '/us/search?q=test' }", EQUALS, "{ number: '#regex /\\\\w{2}/search\\\\?q=(.*)+' }");
match("{ number: '/en/search?q=test+whatever' }", EQUALS, "{ number: '#regex /\\\\w{2}/search\\\\?q=(.*)+' }");
}

@Test
void testOptional() {
match("{ number: '1234' }", EQUALS, "{ number: '##regex \\\\d+' }");
Expand Down

0 comments on commit c504a1a

Please sign in to comment.