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