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    *      http://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.assertNotSame;
21  import static org.junit.jupiter.api.Assertions.fail;
22  
23  import java.util.regex.Pattern;
24  import java.util.regex.PatternSyntaxException;
25  
26  import org.junit.jupiter.api.Test;
27  
28  /**
29   * Test Case for RegexValidatorTest.
30   *
31   * @since 1.4
32   */
33  public class RegexValidatorTest {
34  
35      private static final String REGEX = "^([abc]*)(?:\\-)([DEF]*)(?:\\-)([123]*)$";
36  
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  
56          // Handle nulls
57          if (expect == null || result == null) {
58              if (expect == null && result == null) {
59                  return; // valid, both null
60              }
61              fail(label + " Null expect=" + expect + " result=" + result);
62              return; // not strictly necessary, but prevents possible NPE below
63          }
64  
65          // Check Length
66          if (expect.length != result.length) {
67              fail(label + " Length expect=" + expect.length + " result=" + result.length);
68          }
69  
70          // Check Values
71          for (int i = 0; i < expect.length; i++) {
72              assertEquals(expect[i], result[i], label + " value[" + i + "]");
73          }
74      }
75  
76      /**
77       * Test exceptions
78       */
79      @Test
80      public void testExceptions() {
81          final String invalidRegex = "^([abCD12]*$";
82          try {
83              new RegexValidator(invalidRegex);
84          } catch (final PatternSyntaxException e) {
85              // expected
86          }
87      }
88  
89      @Test
90      public void testGetPatterns() {
91          final RegexValidator regexValidator = new RegexValidator(MULTIPLE_REGEX);
92          assertNotSame(regexValidator.getPatterns(), regexValidator.getPatterns());
93          final Pattern[] patterns = regexValidator.getPatterns();
94          assertEquals(REGEX_1, patterns[0].pattern());
95          assertEquals(REGEX_2, patterns[1].pattern());
96          assertEquals(REGEX_3, patterns[2].pattern());
97      }
98  
99      /**
100      * Test exceptions
101      */
102     @Test
103     public void testMissingRegex() {
104 
105         // Single Regular Expression - null
106         try {
107             new RegexValidator((String) null);
108             fail("Single Null - expected IllegalArgumentException");
109         } catch (final IllegalArgumentException e) {
110             assertEquals(e.getMessage(), "Regular expression[0] is missing", "Single Null");
111         }
112 
113         // Single Regular Expression - Zero Length
114         try {
115             new RegexValidator("");
116             fail("Single Zero Length - expected IllegalArgumentException");
117         } catch (final IllegalArgumentException e) {
118             assertEquals(e.getMessage(), "Regular expression[0] is missing", "Single Zero Length");
119         }
120 
121         // Multiple Regular Expression - Null array
122         try {
123             new RegexValidator((String[]) null);
124             fail("Null Array - expected IllegalArgumentException");
125         } catch (final IllegalArgumentException e) {
126             assertEquals(e.getMessage(), "Regular expressions are missing", "Null Array");
127         }
128 
129         // Multiple Regular Expression - Zero Length array
130         try {
131             new RegexValidator();
132             fail("Zero Length Array - expected IllegalArgumentException");
133         } catch (final IllegalArgumentException e) {
134             assertEquals(e.getMessage(), "Regular expressions are missing", "Zero Length Array");
135         }
136 
137         // Multiple Regular Expression - Array has Null
138         String[] expressions = { "ABC", null };
139         try {
140             new RegexValidator(expressions);
141             fail("Array has Null - expected IllegalArgumentException");
142         } catch (final IllegalArgumentException e) {
143             assertEquals(e.getMessage(), "Regular expression[1] is missing", "Array has Null");
144         }
145 
146         // Multiple Regular Expression - Array has Zero Length
147         expressions = new String[] { "", "ABC" };
148         try {
149             new RegexValidator(expressions);
150             fail("Array has Zero Length - expected IllegalArgumentException");
151         } catch (final IllegalArgumentException e) {
152             assertEquals(e.getMessage(), "Regular expression[0] is missing", "Array has Zero Length");
153         }
154     }
155 
156     /**
157      * Test with multiple regular expressions (case in-sensitive).
158      */
159     @Test
160     public void testMultipleInsensitive() {
161 
162         // ------------ Set up In-sensitive Validators
163         final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX, false);
164         final RegexValidator single1 = new RegexValidator(REGEX_1, false);
165         final RegexValidator single2 = new RegexValidator(REGEX_2, false);
166         final RegexValidator single3 = new RegexValidator(REGEX_3, false);
167 
168         // ------------ Set up test values
169         String value = "AAC FDE 321";
170         final String expect = "AACFDE321";
171         final String[] array = { "AAC", "FDE", "321" };
172 
173         // isValid()
174         assertEquals(true, multiple.isValid(value), "isValid() Multiple");
175         assertEquals(false, single1.isValid(value), "isValid() 1st");
176         assertEquals(true, single2.isValid(value), "isValid() 2nd");
177         assertEquals(false, single3.isValid(value), "isValid() 3rd");
178 
179         // validate()
180         assertEquals(expect, multiple.validate(value), "validate() Multiple");
181         assertEquals(null, single1.validate(value), "validate() 1st");
182         assertEquals(expect, single2.validate(value), "validate() 2nd");
183         assertEquals(null, single3.validate(value), "validate() 3rd");
184 
185         // match()
186         checkArray("match() Multiple", array, multiple.match(value));
187         checkArray("match() 1st", null, single1.match(value));
188         checkArray("match() 2nd", array, single2.match(value));
189         checkArray("match() 3rd", null, single3.match(value));
190 
191         // All invalid
192         value = "AAC*FDE*321";
193         assertEquals(false, multiple.isValid(value), "isValid() Invalid");
194         assertEquals(null, multiple.validate(value), "validate() Invalid");
195         assertEquals(null, multiple.match(value), "match() Multiple");
196     }
197 
198     /**
199      * Test with multiple regular expressions (case sensitive).
200      */
201     @Test
202     public void testMultipleSensitive() {
203 
204         // ------------ Set up Sensitive Validators
205         final RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX);
206         final RegexValidator single1 = new RegexValidator(REGEX_1);
207         final RegexValidator single2 = new RegexValidator(REGEX_2);
208         final RegexValidator single3 = new RegexValidator(REGEX_3);
209 
210         // ------------ Set up test values
211         String value = "aac FDE 321";
212         final String expect = "aacFDE321";
213         final String[] array = { "aac", "FDE", "321" };
214 
215         // isValid()
216         assertEquals(true, multiple.isValid(value), "Sensitive isValid() Multiple");
217         assertEquals(false, single1.isValid(value), "Sensitive isValid() 1st");
218         assertEquals(true, single2.isValid(value), "Sensitive isValid() 2nd");
219         assertEquals(false, single3.isValid(value), "Sensitive isValid() 3rd");
220 
221         // validate()
222         assertEquals(expect, multiple.validate(value), "Sensitive validate() Multiple");
223         assertEquals(null, single1.validate(value), "Sensitive validate() 1st");
224         assertEquals(expect, single2.validate(value), "Sensitive validate() 2nd");
225         assertEquals(null, single3.validate(value), "Sensitive validate() 3rd");
226 
227         // match()
228         checkArray("Sensitive match() Multiple", array, multiple.match(value));
229         checkArray("Sensitive match() 1st", null, single1.match(value));
230         checkArray("Sensitive match() 2nd", array, single2.match(value));
231         checkArray("Sensitive match() 3rd", null, single3.match(value));
232 
233         // All invalid
234         value = "AAC*FDE*321";
235         assertEquals(false, multiple.isValid(value), "isValid() Invalid");
236         assertEquals(null, multiple.validate(value), "validate() Invalid");
237         assertEquals(null, multiple.match(value), "match() Multiple");
238     }
239 
240     /**
241      * Test Null value
242      */
243     @Test
244     public void testNullValue() {
245 
246         final RegexValidator validator = new RegexValidator(REGEX);
247         assertEquals(false, validator.isValid(null), "Instance isValid()");
248         assertEquals(null, validator.validate(null), "Instance validate()");
249         assertEquals(null, validator.match(null), "Instance match()");
250     }
251 
252     /**
253      * Test instance methods with single regular expression.
254      */
255     @Test
256     public void testSingle() {
257         final RegexValidator sensitive = new RegexValidator(REGEX);
258         final RegexValidator insensitive = new RegexValidator(REGEX, false);
259 
260         // isValid()
261         assertEquals(true, sensitive.isValid("ac-DE-1"), "Sensitive isValid() valid");
262         assertEquals(false, sensitive.isValid("AB-de-1"), "Sensitive isValid() invalid");
263         assertEquals(true, insensitive.isValid("AB-de-1"), "Insensitive isValid() valid");
264         assertEquals(false, insensitive.isValid("ABd-de-1"), "Insensitive isValid() invalid");
265 
266         // validate()
267         assertEquals(sensitive.validate("ac-DE-1"), "acDE1", "Sensitive validate() valid");
268         assertEquals(null, sensitive.validate("AB-de-1"), "Sensitive validate() invalid");
269         assertEquals(insensitive.validate("AB-de-1"), "ABde1", "Insensitive validate() valid");
270         assertEquals(null, insensitive.validate("ABd-de-1"), "Insensitive validate() invalid");
271 
272         // match()
273         checkArray("Sensitive match() valid", new String[] { "ac", "DE", "1" }, sensitive.match("ac-DE-1"));
274         checkArray("Sensitive match() invalid", null, sensitive.match("AB-de-1"));
275         checkArray("Insensitive match() valid", new String[] { "AB", "de", "1" }, insensitive.match("AB-de-1"));
276         checkArray("Insensitive match() invalid", null, insensitive.match("ABd-de-1"));
277         assertEquals(new RegexValidator("^([A-Z]*)$").validate("ABC"), "ABC", "validate one");
278         checkArray("match one", new String[] { "ABC" }, new RegexValidator("^([A-Z]*)$").match("ABC"));
279     }
280 
281     /**
282      * Test toString() method
283      */
284     @Test
285     public void testToString() {
286         final RegexValidator single = new RegexValidator(REGEX);
287         assertEquals(single.toString(), "RegexValidator{" + REGEX + "}", "Single");
288 
289         final RegexValidator multiple = new RegexValidator(REGEX, REGEX);
290         assertEquals(multiple.toString(), "RegexValidator{" + REGEX + "," + REGEX + "}", "Multiple");
291     }
292 
293 }