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;
18  
19  import java.text.DateFormat;
20  import java.text.ParseException;
21  import java.util.ArrayList;
22  import java.util.Date;
23  import java.util.List;
24  import java.util.Locale;
25  
26  import junit.framework.Test;
27  import junit.framework.TestCase;
28  import junit.framework.TestSuite;
29  
30  import org.apache.commons.validator.util.ValidatorUtils;
31                                                            
32  /***                                                       
33   * Performs Validation Test.
34   *
35   * @version $Revision: 478334 $ $Date: 2006-11-22 21:31:54 +0000 (Wed, 22 Nov 2006) $
36   */
37  public class ValidatorTest extends TestCase {            
38                                                            
39     public ValidatorTest(String name) {                  
40         super(name);                                      
41     }                                                     
42  
43     /***
44      * Start the tests. 
45      *
46      * @param theArgs the arguments. Not used
47      */
48     public static void main(String[] theArgs) {
49         junit.awtui.TestRunner.main(new String[] {ValidatorTest.class.getName()});
50     }
51  
52     /***
53      * @return a test suite (<code>TestSuite</code>) that includes all methods
54      *         starting with "test"
55      */
56     public static Test suite() {
57         // All methods starting with "test" will be executed in the test suite.
58         return new TestSuite(ValidatorTest.class);
59     }
60  
61     protected void setUp() {
62     }
63  
64     protected void tearDown() {
65     }
66  
67     /***
68      * Verify that one value generates an error and the other passes.  The validation 
69      * method being tested returns an object (<code>null</code> will be considered an error).
70      */
71     public void testManualObject() {
72  		//     property name of the method we are validating
73  		String property = "date";
74  		// name of ValidatorAction
75  		String action = "date";
76          ValidatorResources resources = setupDateResources(property, action);
77  
78        TestBean bean = new TestBean();  
79        bean.setDate("2/3/1999");
80        
81        Validator validator = new Validator(resources, "testForm");
82        validator.setParameter(Validator.BEAN_PARAM, bean);
83  
84        try {
85           ValidatorResults results = validator.validate();
86           
87           assertNotNull("Results are null.", results);
88           
89           ValidatorResult result = results.getValidatorResult(property);
90           
91           assertNotNull("Results are null.", results);
92           
93           assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action));
94           
95           assertTrue("Validation of the date formatting has failed.", result.isValid(action));
96        } catch (Exception e) {
97           fail("An exception was thrown while calling Validator.validate()");
98        }
99  
100       bean.setDate("2/30/1999");
101       
102       try {
103          ValidatorResults results = validator.validate();
104          
105          assertNotNull("Results are null.", results);
106          
107          ValidatorResult result = results.getValidatorResult(property);
108          
109          assertNotNull("Results are null.", results);
110          
111          assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action));
112          
113          assertTrue("Validation of the date formatting has passed when it should have failed.", !result.isValid(action));
114       } catch (Exception e) {
115          fail("An exception was thrown while calling Validator.validate()");
116       }
117 
118    }
119    
120    public void testOnlyReturnErrors() throws ValidatorException {
121     	//     property name of the method we are validating
122     	String property = "date";
123     	// name of ValidatorAction
124     	String action = "date";
125     	ValidatorResources resources = setupDateResources(property, action);
126     
127     	TestBean bean = new TestBean();
128     	bean.setDate("2/3/1999");
129     
130     	Validator validator = new Validator(resources, "testForm");
131     	validator.setParameter(Validator.BEAN_PARAM, bean);
132     
133     	ValidatorResults results = validator.validate();
134     
135     	assertNotNull(results);
136     
137         // Field passed and should be in results
138     	assertTrue(results.getPropertyNames().contains(property));
139         
140         // Field passed but should not be in results
141         validator.setOnlyReturnErrors(true);
142         results = validator.validate();
143         assertFalse(results.getPropertyNames().contains(property));    
144    }
145    
146    public void testOnlyValidateField() throws ValidatorException {
147     	//     property name of the method we are validating
148     	String property = "date";
149     	// name of ValidatorAction
150     	String action = "date";
151     	ValidatorResources resources = setupDateResources(property, action);
152     
153     	TestBean bean = new TestBean();
154     	bean.setDate("2/3/1999");
155     
156     	Validator validator = new Validator(resources, "testForm", property);
157     	validator.setParameter(Validator.BEAN_PARAM, bean);
158     
159     	ValidatorResults results = validator.validate();
160     
161     	assertNotNull(results);
162     
163         // Field passed and should be in results
164     	assertTrue(results.getPropertyNames().contains(property));
165    }
166    
167    
168     private ValidatorResources setupDateResources(String property, String action) {
169     
170     	ValidatorResources resources = new ValidatorResources();
171     
172     	ValidatorAction va = new ValidatorAction();
173     	va.setName(action);
174     	va.setClassname("org.apache.commons.validator.ValidatorTest");
175     	va.setMethod("formatDate");
176     	va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");
177     
178     	FormSet fs = new FormSet();
179     	Form form = new Form();
180     	form.setName("testForm");
181     	Field field = new Field();
182     	field.setProperty(property);
183     	field.setDepends(action);
184     	form.addField(field);
185     	fs.addForm(form);
186     
187     	resources.addValidatorAction(va);
188     	resources.addFormSet(fs);
189     	resources.process();
190     
191     	return resources;
192     }
193                                                           
194    /***
195     * Verify that one value generates an error and the other passes.  The validation 
196     * method being tested returns a <code>boolean</code> value.
197     */
198    public void testManualBoolean() {
199       ValidatorResources resources = new ValidatorResources();
200 
201       ValidatorAction va = new ValidatorAction();
202       va.setName("capLetter");
203       va.setClassname("org.apache.commons.validator.ValidatorTest");
204       va.setMethod("isCapLetter");
205       va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List");
206       
207       FormSet fs = new FormSet();
208       Form form = new Form();
209       form.setName("testForm");
210       Field field = new Field();
211       field.setProperty("letter");
212       field.setDepends("capLetter");
213       form.addField(field);
214       fs.addForm(form);
215       
216       resources.addValidatorAction(va);
217       resources.addFormSet(fs);
218       resources.process();
219 
220       List l = new ArrayList();
221 
222       TestBean bean = new TestBean();  
223       bean.setLetter("A");
224       
225       Validator validator = new Validator(resources, "testForm");
226       validator.setParameter(Validator.BEAN_PARAM, bean);
227       validator.setParameter("java.util.List", l);
228 
229       try {
230          validator.validate();
231       } catch (Exception e) {
232          fail("An exception was thrown while calling Validator.validate()");
233       }
234 
235       assertEquals("Validation of the letter 'A'.", 0, l.size());
236 
237       l.clear();       
238       bean.setLetter("AA");
239 
240       try {
241          validator.validate();
242       } catch (Exception e) {
243          fail("An exception was thrown while calling Validator.validate()");
244       }
245       
246       assertEquals("Validation of the letter 'AA'.", 1, l.size());
247    }
248 
249    /***
250     * Checks if the field is one upper case letter between 'A' and 'Z'.
251     */
252    public static boolean isCapLetter(Object bean, Field field, List l) {
253       String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
254 
255       if (value != null && value.length() == 1) {
256          if (value.charAt(0) >= 'A' && value.charAt(0) <= 'Z') {
257             return true;
258          } else {
259             l.add("Error");
260             return false;
261          }
262       } else {
263          l.add("Error");
264          return false;
265       }
266    }
267 
268    /***
269     * Formats a <code>String</code> to a <code>Date</code>.  
270     * The <code>Validator</code> will interpret a <code>null</code> 
271     * as validation having failed.
272     */
273    public static Date formatDate(Object bean, Field field) {
274       String value = ValidatorUtils.getValueAsString(bean, field.getProperty());
275       Date date = null;
276       
277       try {
278          DateFormat formatter = null;
279          formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
280             
281          formatter.setLenient(false);
282              
283          date = formatter.parse(value);
284       } catch (ParseException e) {
285          System.out.println("ValidatorTest.formatDate() - " + e.getMessage());
286       }
287    
288       return date;
289    }	
290        
291    public class TestBean {
292       private String letter = null;
293       private String date = null;
294       
295       public String getLetter() {
296          return letter;
297       }
298       
299       public void setLetter(String letter) {
300          this.letter = letter;	
301       }
302 
303       public String getDate() {
304          return date;
305       }
306       
307       public void setDate(String date) {
308          this.date = date;	
309       }
310    }
311 
312 }