From 9707ea51280ddd6b4d324a7cc25522c149000a50 Mon Sep 17 00:00:00 2001 From: Guy Burton Date: Sun, 14 Jul 2013 10:39:23 +0100 Subject: [PATCH] Added test for optional regex capture group handling. Corrected behaviour of JdkPatternArgumentMatcher to pass null for Argument offset rather than -1 for omitted optional parameter. --- .../cucumber/runtime/JdkPatternArgumentMatcher.java | 3 ++- .../runtime/JdkPatternArgumentMatcherTest.java | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/cucumber/runtime/JdkPatternArgumentMatcher.java b/core/src/main/java/cucumber/runtime/JdkPatternArgumentMatcher.java index 7cd1d5e00d..c19cec9029 100644 --- a/core/src/main/java/cucumber/runtime/JdkPatternArgumentMatcher.java +++ b/core/src/main/java/cucumber/runtime/JdkPatternArgumentMatcher.java @@ -19,7 +19,8 @@ public List argumentsFrom(String stepName) { if (matcher.lookingAt()) { List arguments = new ArrayList(matcher.groupCount()); for (int i = 1; i <= matcher.groupCount(); i++) { - arguments.add(new Argument(matcher.start(i), matcher.group(i))); + int startIndex = matcher.start(i); + arguments.add(new Argument(startIndex == -1 ? null : startIndex, matcher.group(i))); } return arguments; } else { diff --git a/core/src/test/java/cucumber/runtime/JdkPatternArgumentMatcherTest.java b/core/src/test/java/cucumber/runtime/JdkPatternArgumentMatcherTest.java index d7fb9e5eb1..09d7e9ddd1 100644 --- a/core/src/test/java/cucumber/runtime/JdkPatternArgumentMatcherTest.java +++ b/core/src/test/java/cucumber/runtime/JdkPatternArgumentMatcherTest.java @@ -47,6 +47,19 @@ public void shouldDealWithAnchoredPattern() { assertEquals(1, matcher.argumentsFrom("I wait for 30 seconds").size()); } + @Test + public void canHandleVariableNumberOfArguments() { + JdkPatternArgumentMatcher matcher = new JdkPatternArgumentMatcher(Pattern.compile("I wait for (.+) seconds|I wait for some time")); + + List arguments = matcher.argumentsFrom("I wait for 30 seconds to be sure"); + List optionalArguments = matcher.argumentsFrom("I wait for some time"); + + assertEquals(1, arguments.size()); + assertEquals(1, optionalArguments.size()); + assertNull(matcher.argumentsFrom("I wait for some time").get(0).getOffset()); + assertNull(matcher.argumentsFrom("I wait for some time").get(0).getVal()); + } + private void assertVariables(String regex, String string, String v1, Integer pos1, String v2, Integer pos2) throws UnsupportedEncodingException { List args = new JdkPatternArgumentMatcher(Pattern.compile(regex)).argumentsFrom(string); assertEquals(2, args.size());