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 */
17package libcore.java.text;
18
19import java.text.DateFormat;
20import java.text.FieldPosition;
21import java.text.ParseException;
22import java.text.ParsePosition;
23import java.text.SimpleDateFormat;
24import java.util.Calendar;
25import java.util.Date;
26import java.util.Locale;
27import java.util.TimeZone;
28
29public class OldDateFormatTest extends junit.framework.TestCase {
30
31    private class MockDateFormat extends DateFormat {
32
33        private static final long serialVersionUID = 1L;
34
35        public MockDateFormat() {
36            super();
37        }
38
39        @Override
40        public Date parse(String source, ParsePosition pos) {
41            // it is a fake
42            return null;
43        }
44
45        @Override
46        public StringBuffer format(Date date, StringBuffer toAppendTo,
47                FieldPosition fieldPosition) {
48            // it is a fake
49            return null;
50        }
51    }
52
53    /**
54     * java.text.DateFormat#DateFormat() Test of method
55     *        java.text.DateFormat#DateFormat().
56     */
57    public void test_Constructor() {
58        try {
59            new MockDateFormat();
60        } catch (Exception e) {
61            fail("Unexpected exception " + e.toString());
62        }
63    }
64
65    /**
66     * java.text.DateFormat#equals(java.lang.Object obj) Test of
67     *        java.text.DateFormat#equals(java.lang.Object obj).
68     */
69    public void test_equalsLjava_lang_Object() {
70        try {
71            DateFormat format = DateFormat.getInstance();
72            DateFormat clone = (DateFormat) format.clone();
73            assertTrue("Clone and parent are not equaled", format.equals(clone));
74            assertTrue("Clone is equal to other object", !clone
75                    .equals(DateFormat.getTimeInstance()));
76            format.setCalendar(Calendar.getInstance());
77            assertTrue("Clone and parent are not equaled", format.equals(clone));
78        } catch (Exception e) {
79            fail("Unexpected exception " + e.toString());
80        }
81    }
82
83    /**
84     * java.text.DateFormat#format(java.util.Date) Test of method
85     *        java.text.DateFormat#format(java.util.Date).
86     */
87    public void test_formatLjava_util_Date() {
88        try {
89            DateFormat format = DateFormat.getDateTimeInstance(
90                    DateFormat.SHORT, DateFormat.SHORT, Locale.US);
91            Date current = new Date();
92            String dtf = format.format(current);
93            SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a", Locale.US);
94            assertTrue("Incorrect date format", sdf.format(current).equals(dtf));
95        } catch (Exception e) {
96            fail("Unexpected exception " + e.toString());
97        }
98    }
99
100    /**
101     * java.text.DateFormat#format(Object, StringBuffer, FieldPosition)
102     *        Test of method java.text.DateFormat#format(Object, StringBuffer,
103     *        FieldPosition)
104     */
105    public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() {
106        try {
107            DateFormat format = DateFormat.getDateTimeInstance(
108                    DateFormat.SHORT, DateFormat.SHORT, Locale.US);
109            Date current = new Date();
110            StringBuffer toAppend = new StringBuffer();
111            FieldPosition fp = new FieldPosition(DateFormat.YEAR_FIELD);
112            StringBuffer sb = format.format(current, toAppend, fp);
113            SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a", Locale.US);
114            assertTrue("Incorrect date format", sdf.format(current).equals(
115                    sb.toString()));
116            assertTrue("Incorrect beginIndex of filed position", fp
117                    .getBeginIndex() == sb.lastIndexOf("/") + 1);
118            assertTrue("Incorrect endIndex of filed position",
119                    fp.getEndIndex() == sb.lastIndexOf("/") + 3);
120        } catch (Exception e) {
121            fail("Unexpected exception " + e.toString());
122        }
123    }
124
125    public void test_getTimeZone() {
126        try {
127            DateFormat format = DateFormat.getInstance();
128            TimeZone   tz     = format.getTimeZone();
129            //if(1 == 1)
130            //    throw new Exception(tz.getClass().getName());
131            // We know we are not sun.util so:
132            // Redundant checking
133            //assertFalse("Incorrect zone info", tz.getClass().getName().equals(
134            //        "sun.util.calendar.ZoneInfo"));
135            assertTrue("Incorrect time zone", tz.equals(format.getCalendar()
136                    .getTimeZone()));
137        } catch (Exception e) {
138            fail("Unexpected exception " + e.toString());
139        }
140    }
141
142    /**
143     * java.text.DateFormat#hashCode() Test of method
144     *        java.text.DateFormat#hashCode().
145     */
146    public void test_hashCode() {
147        try {
148            DateFormat df1 = DateFormat.getInstance();
149            DateFormat df2 = (DateFormat) df1.clone();
150            assertTrue("Hash codes of clones are not equal",
151                    df1.hashCode() == df2.hashCode());
152            assertTrue("Hash codes of different objects are the same", df1
153                    .hashCode() != DateFormat.getDateInstance().hashCode());
154        } catch (Exception e) {
155            fail("Unexpected exception " + e.toString());
156        }
157    }
158
159    /**
160     * java.text.DateFormat#isLenient() Test of method
161     *        java.text.DateFormat#isLenient().
162     */
163    public void test_isLenient() {
164        DateFormat df = DateFormat.getInstance();
165        Calendar c = df.getCalendar();
166        if (df.isLenient()) {
167            try {
168                c.set(Calendar.DAY_OF_MONTH, 32);
169                c.get(Calendar.DAY_OF_MONTH);
170            } catch (Exception e) {
171                fail("Unexpected exception " + e.toString());
172            }
173            c.setLenient(false);
174            try {
175                c.set(Calendar.DAY_OF_MONTH, 32);
176                c.get(Calendar.DAY_OF_MONTH);
177                fail("Expected IllegalArgumentException was not thrown");
178            } catch (IllegalArgumentException e) {
179                // expected
180            } catch (Exception e) {
181                fail("Unexpected exception " + e.toString());
182            }
183        } else {
184            try {
185                c.set(Calendar.DAY_OF_MONTH, 32);
186                c.get(Calendar.DAY_OF_MONTH);
187                fail("Expected IllegalArgumentException was not thrown");
188            } catch (IllegalArgumentException e) {
189                // expected
190            } catch (Exception e) {
191                fail("Unexpected exception " + e.toString());
192            }
193            c.setLenient(true);
194            try {
195                c.set(Calendar.DAY_OF_MONTH, 32);
196                c.get(Calendar.DAY_OF_MONTH);
197            } catch (Exception e) {
198                fail("Unexpected exception " + e.toString());
199            }
200        }
201    }
202
203    /**
204     * java.text.DateFormat#parse(String)
205     */
206    public void test_parseLString() throws Exception {
207        DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
208
209        try {
210            format.parse("not a Date");
211            fail("should throw ParseException first");
212        } catch (ParseException pe) {
213            assertNotNull(pe.getMessage());
214        }
215
216        Date current = new Date();
217
218        try {
219            Date date = format.parse(format.format(current).toString());
220            assertEquals(current.getDate(), date.getDate());
221            assertEquals(current.getDay(), date.getDay());
222            assertEquals(current.getMonth(), date.getMonth());
223            assertEquals(current.getYear(), date.getYear());
224            assertEquals(current.getHours(), date.getHours());
225            assertEquals(current.getMinutes(), date.getMinutes());
226            assertEquals(0, date.getSeconds());
227        } catch(ParseException pe) {
228            fail("ParseException was thrown for current Date.");
229        }
230
231        try {
232            format.parse("27/08/1998");
233            fail("ParseException was not thrown.");
234        } catch(ParseException pe) {
235            //expected
236        }
237        try {
238            format.parse("30/30/908 4:50, PDT");
239            fail("ParseException was not thrown.");
240        } catch(ParseException pe) {
241            //expected
242        }
243        try {
244            format.parse("837039928046");
245            fail("ParseException was not thrown.");
246        } catch(ParseException pe) {
247            //expected
248        }
249
250        format = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
251        try {
252            Date date = format.parse(format.format(current).toString());
253            assertEquals(current.getDate(), date.getDate());
254            assertEquals(current.getDay(), date.getDay());
255            assertEquals(current.getMonth(), date.getMonth());
256            assertEquals(current.getYear(), date.getYear());
257            assertEquals(0, date.getHours());
258            assertEquals(0, date.getMinutes());
259            assertEquals(0, date.getSeconds());
260        } catch(ParseException pe) {
261            fail("ParseException was thrown for current Date.");
262        }
263
264        try {
265            format.parse("Jan 16 1970");
266            fail("ParseException was not thrown.");
267        } catch(ParseException pe) {
268            //expected
269        }
270
271        try {
272            format.parse("27/08/1998");
273            fail("ParseException was not thrown.");
274        } catch(ParseException pe) {
275            //expected
276        }
277
278        format = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
279        try {
280            Date date = format.parse(format.format(current).toString());
281            assertEquals(current.getDate(), date.getDate());
282            assertEquals(current.getDay(), date.getDay());
283            assertEquals(current.getMonth(), date.getMonth());
284            assertEquals(current.getYear(), date.getYear());
285            assertEquals(0, date.getHours());
286            assertEquals(0, date.getMinutes());
287            assertEquals(0, date.getSeconds());
288        } catch(ParseException pe) {
289            fail("ParseException was thrown for current Date.");
290        }
291
292        format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
293        try {
294            Date date = format.parse(format.format(current).toString());
295            assertEquals(current.getDate(), date.getDate());
296            assertEquals(current.getDay(), date.getDay());
297            assertEquals(current.getMonth(), date.getMonth());
298            assertEquals(current.getYear(), date.getYear());
299            assertEquals(0, date.getHours());
300            assertEquals(0, date.getMinutes());
301            assertEquals(0, date.getSeconds());
302        } catch(ParseException pe) {
303            fail("ParseException was thrown for current Date.");
304        }
305
306        format = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US);
307        try {
308            Date date = format.parse(format.format(current).toString());
309            assertEquals(1, date.getDate());
310            assertEquals(0, date.getMonth());
311            assertEquals(70, date.getYear());
312            assertEquals(current.getHours(), date.getHours());
313            assertEquals(current.getMinutes(), date.getMinutes());
314        } catch(ParseException pe) {
315            fail("ParseException was thrown for current Date.");
316        }
317
318        try {
319            format.parse("8:58:44");
320            fail("ParseException was not thrown.");
321        } catch(ParseException pe) {
322            //expected
323        }
324
325        format = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, Locale.US);
326        try {
327            Date date = format.parse(format.format(current).toString());
328            assertEquals(current.getDate(), date.getDate());
329            assertEquals(current.getDay(), date.getDay());
330            assertEquals(current.getMonth(), date.getMonth());
331            assertEquals(current.getYear(), date.getYear());
332            assertEquals(current.getHours(), date.getHours());
333            assertEquals(current.getMinutes(), date.getMinutes());
334        } catch(ParseException pe) {
335            fail("ParseException was thrown for current Date.");
336        }
337
338        try {
339            format.parse("January 31 1970 7:52:34 AM PST");
340            fail("ParseException was not thrown.");
341        } catch (ParseException expected) {
342        }
343
344        try {
345            format.parse("January 31 1970");
346            fail("ParseException was not thrown.");
347        } catch (ParseException expected) {
348        }
349
350        format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
351        String formatPattern = ((SimpleDateFormat) format).toPattern();
352        String formattedCurrent = format.format(current);
353        Date date = format.parse(formattedCurrent);
354        // Date has millisecond accuracy, but humans don't use time formats that precise.
355        if (date.getTime() / 1000 != current.getTime() / 1000) {
356            fail(date.getTime() + " != " + current.getTime() +
357                    "; " + formatPattern + "; " + formattedCurrent);
358        }
359
360        try {
361            format.parse("January 16, 1970 8:03:52 PM CET");
362            fail("ParseException was not thrown.");
363        } catch (ParseException expected) {
364        }
365    }
366
367    /**
368     * java.text.DateFormat#parseObject(String, ParsePosition) Test of
369     *        method java.text.DateFormat#parseObject(String, ParsePosition).
370     *        Case 1: Try to parse correct data string. Case 2: Try to parse
371     *        partialy correct data string. Case 3: Try to use argument
372     *        ParsePosition as null.
373     */
374    public void test_parseObjectLjava_lang_StringLjava_text_ParsePosition() {
375        DateFormat df = DateFormat.getInstance();
376        try {
377            // case 1: Try to parse correct data string.
378            Date current = new Date();
379            ParsePosition pp = new ParsePosition(0);
380            int parseIndex = pp.getIndex();
381            Date result = (Date) df.parseObject(df.format(current), pp);
382
383            assertEquals("Dates are different.", current.getDate(), result.getDate());
384            assertEquals("Days are different.", current.getDay(), result.getDay());
385            assertEquals("Months are different.", current.getMonth(), result.getMonth());
386            assertEquals("Years are different.", current.getYear(), result.getYear());
387            assertEquals("Hours are different", current.getHours(), result.getHours());
388            assertEquals("Minutes are diffetrent,", current.getMinutes(), result.getMinutes());
389
390            assertTrue("Parse operation return null", result != null);
391            assertTrue("ParseIndex is incorrect", pp.getIndex() != parseIndex);
392
393            // case 2: Try to parse partially correct data string.
394            pp.setIndex(0);
395            char[] cur = df.format(current).toCharArray();
396            cur[cur.length / 2] = 'Z';
397            String partialCorrect = new String(cur);
398            result = (Date) df.parseObject(partialCorrect, pp);
399            assertTrue("Parse operation return not-null", result == null);
400            assertTrue("ParseIndex is incorrect", pp.getIndex() == 0);
401            assertTrue("ParseErrorIndex is incorrect",
402                    pp.getErrorIndex() == cur.length / 2);
403
404            pp.setIndex(2);
405            char[] curDate = df.format(current).toCharArray();
406            char [] newArray = new char[curDate.length + pp.getIndex()];
407            for(int i = 0; i < curDate.length; i++) {
408                newArray[i + pp.getIndex()] = curDate[i];
409            }
410            result = (Date) df.parseObject(new String(newArray), pp);
411            //assertEquals(current, result);
412
413            assertEquals("Dates are different.", current.getDate(), result.getDate());
414            assertEquals("Days are different.", current.getDay(), result.getDay());
415            assertEquals("Months are different.", current.getMonth(), result.getMonth());
416            assertEquals("Years are different.", current.getYear(), result.getYear());
417            assertEquals("Hours are different", current.getHours(), result.getHours());
418            assertEquals("Minutes are diffetrent,", current.getMinutes(), result.getMinutes());
419
420            // case 3: Try to use argument ParsePosition as null.
421            try {
422                df.parseObject(df.format(current), null);
423                fail("Expected NullPointerException was not thrown");
424            } catch (NullPointerException e) {
425                // expected
426            }
427
428            assertNull(df.parseObject("test", pp));
429
430        } catch (Exception e) {
431            fail("Unexpected exception " + e.toString());
432        }
433    }
434
435    /**
436     * java.text.DateFormat#setLenient(boolean) Test of method
437     *        java.text.DateFormat#setLenient(boolean).
438     */
439    public void test_setLenientZ() {
440        DateFormat df = DateFormat.getInstance();
441        Calendar c = df.getCalendar();
442        try {
443            c.setLenient(true);
444            try {
445                c.set(Calendar.DAY_OF_MONTH, 32);
446                c.get(Calendar.DAY_OF_MONTH);
447            } catch (Exception e) {
448                fail("Unexpected exception " + e.toString());
449            }
450            c.setLenient(false);
451            try {
452                c.set(Calendar.DAY_OF_MONTH, 32);
453                c.get(Calendar.DAY_OF_MONTH);
454                fail("Expected IllegalArgumentException was not thrown");
455            } catch (IllegalArgumentException e) {
456                // expected
457            } catch (Exception e) {
458                fail("Unexpected exception " + e.toString());
459            }
460        } catch (Exception e) {
461            fail("Uexpected exception " + e.toString());
462        }
463    }
464
465    /**
466     * java.text.DateFormat#setTimeZone(TimeZone) Test of method
467     *        java.text.DateFormat#setTimeZone(TimeZone).
468     */
469    public void test_setTimeZoneLjava_util_TimeZone() {
470        try {
471            DateFormat format = DateFormat.getInstance();
472            TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
473            format.setTimeZone(tz);
474            assertTrue("TimeZone is set incorrectly", tz.equals(format
475                    .getTimeZone()));
476        } catch (Exception e) {
477            fail("Unexpected exception " + e.toString());
478        }
479    }
480}
481