View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.validator.routines;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertFalse;
21  import static org.junit.jupiter.api.Assertions.assertNotSame;
22  import static org.junit.jupiter.api.Assertions.assertNull;
23  import static org.junit.jupiter.api.Assertions.assertThrows;
24  import static org.junit.jupiter.api.Assertions.assertTrue;
25  import static org.junit.jupiter.api.Assertions.fail;
26  
27  import java.util.regex.Pattern;
28  import java.util.regex.PatternSyntaxException;
29  
30  import org.junit.jupiter.api.Test;
31  
32  /**
33   * Test Case for RegexValidatorTest.
34   */
35  class RegexValidatorTest {
36      private static final String REGEX = "^([abc]*)(?:\\-)([DEF]*)(?:\\-)([123]*)$";
37      private static final String COMPONENT_1 = "([abc]{3})";
38      private static final String COMPONENT_2 = "([DEF]{3})";
39      private static final String COMPONENT_3 = "([123]{3})";
40      private static final String SEPARATOR_1 = "(?:\\-)";
41      private static final String SEPARATOR_2 = "(?:\\s)";
42      private static final String REGEX_1 = "^" + COMPONENT_1 + SEPARATOR_1 + COMPONENT_2 + SEPARATOR_1 + COMPONENT_3 + "$";
43      private static final String REGEX_2 = "^" + COMPONENT_1 + SEPARATOR_2 + COMPONENT_2 + SEPARATOR_2 + COMPONENT_3 + "$";
44      private static final String REGEX_3 = "^" + COMPONENT_1 + COMPONENT_2 + COMPONENT_3 + "$";
45      private static final String[] MULTIPLE_REGEX = { REGEX_1, REGEX_2, REGEX_3 };
46  
47      /**
48       * Compare two arrays
49       *
50       * @param label  Label for the test
51       * @param expect Expected array
52       * @param result Actual array
53       */
54      private void checkArray(final String label, final String[] expect, final String[] result) {
55          // Handle nulls
56          if (expect == null || result == null) {
57              if (expect == null && result == null) {
58                  return; // valid, both null
59              }
60              fail(label + " Null expect=" + expect + " result=" + result);
61              return; // not strictly necessary, but prevents possible NPE below
62          }
63          // Check Length
64          if (expect.length != result.length) {
65              fail(label + " Length expect=" + expect.length + " result=" + result.length);
66          }
67          // Check Values
68          for (int i = 0; i < expect.length; i++) {
69              assertEquals(expect[i], result[i], label + " value[" + i + "]");
70          }
71      }
72  
73      /**
74       * Test exceptions
75       */
76      @Test
77      void testExceptions() {
78          assertThrows(PatternSyntaxException.class, () -> new RegexValidator("^([abCD12]*$"));
79      }
80  
81      @Test
82      void testGetPatterns() {
83          final RegexValidator regexValidator = new RegexValidator(MULTIPLE_REGEX);
84          assertNotSame(regexValidator.getPatterns(), regexValidator.getPatterns());
85          final Pattern[] patterns = regexValidator.getPatterns();
86          assertEquals(REGEX_1, patterns[0].pattern());
87          assertEquals(REGEX_2, patterns[1].pattern());
88          assertEquals(REGEX_3, patterns[2].pattern());
89      }
90  
91      /**
92       * Test exceptions
93       */
94      @Test
95      void testMissingRegex() {
96          // Single Regular Expression - null
97          Exception e = assertThrows(IllegalArgumentException.class, () -> new RegexValidator((String) null), "Single Null");
98          assertEquals("Regular expression[0] is missing", e.getMessage(), "Single Null");
99          // Single Regular Expression - Zero Length
100         e = assertThrows(IllegalArgumentException.class, () -> new RegexValidator(""), "Single Zero Length");
101         assertEquals("Regular expression[0] is missing", e.getMessage(), "Single Zero Length");
102         // Multiple Regular Expression - Null array
103         e = assertThrows(IllegalArgumentException.class, () -> new RegexValidator((String[]) null), "Null Array");
104         assertEquals("Regular expressions are missing", e.getMessage(), "Null Array");
105         // Multiple Regular Expression - Zero Length array
106         e = assertThrows(IllegalArgumentException.class, RegexValidator::new, "Zero Length Array");
107         assertEquals("Regular expressions are missing", e.getMessage(), "Zero Length Array");
108         // Multiple Regular Expression - Array has Null
109         e = assertThrows(IllegalArgumentException.class, () -> new RegexValidator(new String[] { "ABC", null }), "Array has Null");
110         assertEquals("Regular expression[1] is missing", e.getMessage(), "Array has Null");
111         // Multiple Regular Expression - Array has Zero Length
112         e = assertThrows(IllegalArgumentException.class, () -> new RegexValidator(new String[] { "", "ABC" }), "Array has Zero Length");
113         assertEquals("Regular expression[0] is missing", e.getMessage(), "Array has Zero Length");
114     }
115 
116     /**
117      * Test with multiple regular expressions (case in-sensitive).
118      */
119     @Test
120     void testMultipleInsensitive() {
121         // Set up In-sensitive Validators
122         final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX, false);
123         final RegexValidator single1 = new RegexValidator(REGEX_1, false);
124         final RegexValidator single2 = new RegexValidator(REGEX_2, false);
125         final RegexValidator single3 = new RegexValidator(REGEX_3, false);
126         // Set up test values
127         String value = "AAC FDE 321";
128         final String expect = "AACFDE321";
129         final String[] array = { "AAC", "FDE", "321" };
130         // isValid()
131         assertTrue(multiple.isValid(value), "isValid() Multiple");
132         assertFalse(single1.isValid(value), "isValid() 1st");
133         assertTrue(single2.isValid(value), "isValid() 2nd");
134         assertFalse(single3.isValid(value), "isValid() 3rd");
135         // validate()
136         assertEquals(expect, multiple.validate(value), "validate() Multiple");
137         assertNull(single1.validate(value), "validate() 1st");
138         assertEquals(expect, single2.validate(value), "validate() 2nd");
139         assertNull(single3.validate(value), "validate() 3rd");
140         // match()
141         checkArray("match() Multiple", array, multiple.match(value));
142         checkArray("match() 1st", null, single1.match(value));
143         checkArray("match() 2nd", array, single2.match(value));
144         checkArray("match() 3rd", null, single3.match(value));
145         // All invalid
146         value = "AAC*FDE*321";
147         assertFalse(multiple.isValid(value), "isValid() Invalid");
148         assertNull(multiple.validate(value), "validate() Invalid");
149         assertNull(multiple.match(value), "match() Multiple");
150     }
151 
152     /**
153      * Test with multiple regular expressions (case sensitive).
154      */
155     @Test
156     void testMultipleSensitive() {
157         // Set up Sensitive Validators
158         final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX);
159         final RegexValidator single1 = new RegexValidator(REGEX_1);
160         final RegexValidator single2 = new RegexValidator(REGEX_2);
161         final RegexValidator single3 = new RegexValidator(REGEX_3);
162         // Set up test values
163         String value = "aac FDE 321";
164         final String expect = "aacFDE321";
165         final String[] array = { "aac", "FDE", "321" };
166         // isValid()
167         assertTrue(multiple.isValid(value), "Sensitive isValid() Multiple");
168         assertFalse(single1.isValid(value), "Sensitive isValid() 1st");
169         assertTrue(single2.isValid(value), "Sensitive isValid() 2nd");
170         assertFalse(single3.isValid(value), "Sensitive isValid() 3rd");
171         // validate()
172         assertEquals(expect, multiple.validate(value), "Sensitive validate() Multiple");
173         assertNull(single1.validate(value), "Sensitive validate() 1st");
174         assertEquals(expect, single2.validate(value), "Sensitive validate() 2nd");
175         assertNull(single3.validate(value), "Sensitive validate() 3rd");
176         // match()
177         checkArray("Sensitive match() Multiple", array, multiple.match(value));
178         checkArray("Sensitive match() 1st", null, single1.match(value));
179         checkArray("Sensitive match() 2nd", array, single2.match(value));
180         checkArray("Sensitive match() 3rd", null, single3.match(value));
181         // All invalid
182         value = "AAC*FDE*321";
183         assertFalse(multiple.isValid(value), "isValid() Invalid");
184         assertNull(multiple.validate(value), "validate() Invalid");
185         assertNull(multiple.match(value), "match() Multiple");
186     }
187 
188     /**
189      * Test Null value
190      */
191     @Test
192     void testNullValue() {
193         final RegexValidator validator = new RegexValidator(REGEX);
194         assertFalse(validator.isValid(null), "Instance isValid()");
195         assertNull(validator.validate(null), "Instance validate()");
196         assertNull(validator.match(null), "Instance match()");
197     }
198 
199     /**
200      * Test instance methods with single regular expression.
201      */
202     @Test
203     void testSingle() {
204         final RegexValidator sensitive = new RegexValidator(REGEX);
205         final RegexValidator insensitive = new RegexValidator(REGEX, false);
206         // isValid()
207         assertTrue(sensitive.isValid("ac-DE-1"), "Sensitive isValid() valid");
208         assertFalse(sensitive.isValid("AB-de-1"), "Sensitive isValid() invalid");
209         assertTrue(insensitive.isValid("AB-de-1"), "Insensitive isValid() valid");
210         assertFalse(insensitive.isValid("ABd-de-1"), "Insensitive isValid() invalid");
211         // validate()
212         assertEquals("acDE1", sensitive.validate("ac-DE-1"), "Sensitive validate() valid");
213         assertNull(sensitive.validate("AB-de-1"), "Sensitive validate() invalid");
214         assertEquals("ABde1", insensitive.validate("AB-de-1"), "Insensitive validate() valid");
215         assertNull(insensitive.validate("ABd-de-1"), "Insensitive validate() invalid");
216         // match()
217         checkArray("Sensitive match() valid", new String[] { "ac", "DE", "1" }, sensitive.match("ac-DE-1"));
218         checkArray("Sensitive match() invalid", null, sensitive.match("AB-de-1"));
219         checkArray("Insensitive match() valid", new String[] { "AB", "de", "1" }, insensitive.match("AB-de-1"));
220         checkArray("Insensitive match() invalid", null, insensitive.match("ABd-de-1"));
221         assertEquals("ABC", new RegexValidator("^([A-Z]*)$").validate("ABC"), "validate one");
222         checkArray("match one", new String[] { "ABC" }, new RegexValidator("^([A-Z]*)$").match("ABC"));
223     }
224 
225     /**
226      * Test toString() method
227      */
228     @Test
229     void testToString() {
230         final RegexValidator single = new RegexValidator(REGEX);
231         assertEquals("RegexValidator{" + REGEX + "}", single.toString(), "Single");
232         final RegexValidator multiple = new RegexValidator(REGEX, REGEX);
233         assertEquals("RegexValidator{" + REGEX + "," + REGEX + "}", multiple.toString(), "Multiple");
234     }
235 }