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