1   /*
2    * $Id: TimeValidatorTest.java 371174 2006-01-22 03:24:40Z niallp $
3    * $Revision: 371174 $
4    * $Date: 2006-01-22 03:24:40 +0000 (Sun, 22 Jan 2006) $
5    *
6    * ====================================================================
7    * Copyright 2006 The Apache Software Foundation
8    *
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   *
13   *     http://www.apache.org/licenses/LICENSE-2.0
14   *
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   */
21  package org.apache.commons.validator.routines;
22  
23  import junit.framework.TestCase;
24  
25  import java.util.Date;
26  import java.util.Calendar;
27  import java.util.Locale;
28  import java.util.TimeZone;
29  
30  /***
31   * Test Case for TimeValidator.
32   * 
33   * @version $Revision: 371174 $ $Date: 2006-01-22 03:24:40 +0000 (Sun, 22 Jan 2006) $
34   */
35  public class TimeValidatorTest extends TestCase {
36  
37      protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset
38      protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours
39  
40      protected TimeValidator validator;
41  
42      protected String[] patternValid = new String[] {
43                         "23-59-59" 
44                        ,"00-00-00"
45                        ,"00-00-01"
46                        ,"0-0-0" 
47                        ,"1-12-1"
48                        ,"10-49-18"
49                        ,"16-23-46"};
50      protected Date[] patternExpect = new Date[] {
51                         createDate(null, 235959, 0)
52                        ,createDate(null, 0, 0)
53                        ,createDate(null, 1, 0)
54                        ,createDate(null, 0, 0)
55                        ,createDate(null, 11201, 0)
56                        ,createDate(null, 104918, 0)
57                        ,createDate(null, 162346, 0)};
58      protected String[] localeValid = new String[] {
59                        "23:59" 
60                       ,"00:00"
61                       ,"00:01"
62                       ,"0:0" 
63                       ,"1:12"
64                       ,"10:49"
65                       ,"16:23"};
66      protected Date[] localeExpect = new Date[] {
67                        createDate(null, 235900, 0)
68                       ,createDate(null, 0, 0)
69                       ,createDate(null, 100, 0)
70                       ,createDate(null, 0, 0)
71                       ,createDate(null, 11200, 0)
72                       ,createDate(null, 104900, 0)
73                       ,createDate(null, 162300, 0)};
74      protected String[] patternInvalid = new String[] {
75                           "24-00-00"  // midnight
76                          ,"24-00-01"  // past midnight
77                          ,"25-02-03"  // invalid hour 
78                          ,"10-61-31"  // invalid minute
79                          ,"10-01-61"  // invalid second
80                          ,"05:02-29"  // invalid sep 
81                          ,"0X-01:01"  // invalid sep
82                          ,"05-0X-01"  // invalid char
83                          ,"10-01-0X"  // invalid char
84                          ,"01:01:05"  // invalid pattern
85                          ,"10-10"     // invalid pattern
86                          ,"10--10"    // invalid pattern
87                          ,"10-10-"};  // invalid pattern
88      protected String[] localeInvalid = new String[] {
89                           "24:00"  // midnight
90                          ,"24:00"  // past midnight
91                          ,"25:02"  // invalid hour 
92                          ,"10:61"  // invalid minute
93                          ,"05-02"  // invalid sep 
94                          ,"0X:01"  // invalid sep
95                          ,"05:0X"  // invalid char
96                          ,"01-01"  // invalid pattern
97                          ,"10:"     // invalid pattern
98                          ,"10::1"    // invalid pattern
99                          ,"10:1:"};  // invalid pattern
100 
101     /***
102      * Main
103      * @param args arguments
104      */
105     public static void main(String[] args) {
106         junit.textui.TestRunner.run(TimeValidatorTest.class);
107     }
108 
109     /***
110      * Constructor
111      * @param name test name
112      */
113     public TimeValidatorTest(String name) {
114         super(name);
115     }
116 
117     protected void setUp() throws Exception {
118         super.setUp();
119         validator = new TimeValidator();
120     }
121 
122     /***
123      * Tear down
124      * @throws Exception
125      */
126     protected void tearDown() throws Exception {
127         super.tearDown();
128         validator = null;
129     }
130 
131     /***
132      * Test Valid Dates with "pattern" validation
133      */
134     public void testPatternValid() {
135         for (int i = 0; i < patternValid.length; i++) {
136             String text = i + " value=[" +patternValid[i]+"] failed ";
137             Calendar calendar = validator.validate(patternValid[i], "HH-mm-ss");
138             assertNotNull("validateObj() " + text,  calendar);
139             Date date = calendar.getTime();
140             assertTrue("isValid() " + text,  validator.isValid(patternValid[i], "HH-mm-ss"));
141             assertEquals("compare " + text, patternExpect[i], date);
142         }
143     }
144 
145     /***
146      * Test Invalid Dates with "pattern" validation
147      */
148     public void testPatternInvalid() {
149         for (int i = 0; i < patternInvalid.length; i++) {
150             String text = i + " value=[" +patternInvalid[i]+"] passed ";
151             Object date = validator.validate(patternInvalid[i], "HH-mm-ss");
152             assertNull("validate() " + text + date,  date);
153             assertFalse("isValid() " + text,  validator.isValid(patternInvalid[i], "HH-mm-ss"));
154         }
155     }
156 
157     /***
158      * Test Valid Dates with "locale" validation
159      */
160     public void testLocaleValid() {
161         for (int i = 0; i < localeValid.length; i++) {
162             String text = i + " value=[" +localeValid[i]+"] failed ";
163             Calendar calendar = validator.validate(localeValid[i], Locale.UK);
164             assertNotNull("validate() " + text,  calendar);
165             Date date = calendar.getTime();
166             assertTrue("isValid() " + text,  validator.isValid(localeValid[i], Locale.UK));
167             assertEquals("compare " + text, localeExpect[i], date);
168         }
169     }
170 
171     /***
172      * Test Invalid Dates with "locale" validation
173      */
174     public void testLocaleInvalid() {
175         for (int i = 0; i < localeInvalid.length; i++) {
176             String text = i + " value=[" +localeInvalid[i]+"] passed ";
177             Object date = validator.validate(localeInvalid[i], Locale.US);
178             assertNull("validate() " + text + date,  date);
179             assertFalse("isValid() " + text,  validator.isValid(localeInvalid[i], Locale.UK));
180         }
181     }
182 
183     /***
184      * Test time zone methods.
185      */
186     public void testTimeZone() {
187         // Set the default Locale & TimeZone
188         Locale origDefault = Locale.getDefault();
189         Locale.setDefault(Locale.UK);
190         TimeZone defaultZone = TimeZone.getDefault();
191         TimeZone.setDefault(GMT);
192 
193         Calendar result = null;
194 
195         // Default Locale, Default TimeZone
196         result = validator.validate("18:01");
197         assertNotNull("default result", result);
198         assertEquals("default zone",  GMT, result.getTimeZone());
199         assertEquals("default hour",   18, result.get(Calendar.HOUR_OF_DAY));
200         assertEquals("default minute", 01, result.get(Calendar.MINUTE));
201         result = null;
202 
203         // Default Locale, diff TimeZone
204         result = validator.validate("16:49", EST);
205         assertNotNull("zone result", result);
206         assertEquals("zone zone",  EST, result.getTimeZone());
207         assertEquals("zone hour",   16, result.get(Calendar.HOUR_OF_DAY));
208         assertEquals("zone minute", 49, result.get(Calendar.MINUTE));
209         result = null;
210 
211         // Pattern, diff TimeZone
212         result = validator.validate("14-34", "HH-mm", EST);
213         assertNotNull("pattern result", result);
214         assertEquals("pattern zone",  EST, result.getTimeZone());
215         assertEquals("pattern hour",   14, result.get(Calendar.HOUR_OF_DAY));
216         assertEquals("pattern minute", 34, result.get(Calendar.MINUTE));
217         result = null;
218 
219         // Locale, diff TimeZone
220         result = validator.validate("7:18 PM", Locale.US, EST);
221         assertNotNull("locale result", result);
222         assertEquals("locale zone",  EST, result.getTimeZone());
223         assertEquals("locale hour",   19, result.get(Calendar.HOUR_OF_DAY));
224         assertEquals("locale minute", 18, result.get(Calendar.MINUTE));
225         result = null;
226 
227         // Locale & Pattern, diff TimeZone
228         result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN, EST);
229         assertNotNull("pattern result", result);
230         assertEquals("pattern zone",  EST, result.getTimeZone());
231         assertEquals("pattern day",  2005, result.get(Calendar.YEAR));
232         assertEquals("pattern day",    11, result.get(Calendar.MONTH)); // months are 0-11
233         assertEquals("pattern day",    31, result.get(Calendar.DATE));
234         assertEquals("pattern hour",   21, result.get(Calendar.HOUR_OF_DAY));
235         assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
236         result = null;
237 
238         // Locale & Pattern, default TimeZone
239         result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN);
240         assertNotNull("pattern result", result);
241         assertEquals("pattern zone",  GMT, result.getTimeZone());
242         assertEquals("pattern day",  2005, result.get(Calendar.YEAR));
243         assertEquals("pattern day",    11, result.get(Calendar.MONTH)); // months are 0-11
244         assertEquals("pattern day",    31, result.get(Calendar.DATE));
245         assertEquals("pattern hour",   21, result.get(Calendar.HOUR_OF_DAY));
246         assertEquals("pattern minute", 05, result.get(Calendar.MINUTE));
247         result = null;
248 
249         // Restore the original default
250         Locale.setDefault(origDefault);
251         TimeZone.setDefault(defaultZone);
252     }
253 
254     /***
255      * Test Invalid Dates with "locale" validation
256      */
257     public void testFormat() {
258         // Set the default Locale
259         Locale origDefault = Locale.getDefault();
260         Locale.setDefault(Locale.UK);
261 
262         Object test = TimeValidator.getInstance().validate("16:49:23", "HH:mm:ss");
263         assertNotNull("Test Date ", test);
264         assertEquals("Format pattern", "16-49-23", validator.format(test, "HH-mm-ss"));
265         assertEquals("Format locale",  "4:49 PM",  validator.format(test, Locale.US));
266         assertEquals("Format default", "16:49",  validator.format(test));
267 
268         // Restore the original default
269         Locale.setDefault(origDefault);
270     }
271 
272     /***
273      * Test compare date methods
274      */
275     public void testCompare() {
276         int testTime = 154523;
277         int min = 100;
278         int hour = 10000;
279 
280         Calendar milliGreater = createTime(GMT, testTime, 500); // > milli sec
281         Calendar value        = createTime(GMT, testTime, 400); // test value
282         Calendar milliLess    = createTime(GMT, testTime, 300); // < milli sec
283 
284         Calendar secGreater   = createTime(GMT, testTime + 1, 100);   // +1 sec
285         Calendar secLess      = createTime(GMT, testTime - 1, 100);   // -1 sec
286 
287         Calendar minGreater   = createTime(GMT, testTime + min, 100);   // +1 min
288         Calendar minLess      = createTime(GMT, testTime - min, 100);   // -1 min
289 
290         Calendar hourGreater  = createTime(GMT, testTime + hour, 100);   // +1 hour
291         Calendar hourLess     = createTime(GMT, testTime - hour, 100);   // -1 hour
292 
293         assertEquals("mili LT", -1, validator.compareTime(value, milliGreater)); // > milli
294         assertEquals("mili EQ", 0,  validator.compareTime(value, value));        // same time
295         assertEquals("mili GT", 1,  validator.compareTime(value, milliLess));    // < milli
296 
297         assertEquals("secs LT", -1, validator.compareSeconds(value, secGreater));   // +1 sec
298         assertEquals("secs =1", 0,  validator.compareSeconds(value, milliGreater)); // > milli
299         assertEquals("secs =2", 0,  validator.compareSeconds(value, value));        // same time
300         assertEquals("secs =3", 0,  validator.compareSeconds(value, milliLess));    // < milli
301         assertEquals("secs GT", 1,  validator.compareSeconds(value, secLess));      // -1 sec
302 
303         assertEquals("mins LT", -1, validator.compareMinutes(value, minGreater));   // +1 min
304         assertEquals("mins =1", 0,  validator.compareMinutes(value, secGreater));   // +1 sec
305         assertEquals("mins =2", 0,  validator.compareMinutes(value, value));        // same time
306         assertEquals("mins =3", 0,  validator.compareMinutes(value, secLess));      // -1 sec
307         assertEquals("mins GT", 1,  validator.compareMinutes(value, minLess));      // -1 min
308 
309         assertEquals("hour LT", -1, validator.compareHours(value, hourGreater));   // +1 hour
310         assertEquals("hour =1", 0,  validator.compareHours(value, minGreater));   // +1 min
311         assertEquals("hour =2", 0,  validator.compareHours(value, value));        // same time
312         assertEquals("hour =3", 0,  validator.compareHours(value, minLess));      // -1 min
313         assertEquals("hour GT", 1,  validator.compareHours(value, hourLess));      // -1 hour
314 
315     }
316 
317     /***
318      * Create a calendar instance for a specified time zone, date and time.
319      * 
320      * @param zone The time zone
321      * @param time the time in HH:mm:ss format
322      * @param millisecond the milliseconds
323      * @return the new Calendar instance.
324      */
325     protected static Calendar createTime(TimeZone zone, int time, int millisecond) {
326         Calendar calendar = zone == null ? Calendar.getInstance()
327                                          : Calendar.getInstance(zone);
328         int hour = ((time / 10000) * 10000);
329         int min  = ((time / 100) * 100) - hour;
330         int sec  = time - (hour + min);
331         calendar.set(Calendar.YEAR,  1970);
332         calendar.set(Calendar.MONTH, 0);
333         calendar.set(Calendar.DATE,  1);
334         calendar.set(Calendar.HOUR_OF_DAY,  (hour / 10000));
335         calendar.set(Calendar.MINUTE, (min / 100));
336         calendar.set(Calendar.SECOND,  sec);
337         calendar.set(Calendar.MILLISECOND,  millisecond);
338         return calendar;
339     }
340 
341     /***
342      * Create a date instance for a specified time zone, date and time.
343      * 
344      * @param zone The time zone
345      * @param time the time in HH:mm:ss format
346      * @param millisecond the milliseconds
347      * @return the new Date instance.
348      */
349     protected static Date createDate(TimeZone zone, int time, int millisecond) {
350         Calendar calendar = createTime(zone, time, millisecond);
351         return calendar.getTime();
352     }
353 }