From c504a1a1613aca663069b5675e3de4fda73838dd Mon Sep 17 00:00:00 2001 From: Alessandro Ruzzon Date: Mon, 22 Mar 2021 21:23:46 +0100 Subject: [PATCH] #1533 add a condition to avoid removal of '?' in regex validation --- .../src/main/java/com/intuit/karate/MatchOperation.java | 9 ++++++--- .../src/test/java/com/intuit/karate/MatchTest.java | 7 +++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/karate-core/src/main/java/com/intuit/karate/MatchOperation.java b/karate-core/src/main/java/com/intuit/karate/MatchOperation.java index 6bdbe540d..61915506e 100644 --- a/karate-core/src/main/java/com/intuit/karate/MatchOperation.java +++ b/karate-core/src/main/java/com/intuit/karate/MatchOperation.java @@ -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; @@ -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)); @@ -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 { @@ -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: diff --git a/karate-core/src/test/java/com/intuit/karate/MatchTest.java b/karate-core/src/test/java/com/intuit/karate/MatchTest.java index 1c5b633cb..80be7ced0 100644 --- a/karate-core/src/test/java/com/intuit/karate/MatchTest.java +++ b/karate-core/src/test/java/com/intuit/karate/MatchTest.java @@ -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+' }");