]> git.saurik.com Git - apple/icu.git/blob - icuSources/test/intltest/dtfmtrtts.cpp
ICU-8.11.1.tar.gz
[apple/icu.git] / icuSources / test / intltest / dtfmtrtts.cpp
1 /***********************************************************************
2 * COPYRIGHT:
3 * Copyright (c) 1997-2006, International Business Machines Corporation
4 * and others. All Rights Reserved.
5 ***********************************************************************/
6
7 #include "unicode/utypes.h"
8
9 #if !UCONFIG_NO_FORMATTING
10
11 #include "unicode/datefmt.h"
12 #include "unicode/smpdtfmt.h"
13 #include "unicode/gregocal.h"
14 #include "dtfmtrtts.h"
15 #include "caltest.h"
16
17 #include <stdio.h>
18 #include <string.h>
19
20 // *****************************************************************************
21 // class DateFormatRoundTripTest
22 // *****************************************************************************
23
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!!!
27 #ifndef INFINITE
28 #define INFINITE 0
29 #endif
30
31 // Define this to test just a single locale
32 //#define TEST_ONE_LOC "cs_CZ"
33
34 // If SPARSENESS is > 0, we don't run each exhaustive possibility.
35 // There are 24 total possible tests per each locale. A SPARSENESS
36 // of 12 means we run half of them. A SPARSENESS of 23 means we run
37 // 1 of them. SPARSENESS _must_ be in the range 0..23.
38 int32_t DateFormatRoundTripTest::SPARSENESS = 0;
39 int32_t DateFormatRoundTripTest::TRIALS = 4;
40 int32_t DateFormatRoundTripTest::DEPTH = 5;
41
42 DateFormatRoundTripTest::DateFormatRoundTripTest() : dateFormat(0) {
43 }
44
45 DateFormatRoundTripTest::~DateFormatRoundTripTest() {
46 delete dateFormat;
47 }
48
49 #define CASE(id,test) case id: name = #test; if (exec) { logln(#test "---"); logln((UnicodeString)""); test(); } break;
50
51 void
52 DateFormatRoundTripTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* par )
53 {
54 optionv = (par && *par=='v');
55 switch (index) {
56 CASE(0,TestDateFormatRoundTrip)
57 CASE(1, TestCentury)
58 default: name = ""; break;
59 }
60 }
61
62 UBool
63 DateFormatRoundTripTest::failure(UErrorCode status, const char* msg)
64 {
65 if(U_FAILURE(status)) {
66 errln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status));
67 return TRUE;
68 }
69
70 return FALSE;
71 }
72
73 UBool
74 DateFormatRoundTripTest::failure(UErrorCode status, const char* msg, const UnicodeString& str)
75 {
76 if(U_FAILURE(status)) {
77 UnicodeString escaped;
78 escape(str,escaped);
79 errln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status) + ", str=" + escaped);
80 return TRUE;
81 }
82
83 return FALSE;
84 }
85
86 void DateFormatRoundTripTest::TestCentury()
87 {
88 UErrorCode status = U_ZERO_ERROR;
89 Locale locale("es_PA");
90 UnicodeString pattern = "MM/dd/yy hh:mm:ss a z";
91 SimpleDateFormat fmt(pattern, locale, status);
92 if(!assertSuccess("trying to construct", status))return;
93 UDate date[] = {-55018555891590.05, 0, 0};
94 UnicodeString result[2];
95
96 fmt.format(date[0], result[0]);
97 date[1] = fmt.parse(result[0], status);
98 fmt.format(date[1], result[1]);
99 date[2] = fmt.parse(result[1], status);
100
101 if (date[1] != date[2] || result[0] != result[1]) {
102 errln("Round trip failure: \"%S\" (%f), \"%S\" (%f)", result[0].getBuffer(), date[1], result[1].getBuffer(), date[2]);
103 }
104 }
105
106 // ==
107
108 void DateFormatRoundTripTest::TestDateFormatRoundTrip()
109 {
110 UErrorCode status = U_ZERO_ERROR;
111
112 getFieldCal = Calendar::createInstance(status);
113 failure(status, "Calendar::createInstance");
114 if(!assertSuccess("trying to construct", status))return;
115
116
117 int32_t locCount = 0;
118 const Locale *avail = DateFormat::getAvailableLocales(locCount);
119 logln("DateFormat available locales: %d", locCount);
120 if(quick) {
121 SPARSENESS = 18;
122 logln("Quick mode: only testing SPARSENESS = 18");
123 }
124 TimeZone *tz = TimeZone::createDefault();
125 UnicodeString temp;
126 logln("Default TimeZone: " + tz->getID(temp));
127 delete tz;
128
129 #ifdef TEST_ONE_LOC // define this to just test ONE locale.
130 Locale loc(TEST_ONE_LOC);
131 test(loc);
132 #if INFINITE
133 for(;;) {
134 test(loc);
135 }
136 #endif
137
138 #else
139 # if INFINITE
140 // Special infinite loop test mode for finding hard to reproduce errors
141 Locale loc = Locale::getDefault();
142 logln("ENTERING INFINITE TEST LOOP FOR Locale: " + loc.getDisplayName(temp));
143 for(;;)
144 test(loc);
145 # else
146 test(Locale::getDefault());
147
148 #if 1
149 // installed locales
150 for (int i=0; i < locCount; ++i) {
151 test(avail[i]);
152 }
153 #endif
154
155 #if 1
156 // special locales
157 int32_t jCount = CalendarTest::testLocaleCount();
158 for (int32_t j=0; j < jCount; ++j) {
159 test(Locale(CalendarTest::testLocaleID(j)));
160 }
161 #endif
162
163 # endif
164 #endif
165
166 delete getFieldCal;
167 }
168
169 static const char *styleName(DateFormat::EStyle s)
170 {
171 switch(s)
172 {
173 case DateFormat::SHORT: return "SHORT";
174 case DateFormat::MEDIUM: return "MEDIUM";
175 case DateFormat::LONG: return "LONG";
176 case DateFormat::FULL: return "FULL";
177 // case DateFormat::DEFAULT: return "DEFAULT";
178 case DateFormat::DATE_OFFSET: return "DATE_OFFSET";
179 case DateFormat::NONE: return "NONE";
180 case DateFormat::DATE_TIME: return "DATE_TIME";
181 default: return "Unknown";
182 }
183 }
184
185 void DateFormatRoundTripTest::test(const Locale& loc)
186 {
187 UnicodeString temp;
188 #if !INFINITE
189 logln("Locale: " + loc.getDisplayName(temp));
190 #endif
191
192 // Total possibilities = 24
193 // 4 date
194 // 4 time
195 // 16 date-time
196 UBool TEST_TABLE [24];//= new boolean[24];
197 int32_t i = 0;
198 for(i = 0; i < 24; ++i)
199 TEST_TABLE[i] = TRUE;
200
201 // If we have some sparseness, implement it here. Sparseness decreases
202 // test time by eliminating some tests, up to 23.
203 for(i = 0; i < SPARSENESS; ) {
204 int random = (int)(randFraction() * 24);
205 if (random >= 0 && random < 24 && TEST_TABLE[i]) {
206 TEST_TABLE[i] = FALSE;
207 ++i;
208 }
209 }
210
211 int32_t itable = 0;
212 int32_t style = 0;
213 for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
214 if(TEST_TABLE[itable++]) {
215 logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
216 DateFormat *df = DateFormat::createDateInstance((DateFormat::EStyle)style, loc);
217 if(df == NULL) {
218 errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp));
219 } else {
220 test(df, loc);
221 delete df;
222 }
223 }
224 }
225
226 for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
227 if (TEST_TABLE[itable++]) {
228 logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
229 DateFormat *df = DateFormat::createTimeInstance((DateFormat::EStyle)style, loc);
230 if(df == NULL) {
231 errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp));
232 } else {
233 test(df, loc, TRUE);
234 delete df;
235 }
236 }
237 }
238
239 for(int32_t dstyle = DateFormat::FULL; dstyle <= DateFormat::SHORT; ++dstyle) {
240 for(int32_t tstyle = DateFormat::FULL; tstyle <= DateFormat::SHORT; ++tstyle) {
241 if(TEST_TABLE[itable++]) {
242 logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) );
243 DateFormat *df = DateFormat::createDateTimeInstance((DateFormat::EStyle)dstyle, (DateFormat::EStyle)tstyle, loc);
244 if(df == NULL) {
245 errln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) + "Locale: " + loc.getDisplayName(temp));
246 } else {
247 test(df, loc);
248 delete df;
249 }
250 }
251 }
252 }
253 }
254
255 void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UBool timeOnly)
256 {
257 UnicodeString pat;
258 if(fmt->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
259 errln("DateFormat wasn't a SimpleDateFormat");
260 return;
261 }
262
263 UBool isGregorian = FALSE;
264 UErrorCode minStatus = U_ZERO_ERROR;
265 UDate minDate = CalendarTest::minDateOfCalendar(*fmt->getCalendar(), isGregorian, minStatus);
266 if(U_FAILURE(minStatus)) {
267 errln((UnicodeString)"Failure getting min date for " + origLocale.getName());
268 return;
269 }
270 //logln(UnicodeString("Min date is ") + fullFormat(minDate) + " for " + origLocale.getName());
271
272 pat = ((SimpleDateFormat*)fmt)->toPattern(pat);
273
274 // NOTE TO MAINTAINER
275 // This indexOf check into the pattern needs to be refined to ignore
276 // quoted characters. Currently, this isn't a problem with the locale
277 // patterns we have, but it may be a problem later.
278
279 UBool hasEra = (pat.indexOf(UnicodeString("G")) != -1);
280 UBool hasZone = (pat.indexOf(UnicodeString("Z")) != -1) || (pat.indexOf(UnicodeString("z")) != -1) || (pat.indexOf(UnicodeString("v")) != -1);
281
282 // Because patterns contain incomplete data representing the Date,
283 // we must be careful of how we do the roundtrip. We start with
284 // a randomly generated Date because they're easier to generate.
285 // From this we get a string. The string is our real starting point,
286 // because this string should parse the same way all the time. Note
287 // that it will not necessarily parse back to the original date because
288 // of incompleteness in patterns. For example, a time-only pattern won't
289 // parse back to the same date.
290
291 //try {
292 for(int i = 0; i < TRIALS; ++i) {
293 UDate *d = new UDate [DEPTH];
294 UnicodeString *s = new UnicodeString[DEPTH];
295
296 if(isGregorian == TRUE) {
297 d[0] = generateDate();
298 } else {
299 d[0] = generateDate(minDate);
300 }
301
302 UErrorCode status = U_ZERO_ERROR;
303
304 // We go through this loop until we achieve a match or until
305 // the maximum loop count is reached. We record the points at
306 // which the date and the string starts to match. Once matching
307 // starts, it should continue.
308 int loop;
309 int dmatch = 0; // d[dmatch].getTime() == d[dmatch-1].getTime()
310 int smatch = 0; // s[smatch].equals(s[smatch-1])
311 for(loop = 0; loop < DEPTH; ++loop) {
312 if (loop > 0) {
313 d[loop] = fmt->parse(s[loop-1], status);
314 failure(status, "fmt->parse", s[loop-1]+" in locale: " + origLocale.getName());
315 status = U_ZERO_ERROR; /* any error would have been reported */
316 }
317
318 s[loop] = fmt->format(d[loop], s[loop]);
319
320 // For displaying which date is being tested
321 //logln(s[loop] + " = " + fullFormat(d[loop]));
322
323 if(s[loop].length() == 0) {
324 errln("FAIL: fmt->format gave 0-length string in " + pat + " with number " + d[loop] + " in locale " + origLocale.getName());
325 }
326
327 if(loop > 0) {
328 if(smatch == 0) {
329 UBool match = s[loop] == s[loop-1];
330 if(smatch == 0) {
331 if(match)
332 smatch = loop;
333 }
334 else if( ! match)
335 errln("FAIL: String mismatch after match");
336 }
337
338 if(dmatch == 0) {
339 // {sfb} watch out here, this might not work
340 UBool match = d[loop]/*.getTime()*/ == d[loop-1]/*.getTime()*/;
341 if(dmatch == 0) {
342 if(match)
343 dmatch = loop;
344 }
345 else if( ! match)
346 errln("FAIL: Date mismatch after match");
347 }
348
349 if(smatch != 0 && dmatch != 0)
350 break;
351 }
352 }
353 // At this point loop == DEPTH if we've failed, otherwise loop is the
354 // max(smatch, dmatch), that is, the index at which we have string and
355 // date matching.
356
357 // Date usually matches in 2. Exceptions handled below.
358 int maxDmatch = 2;
359 int maxSmatch = 1;
360 if (dmatch > maxDmatch) {
361 // Time-only pattern with zone information and a starting date in PST.
362 if(timeOnly && hasZone && fmt->getTimeZone().inDaylightTime(d[0], status) && ! failure(status, "TimeZone::inDST()")) {
363 maxDmatch = 3;
364 maxSmatch = 2;
365 }
366 }
367
368 // String usually matches in 1. Exceptions are checked for here.
369 if(smatch > maxSmatch) { // Don't compute unless necessary
370 UBool in0;
371 // Starts in BC, with no era in pattern
372 if( ! hasEra && getField(d[0], UCAL_ERA) == GregorianCalendar::BC)
373 maxSmatch = 2;
374 // Starts in DST, no year in pattern
375 else if((in0=fmt->getTimeZone().inDaylightTime(d[0], status)) && ! failure(status, "gettingDaylightTime") &&
376 pat.indexOf(UnicodeString("yyyy")) == -1)
377 maxSmatch = 2;
378 // If we start not in DST, but transition into DST
379 else if (!in0 &&
380 fmt->getTimeZone().inDaylightTime(d[1], status) && !failure(status, "gettingDaylightTime"))
381 maxSmatch = 2;
382 // Two digit year with no time zone change,
383 // unless timezone isn't used or we aren't close to the DST changover
384 else if (pat.indexOf(UnicodeString("y")) != -1
385 && pat.indexOf(UnicodeString("yyyy")) == -1
386 && getField(d[0], UCAL_YEAR)
387 != getField(d[dmatch], UCAL_YEAR)
388 && !failure(status, "error status [smatch>maxSmatch]")
389 && ((hasZone
390 && (fmt->getTimeZone().inDaylightTime(d[0], status)
391 == fmt->getTimeZone().inDaylightTime(d[dmatch], status)
392 || getField(d[0], UCAL_MONTH) == UCAL_APRIL
393 || getField(d[0], UCAL_MONTH) == UCAL_OCTOBER))
394 || !hasZone)
395 )
396 {
397 maxSmatch = 2;
398 }
399 }
400
401 if(dmatch > maxDmatch || smatch > maxSmatch) { // Special case for Japanese and Islamic (could have large negative years)
402 const char *type = fmt->getCalendar()->getType();
403 if(!strcmp(type,"japanese")) {
404 maxSmatch = 4;
405 maxDmatch = 4;
406 }
407 }
408
409 // Use @v to see verbose results on successful cases
410 UBool fail = (dmatch > maxDmatch || smatch > maxSmatch);
411 if (optionv || fail) {
412 if (fail) {
413 errln(UnicodeString("\nFAIL: Pattern: ") + pat +
414 " in Locale: " + origLocale.getName());
415 } else {
416 errln(UnicodeString("\nOk: Pattern: ") + pat +
417 " in Locale: " + origLocale.getName());
418 }
419
420 logln("Date iters until match=%d (max allowed=%d), string iters until match=%d (max allowed=%d)",
421 dmatch,maxDmatch, smatch, maxSmatch);
422
423 for(int j = 0; j <= loop && j < DEPTH; ++j) {
424 UnicodeString temp;
425 FieldPosition pos(FieldPosition::DONT_CARE);
426 errln((j>0?" P> ":" ") + fullFormat(d[j]) + " F> " +
427 escape(s[j], temp) + UnicodeString(" d=") + d[j] +
428 (j > 0 && d[j]/*.getTime()*/==d[j-1]/*.getTime()*/?" d==":"") +
429 (j > 0 && s[j] == s[j-1]?" s==":""));
430 }
431 }
432 delete[] d;
433 delete[] s;
434 }
435 /*}
436 catch (ParseException e) {
437 errln("Exception: " + e.getMessage());
438 logln(e.toString());
439 }*/
440 }
441
442 const UnicodeString& DateFormatRoundTripTest::fullFormat(UDate d) {
443 UErrorCode ec = U_ZERO_ERROR;
444 if (dateFormat == 0) {
445 dateFormat = new SimpleDateFormat((UnicodeString)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", ec);
446 if (U_FAILURE(ec) || dateFormat == 0) {
447 fgStr = "[FAIL: SimpleDateFormat constructor]";
448 delete dateFormat;
449 dateFormat = 0;
450 return fgStr;
451 }
452 }
453 fgStr.truncate(0);
454 dateFormat->format(d, fgStr);
455 return fgStr;
456 }
457
458 /**
459 * Return a field of the given date
460 */
461 int32_t DateFormatRoundTripTest::getField(UDate d, int32_t f) {
462 // Should be synchronized, but we're single threaded so it's ok
463 UErrorCode status = U_ZERO_ERROR;
464 getFieldCal->setTime(d, status);
465 failure(status, "getfieldCal->setTime");
466 int32_t ret = getFieldCal->get((UCalendarDateFields)f, status);
467 failure(status, "getfieldCal->get");
468 return ret;
469 }
470
471 UnicodeString& DateFormatRoundTripTest::escape(const UnicodeString& src, UnicodeString& dst )
472 {
473 dst.remove();
474 for (int32_t i = 0; i < src.length(); ++i) {
475 UChar c = src[i];
476 if(c < 0x0080)
477 dst += c;
478 else {
479 dst += UnicodeString("[");
480 char buf [8];
481 sprintf(buf, "%#x", c);
482 dst += UnicodeString(buf);
483 dst += UnicodeString("]");
484 }
485 }
486
487 return dst;
488 }
489
490 #define U_MILLIS_PER_YEAR (365.25 * 24 * 60 * 60 * 1000)
491
492 UDate DateFormatRoundTripTest::generateDate(UDate minDate)
493 {
494 // Bring range in conformance to generateDate() below.
495 if(minDate < (U_MILLIS_PER_YEAR * -(4000-1970))) {
496 minDate = (U_MILLIS_PER_YEAR * -(4000-1970));
497 }
498 for(int i=0;i<8;i++) {
499 double a = randFraction();
500
501 // Range from (min) to (8000-1970) AD
502 double dateRange = (0.0 - minDate) + (U_MILLIS_PER_YEAR + (8000-1970));
503
504 a *= dateRange;
505
506 // Now offset from minDate
507 a += minDate;
508
509 // Last sanity check
510 if(a>=minDate) {
511 return a;
512 }
513 }
514 return minDate;
515 }
516
517 UDate DateFormatRoundTripTest::generateDate()
518 {
519 double a = randFraction();
520
521 // Now 'a' ranges from 0..1; scale it to range from 0 to 8000 years
522 a *= 8000;
523
524 // Range from (4000-1970) BC to (8000-1970) AD
525 a -= 4000;
526
527 // Now scale up to ms
528 a *= 365.25 * 24 * 60 * 60 * 1000;
529
530 //return new Date((long)a);
531 return a;
532 }
533
534 #endif /* #if !UCONFIG_NO_FORMATTING */
535
536 //eof