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