1 package emissary.test.util;
2
3 import org.apache.commons.collections4.CollectionUtils;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6
7 import java.util.List;
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
10 import javax.annotation.Nullable;
11
12 import static org.junit.jupiter.api.Assertions.assertFalse;
13 import static org.junit.jupiter.api.Assertions.assertTrue;
14 import static org.junit.jupiter.api.Assertions.fail;
15
16
17
18
19 public final class RegularExpressionTestUtil {
20 private static final Logger logger = LoggerFactory.getLogger(RegularExpressionTestUtil.class);
21
22 private RegularExpressionTestUtil() {}
23
24
25
26
27
28
29
30
31
32
33 public static void testRegexPattern(String regexPatternString, @Nullable List<String> shouldMatch, @Nullable List<String> shouldNotMatch) {
34
35 if (regexPatternString == null || regexPatternString.isBlank()) {
36 fail("The test lacks required parameters.");
37 }
38
39 Pattern subjectUnderTest = Pattern.compile(regexPatternString);
40
41 testRegexPattern(subjectUnderTest, shouldMatch, shouldNotMatch);
42
43 }
44
45
46
47
48
49
50
51
52
53
54 public static void testRegexPattern(Pattern patternUnderTest, @Nullable List<String> shouldMatch, @Nullable List<String> shouldNotMatch) {
55 int fineGrainTestCount = 0;
56 if (patternUnderTest == null || (CollectionUtils.isEmpty(shouldMatch) && CollectionUtils.isEmpty(shouldNotMatch))) {
57 fail("The test lacks required parameters.");
58 }
59
60 if (!CollectionUtils.isEmpty(shouldMatch)) {
61 for (String matchMe : shouldMatch) {
62 Matcher mm = patternUnderTest.matcher(matchMe);
63 assertTrue(mm.find(), String.format(" -- Pattern SHOULD match the regex [%s], but did not: %s", patternUnderTest.pattern(), matchMe));
64 fineGrainTestCount++;
65 }
66 }
67
68 if (!CollectionUtils.isEmpty(shouldNotMatch)) {
69 for (String dontMatchMe : shouldNotMatch) {
70 Matcher dmm = patternUnderTest.matcher(dontMatchMe);
71 assertFalse(dmm.find(),
72 String.format(" -- Pattern SHOULD NOT match the regex[%s], but did: %s", patternUnderTest.pattern(), dontMatchMe));
73 fineGrainTestCount++;
74 }
75 }
76 assertTrue(fineGrainTestCount > 0, "No regex assertions performed.");
77 logger.debug("Successfully asserted {} regex test cases.", fineGrainTestCount);
78 }
79
80
81 }