]>
git.saurik.com Git - apple/icu.git/blob - icuSources/test/intltest/dtfmtrtts.cpp
1 /***********************************************************************
3 * Copyright (c) 1997-2010, International Business Machines Corporation
4 * and others. All Rights Reserved.
5 ***********************************************************************/
7 #include "unicode/utypes.h"
9 #if !UCONFIG_NO_FORMATTING
11 #include "unicode/datefmt.h"
12 #include "unicode/smpdtfmt.h"
13 #include "unicode/gregocal.h"
14 #include "dtfmtrtts.h"
20 // *****************************************************************************
21 // class DateFormatRoundTripTest
22 // *****************************************************************************
24 // Useful for turning up subtle bugs: Change the following to TRUE, recompile,
25 // and run while at lunch.
26 // Warning -- makes test run infinite loop!!!
31 static const UVersionInfo ICU_452
= {4,5,2,0};
33 // Define this to test just a single locale
34 //#define TEST_ONE_LOC "cs_CZ"
36 // If SPARSENESS is > 0, we don't run each exhaustive possibility.
37 // There are 24 total possible tests per each locale. A SPARSENESS
38 // of 12 means we run half of them. A SPARSENESS of 23 means we run
39 // 1 of them. SPARSENESS _must_ be in the range 0..23.
40 int32_t DateFormatRoundTripTest::SPARSENESS
= 0;
41 int32_t DateFormatRoundTripTest::TRIALS
= 4;
42 int32_t DateFormatRoundTripTest::DEPTH
= 5;
44 DateFormatRoundTripTest::DateFormatRoundTripTest() : dateFormat(0) {
47 DateFormatRoundTripTest::~DateFormatRoundTripTest() {
51 #define CASE(id,test) case id: name = #test; if (exec) { logln(#test "---"); logln((UnicodeString)""); test(); } break;
54 DateFormatRoundTripTest::runIndexedTest( int32_t index
, UBool exec
, const char* &name
, char* par
)
56 optionv
= (par
&& *par
=='v');
58 CASE(0,TestDateFormatRoundTrip
)
60 default: name
= ""; break;
65 DateFormatRoundTripTest::failure(UErrorCode status
, const char* msg
)
67 if(U_FAILURE(status
)) {
68 errln(UnicodeString("FAIL: ") + msg
+ " failed, error " + u_errorName(status
));
76 DateFormatRoundTripTest::failure(UErrorCode status
, const char* msg
, const UnicodeString
& str
)
78 if(U_FAILURE(status
)) {
79 UnicodeString escaped
;
81 errln(UnicodeString("FAIL: ") + msg
+ " failed, error " + u_errorName(status
) + ", str=" + escaped
);
88 void DateFormatRoundTripTest::TestCentury()
90 UErrorCode status
= U_ZERO_ERROR
;
91 Locale
locale("es_PA");
92 UnicodeString pattern
= "MM/dd/yy hh:mm:ss a z";
93 SimpleDateFormat
fmt(pattern
, locale
, status
);
94 if (U_FAILURE(status
)) {
95 dataerrln("Fail: construct SimpleDateFormat: %s", u_errorName(status
));
98 UDate date
[] = {-55018555891590.05, 0, 0};
99 UnicodeString result
[2];
101 fmt
.format(date
[0], result
[0]);
102 date
[1] = fmt
.parse(result
[0], status
);
103 fmt
.format(date
[1], result
[1]);
104 date
[2] = fmt
.parse(result
[1], status
);
106 /* This test case worked OK by accident before. date[1] != date[0],
107 * because we use -80/+20 year window for 2-digit year parsing.
108 * (date[0] is in year 1926, date[1] is in year 2026.) result[1] set
109 * by the first format call returns "07/13/26 07:48:28 p.m. PST",
110 * which is correct, because DST was not used in year 1926 in zone
111 * America/Los_Angeles. When this is parsed, date[1] becomes a time
112 * in 2026, which is "07/13/26 08:48:28 p.m. PDT". There was a zone
113 * offset calculation bug that observed DST in 1926, which was resolved.
114 * Before the bug was resolved, result[0] == result[1] was true,
115 * but after the bug fix, the expected result is actually
116 * result[0] != result[1]. -Yoshito
118 /* TODO: We need to review this code and clarify what we really
121 //if (date[1] != date[2] || result[0] != result[1]) {
122 if (date
[1] != date
[2]) {
123 errln("Round trip failure: \"%S\" (%f), \"%S\" (%f)", result
[0].getBuffer(), date
[1], result
[1].getBuffer(), date
[2]);
128 void DateFormatRoundTripTest::TestDateFormatRoundTrip()
130 UErrorCode status
= U_ZERO_ERROR
;
132 getFieldCal
= Calendar::createInstance(status
);
133 if (U_FAILURE(status
)) {
134 dataerrln("Fail: Calendar::createInstance: %s", u_errorName(status
));
139 int32_t locCount
= 0;
140 const Locale
*avail
= DateFormat::getAvailableLocales(locCount
);
141 logln("DateFormat available locales: %d", locCount
);
144 logln("Quick mode: only testing SPARSENESS = 18");
146 TimeZone
*tz
= TimeZone::createDefault();
148 logln("Default TimeZone: " + tz
->getID(temp
));
151 #ifdef TEST_ONE_LOC // define this to just test ONE locale.
152 Locale
loc(TEST_ONE_LOC
);
162 // Special infinite loop test mode for finding hard to reproduce errors
163 Locale loc
= Locale::getDefault();
164 logln("ENTERING INFINITE TEST LOOP FOR Locale: " + loc
.getDisplayName(temp
));
168 test(Locale::getDefault());
172 for (int i
=0; i
< locCount
; ++i
) {
179 int32_t jCount
= CalendarTest::testLocaleCount();
180 for (int32_t j
=0; j
< jCount
; ++j
) {
181 test(Locale(CalendarTest::testLocaleID(j
)));
191 static const char *styleName(DateFormat::EStyle s
)
195 case DateFormat::SHORT
: return "SHORT";
196 case DateFormat::MEDIUM
: return "MEDIUM";
197 case DateFormat::LONG
: return "LONG";
198 case DateFormat::FULL
: return "FULL";
199 // case DateFormat::DEFAULT: return "DEFAULT";
200 case DateFormat::DATE_OFFSET
: return "DATE_OFFSET";
201 case DateFormat::NONE
: return "NONE";
202 case DateFormat::DATE_TIME
: return "DATE_TIME";
203 default: return "Unknown";
207 void DateFormatRoundTripTest::test(const Locale
& loc
)
211 logln("Locale: " + loc
.getDisplayName(temp
));
214 // Total possibilities = 24
218 UBool TEST_TABLE
[24];//= new boolean[24];
220 for(i
= 0; i
< 24; ++i
)
221 TEST_TABLE
[i
] = TRUE
;
223 // If we have some sparseness, implement it here. Sparseness decreases
224 // test time by eliminating some tests, up to 23.
225 for(i
= 0; i
< SPARSENESS
; ) {
226 int random
= (int)(randFraction() * 24);
227 if (random
>= 0 && random
< 24 && TEST_TABLE
[i
]) {
228 TEST_TABLE
[i
] = FALSE
;
235 for(style
= DateFormat::FULL
; style
<= DateFormat::SHORT
; ++style
) {
236 if(TEST_TABLE
[itable
++]) {
237 logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle
)style
)));
238 DateFormat
*df
= DateFormat::createDateInstance((DateFormat::EStyle
)style
, loc
);
240 errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle
)style
)) + " Locale: " + loc
.getDisplayName(temp
));
248 for(style
= DateFormat::FULL
; style
<= DateFormat::SHORT
; ++style
) {
249 if (TEST_TABLE
[itable
++]) {
250 logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle
)style
)));
251 DateFormat
*df
= DateFormat::createTimeInstance((DateFormat::EStyle
)style
, loc
);
253 errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle
)style
)) + " Locale: " + loc
.getDisplayName(temp
));
261 for(int32_t dstyle
= DateFormat::FULL
; dstyle
<= DateFormat::SHORT
; ++dstyle
) {
262 for(int32_t tstyle
= DateFormat::FULL
; tstyle
<= DateFormat::SHORT
; ++tstyle
) {
263 if(TEST_TABLE
[itable
++]) {
264 logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle
)dstyle
)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle
)tstyle
)) );
265 DateFormat
*df
= DateFormat::createDateTimeInstance((DateFormat::EStyle
)dstyle
, (DateFormat::EStyle
)tstyle
, loc
);
267 dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle
)dstyle
)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle
)tstyle
)) + "Locale: " + loc
.getDisplayName(temp
));
277 void DateFormatRoundTripTest::test(DateFormat
*fmt
, const Locale
&origLocale
, UBool timeOnly
)
280 if(fmt
->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
281 errln("DateFormat wasn't a SimpleDateFormat");
285 UBool isGregorian
= FALSE
;
286 UErrorCode minStatus
= U_ZERO_ERROR
;
287 UDate minDate
= CalendarTest::minDateOfCalendar(*fmt
->getCalendar(), isGregorian
, minStatus
);
288 if(U_FAILURE(minStatus
)) {
289 errln((UnicodeString
)"Failure getting min date for " + origLocale
.getName());
292 //logln(UnicodeString("Min date is ") + fullFormat(minDate) + " for " + origLocale.getName());
294 pat
= ((SimpleDateFormat
*)fmt
)->toPattern(pat
);
296 // NOTE TO MAINTAINER
297 // This indexOf check into the pattern needs to be refined to ignore
298 // quoted characters. Currently, this isn't a problem with the locale
299 // patterns we have, but it may be a problem later.
301 UBool hasEra
= (pat
.indexOf(UnicodeString("G")) != -1);
302 UBool hasZoneDisplayName
= (pat
.indexOf(UnicodeString("z")) != -1) || (pat
.indexOf(UnicodeString("v")) != -1)
303 || (pat
.indexOf(UnicodeString("V")) != -1);
305 // Because patterns contain incomplete data representing the Date,
306 // we must be careful of how we do the roundtrip. We start with
307 // a randomly generated Date because they're easier to generate.
308 // From this we get a string. The string is our real starting point,
309 // because this string should parse the same way all the time. Note
310 // that it will not necessarily parse back to the original date because
311 // of incompleteness in patterns. For example, a time-only pattern won't
312 // parse back to the same date.
315 for(int i
= 0; i
< TRIALS
; ++i
) {
316 UDate
*d
= new UDate
[DEPTH
];
317 UnicodeString
*s
= new UnicodeString
[DEPTH
];
319 if(isGregorian
== TRUE
) {
320 d
[0] = generateDate();
322 d
[0] = generateDate(minDate
);
325 UErrorCode status
= U_ZERO_ERROR
;
327 // We go through this loop until we achieve a match or until
328 // the maximum loop count is reached. We record the points at
329 // which the date and the string starts to match. Once matching
330 // starts, it should continue.
332 int dmatch
= 0; // d[dmatch].getTime() == d[dmatch-1].getTime()
333 int smatch
= 0; // s[smatch].equals(s[smatch-1])
334 for(loop
= 0; loop
< DEPTH
; ++loop
) {
336 d
[loop
] = fmt
->parse(s
[loop
-1], status
);
337 failure(status
, "fmt->parse", s
[loop
-1]+" in locale: " + origLocale
.getName());
338 status
= U_ZERO_ERROR
; /* any error would have been reported */
341 s
[loop
] = fmt
->format(d
[loop
], s
[loop
]);
343 // For displaying which date is being tested
344 //logln(s[loop] + " = " + fullFormat(d[loop]));
346 if(s
[loop
].length() == 0) {
347 errln("FAIL: fmt->format gave 0-length string in " + pat
+ " with number " + d
[loop
] + " in locale " + origLocale
.getName());
352 UBool match
= s
[loop
] == s
[loop
-1];
358 errln("FAIL: String mismatch after match");
362 // {sfb} watch out here, this might not work
363 UBool match
= d
[loop
]/*.getTime()*/ == d
[loop
-1]/*.getTime()*/;
369 errln("FAIL: Date mismatch after match");
372 if(smatch
!= 0 && dmatch
!= 0)
376 // At this point loop == DEPTH if we've failed, otherwise loop is the
377 // max(smatch, dmatch), that is, the index at which we have string and
380 // Date usually matches in 2. Exceptions handled below.
383 if (dmatch
> maxDmatch
) {
384 // Time-only pattern with zone information and a starting date in PST.
385 if(timeOnly
&& hasZoneDisplayName
) {
386 int32_t startRaw
, startDst
;
387 fmt
->getTimeZone().getOffset(d
[0], FALSE
, startRaw
, startDst
, status
);
388 failure(status
, "TimeZone::getOffset");
389 // if the start offset is greater than the offset on Jan 1, 1970
390 // in PST, then need one more round trip. There are two cases
391 // fall into this category. The start date is 1) DST or
392 // 2) LMT (GMT-07:52:58).
393 if (startRaw
+ startDst
> -28800000) {
400 // String usually matches in 1. Exceptions are checked for here.
401 if(smatch
> maxSmatch
) { // Don't compute unless necessary
403 // Starts in BC, with no era in pattern
404 if( ! hasEra
&& getField(d
[0], UCAL_ERA
) == GregorianCalendar::BC
)
406 // Starts in DST, no year in pattern
407 else if((in0
=fmt
->getTimeZone().inDaylightTime(d
[0], status
)) && ! failure(status
, "gettingDaylightTime") &&
408 pat
.indexOf(UnicodeString("yyyy")) == -1)
410 // If we start not in DST, but transition into DST
412 fmt
->getTimeZone().inDaylightTime(d
[1], status
) && !failure(status
, "gettingDaylightTime"))
414 // Two digit year with no time zone change,
415 // unless timezone isn't used or we aren't close to the DST changover
416 else if (pat
.indexOf(UnicodeString("y")) != -1
417 && pat
.indexOf(UnicodeString("yyyy")) == -1
418 && getField(d
[0], UCAL_YEAR
)
419 != getField(d
[dmatch
], UCAL_YEAR
)
420 && !failure(status
, "error status [smatch>maxSmatch]")
421 && ((hasZoneDisplayName
422 && (fmt
->getTimeZone().inDaylightTime(d
[0], status
)
423 == fmt
->getTimeZone().inDaylightTime(d
[dmatch
], status
)
424 || getField(d
[0], UCAL_MONTH
) == UCAL_APRIL
425 || getField(d
[0], UCAL_MONTH
) == UCAL_OCTOBER
))
426 || !hasZoneDisplayName
)
431 // If zone display name is used, fallback format might be used before 1970
432 else if (hasZoneDisplayName
&& d
[0] < 0) {
437 if(dmatch
> maxDmatch
|| smatch
> maxSmatch
) { // Special case for Japanese and Islamic (could have large negative years)
438 const char *type
= fmt
->getCalendar()->getType();
439 if(!strcmp(type
,"japanese") || (!strcmp(type
,"buddhist"))) {
445 // Use @v to see verbose results on successful cases
446 UBool fail
= (dmatch
> maxDmatch
|| smatch
> maxSmatch
);
447 if (optionv
|| fail
) {
449 errln(UnicodeString("\nFAIL: Pattern: ") + pat
+
450 " in Locale: " + origLocale
.getName());
452 errln(UnicodeString("\nOk: Pattern: ") + pat
+
453 " in Locale: " + origLocale
.getName());
456 logln("Date iters until match=%d (max allowed=%d), string iters until match=%d (max allowed=%d)",
457 dmatch
,maxDmatch
, smatch
, maxSmatch
);
459 for(int j
= 0; j
<= loop
&& j
< DEPTH
; ++j
) {
461 FieldPosition
pos(FieldPosition::DONT_CARE
);
462 errln((j
>0?" P> ":" ") + fullFormat(d
[j
]) + " F> " +
463 escape(s
[j
], temp
) + UnicodeString(" d=") + d
[j
] +
464 (j
> 0 && d
[j
]/*.getTime()*/==d
[j
-1]/*.getTime()*/?" d==":"") +
465 (j
> 0 && s
[j
] == s
[j
-1]?" s==":""));
472 catch (ParseException e) {
473 errln("Exception: " + e.getMessage());
478 const UnicodeString
& DateFormatRoundTripTest::fullFormat(UDate d
) {
479 UErrorCode ec
= U_ZERO_ERROR
;
480 if (dateFormat
== 0) {
481 dateFormat
= new SimpleDateFormat((UnicodeString
)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", ec
);
482 if (U_FAILURE(ec
) || dateFormat
== 0) {
483 fgStr
= "[FAIL: SimpleDateFormat constructor]";
490 dateFormat
->format(d
, fgStr
);
495 * Return a field of the given date
497 int32_t DateFormatRoundTripTest::getField(UDate d
, int32_t f
) {
498 // Should be synchronized, but we're single threaded so it's ok
499 UErrorCode status
= U_ZERO_ERROR
;
500 getFieldCal
->setTime(d
, status
);
501 failure(status
, "getfieldCal->setTime");
502 int32_t ret
= getFieldCal
->get((UCalendarDateFields
)f
, status
);
503 failure(status
, "getfieldCal->get");
507 UnicodeString
& DateFormatRoundTripTest::escape(const UnicodeString
& src
, UnicodeString
& dst
)
510 for (int32_t i
= 0; i
< src
.length(); ++i
) {
515 dst
+= UnicodeString("[");
517 sprintf(buf
, "%#x", c
);
518 dst
+= UnicodeString(buf
);
519 dst
+= UnicodeString("]");
526 #define U_MILLIS_PER_YEAR (365.25 * 24 * 60 * 60 * 1000)
528 UDate
DateFormatRoundTripTest::generateDate(UDate minDate
)
530 // Bring range in conformance to generateDate() below.
531 if(minDate
< (U_MILLIS_PER_YEAR
* -(4000-1970))) {
532 minDate
= (U_MILLIS_PER_YEAR
* -(4000-1970));
534 for(int i
=0;i
<8;i
++) {
535 double a
= randFraction();
537 // Range from (min) to (8000-1970) AD
538 double dateRange
= (0.0 - minDate
) + (U_MILLIS_PER_YEAR
+ (8000-1970));
542 // Now offset from minDate
553 UDate
DateFormatRoundTripTest::generateDate()
555 double a
= randFraction();
557 // Now 'a' ranges from 0..1; scale it to range from 0 to 8000 years
560 // Range from (4000-1970) BC to (8000-1970) AD
563 // Now scale up to ms
564 a
*= 365.25 * 24 * 60 * 60 * 1000;
566 //return new Date((long)a);
570 #endif /* #if !UCONFIG_NO_FORMATTING */