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