2 *******************************************************************************
3 * Copyright (C) 2007-2011, International Business Machines Corporation and *
4 * others. All Rights Reserved. *
5 *******************************************************************************
7 #include "unicode/utypes.h"
9 #if !UCONFIG_NO_FORMATTING
13 #include "simplethread.h"
14 #include "unicode/timezone.h"
15 #include "unicode/simpletz.h"
16 #include "unicode/calendar.h"
17 #include "unicode/strenum.h"
18 #include "unicode/smpdtfmt.h"
19 #include "unicode/uchar.h"
20 #include "unicode/basictz.h"
23 static const char* PATTERNS[] = {"z", "zzzz", "Z", "ZZZZ", "v", "vvvv", "V", "VVVV"};
24 static const int NUM_PATTERNS = sizeof(PATTERNS)/sizeof(const char*);
27 TimeZoneFormatTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
30 logln("TestSuite TimeZoneFormatTest");
33 TESTCASE(0, TestTimeZoneRoundTrip);
34 TESTCASE(1, TestTimeRoundTrip);
35 default: name = ""; break;
40 TimeZoneFormatTest::TestTimeZoneRoundTrip(void) {
41 UErrorCode status = U_ZERO_ERROR;
43 SimpleTimeZone unknownZone(-31415, (UnicodeString)"Etc/Unknown");
44 int32_t badDstOffset = -1234;
45 int32_t badZoneOffset = -2345;
47 int32_t testDateData[][3] = {
56 Calendar *cal = Calendar::createInstance(TimeZone::createTimeZone((UnicodeString)"UTC"), status);
57 if (U_FAILURE(status)) {
58 dataerrln("Calendar::createInstance failed: %s", u_errorName(status));
62 // Set up rule equivalency test range
64 cal->set(1900, UCAL_JANUARY, 1);
65 low = cal->getTime(status);
66 cal->set(2040, UCAL_JANUARY, 1);
67 high = cal->getTime(status);
68 if (U_FAILURE(status)) {
69 errln("getTime failed");
74 UDate DATES[(sizeof(testDateData)/sizeof(int32_t))/3];
75 const int32_t nDates = (sizeof(testDateData)/sizeof(int32_t))/3;
77 for (int32_t i = 0; i < nDates; i++) {
78 cal->set(testDateData[i][0], testDateData[i][1], testDateData[i][2]);
79 DATES[i] = cal->getTime(status);
80 if (U_FAILURE(status)) {
81 errln("getTime failed");
86 // Set up test locales
87 const Locale testLocales[] = {
94 const Locale *LOCALES;
98 LOCALES = testLocales;
99 nLocales = sizeof(testLocales)/sizeof(Locale);
101 LOCALES = Locale::getAvailableLocales(nLocales);
104 StringEnumeration *tzids = TimeZone::createEnumeration();
105 int32_t inRaw, inDst;
106 int32_t outRaw, outDst;
108 // Run the roundtrip test
109 for (int32_t locidx = 0; locidx < nLocales; locidx++) {
110 UnicodeString localGMTString;
111 SimpleDateFormat gmtFmt(UnicodeString("ZZZZ"), LOCALES[locidx], status);
112 gmtFmt.setTimeZone(*TimeZone::getGMT());
113 gmtFmt.format(0.0, localGMTString);
115 for (int32_t patidx = 0; patidx < NUM_PATTERNS; patidx++) {
117 SimpleDateFormat *sdf = new SimpleDateFormat((UnicodeString)PATTERNS[patidx], LOCALES[locidx], status);
118 if (U_FAILURE(status)) {
119 errcheckln(status, (UnicodeString)"new SimpleDateFormat failed for pattern " +
120 PATTERNS[patidx] + " for locale " + LOCALES[locidx].getName() + " - " + u_errorName(status));
121 status = U_ZERO_ERROR;
125 tzids->reset(status);
126 const UnicodeString *tzid;
127 while ((tzid = tzids->snext(status))) {
128 TimeZone *tz = TimeZone::createTimeZone(*tzid);
130 for (int32_t datidx = 0; datidx < nDates; datidx++) {
132 FieldPosition fpos(0);
134 sdf->setTimeZone(*tz);
135 sdf->format(DATES[datidx], tzstr, fpos);
137 // Before parse, set unknown zone to SimpleDateFormat instance
138 // just for making sure that it does not depends on the time zone
140 sdf->setTimeZone(unknownZone);
143 ParsePosition pos(0);
144 Calendar *outcal = Calendar::createInstance(unknownZone, status);
145 if (U_FAILURE(status)) {
146 errln("Failed to create an instance of calendar for receiving parse result.");
147 status = U_ZERO_ERROR;
150 outcal->set(UCAL_DST_OFFSET, badDstOffset);
151 outcal->set(UCAL_ZONE_OFFSET, badZoneOffset);
153 sdf->parse(tzstr, *outcal, pos);
156 const TimeZone &outtz = outcal->getTimeZone();
157 UnicodeString outtzid;
158 outtz.getID(outtzid);
160 tz->getOffset(DATES[datidx], false, inRaw, inDst, status);
161 if (U_FAILURE(status)) {
162 errln((UnicodeString)"Failed to get offsets from time zone" + *tzid);
163 status = U_ZERO_ERROR;
165 outtz.getOffset(DATES[datidx], false, outRaw, outDst, status);
166 if (U_FAILURE(status)) {
167 errln((UnicodeString)"Failed to get offsets from time zone" + outtzid);
168 status = U_ZERO_ERROR;
171 if (uprv_strcmp(PATTERNS[patidx], "VVVV") == 0) {
172 // Location: time zone rule must be preserved except
173 // zones not actually associated with a specific location.
174 // Time zones in this category do not have "/" in its ID.
175 UnicodeString canonical;
176 TimeZone::getCanonicalID(*tzid, canonical, status);
177 if (U_FAILURE(status)) {
178 // Uknown ID - we should not get here
179 errln((UnicodeString)"Unknown ID " + *tzid);
180 status = U_ZERO_ERROR;
181 } else if (outtzid != canonical) {
182 // Canonical ID did not match - check the rules
183 if (!((BasicTimeZone*)&outtz)->hasEquivalentTransitions((BasicTimeZone&)*tz, low, high, TRUE, status)) {
184 if (canonical.indexOf((UChar)0x27 /*'/'*/) == -1) {
185 // Exceptional cases, such as CET, EET, MET and WET
186 logln("Canonical round trip failed (as expected); tz=" + *tzid
187 + ", locale=" + LOCALES[locidx].getName() + ", pattern=" + PATTERNS[patidx]
188 + ", time=" + DATES[datidx] + ", str=" + tzstr
189 + ", outtz=" + outtzid);
191 errln("Canonical round trip failed; tz=" + *tzid
192 + ", locale=" + LOCALES[locidx].getName() + ", pattern=" + PATTERNS[patidx]
193 + ", time=" + DATES[datidx] + ", str=" + tzstr
194 + ", outtz=" + outtzid);
196 if (U_FAILURE(status)) {
197 errln("hasEquivalentTransitions failed");
198 status = U_ZERO_ERROR;
204 // Check if localized GMT format or RFC format is used.
205 int32_t numDigits = 0;
206 for (int n = 0; n < tzstr.length(); n++) {
207 if (u_isdigit(tzstr.charAt(n))) {
211 if (tzstr == localGMTString || numDigits >= 3) {
212 // Localized GMT or RFC: total offset (raw + dst) must be preserved.
213 int32_t inOffset = inRaw + inDst;
214 int32_t outOffset = outRaw + outDst;
215 if (inOffset != outOffset) {
216 errln((UnicodeString)"Offset round trip failed; tz=" + *tzid
217 + ", locale=" + LOCALES[locidx].getName() + ", pattern=" + PATTERNS[patidx]
218 + ", time=" + DATES[datidx] + ", str=" + tzstr
219 + ", inOffset=" + inOffset + ", outOffset=" + outOffset);
222 // Specific or generic: raw offset must be preserved.
223 if (inRaw != outRaw) {
224 errln((UnicodeString)"Raw offset round trip failed; tz=" + *tzid
225 + ", locale=" + LOCALES[locidx].getName() + ", pattern=" + PATTERNS[patidx]
226 + ", time=" + DATES[datidx] + ", str=" + tzstr
227 + ", inRawOffset=" + inRaw + ", outRawOffset=" + outRaw);
246 const Locale* locales; // Static
247 int32_t nLocales; // Static
248 UBool quick; // Static
249 UDate START_TIME; // Static
250 UDate END_TIME; // Static
254 class TestTimeRoundTripThread: public SimpleThread {
256 TestTimeRoundTripThread(IntlTest& tlog, LocaleData &ld, int32_t i)
257 : log(tlog), data(ld), index(i) {}
259 UErrorCode status = U_ZERO_ERROR;
260 UBool REALLY_VERBOSE = FALSE;
262 // Whether each pattern is ambiguous at DST->STD local time overlap
263 UBool AMBIGUOUS_DST_DECESSION[] = { FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE };
264 // Whether each pattern is ambiguous at STD->STD/DST->DST local time overlap
265 UBool AMBIGUOUS_NEGATIVE_SHIFT[] = { TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE };
267 // Workaround for #6338
268 //UnicodeString BASEPATTERN("yyyy-MM-dd'T'HH:mm:ss.SSS");
269 UnicodeString BASEPATTERN("yyyy.MM.dd HH:mm:ss.SSS");
271 // timer for performance analysis
274 UBool expectedRoundTrip[4];
277 StringEnumeration *tzids = TimeZone::createTimeZoneIDEnumeration(UCAL_ZONE_TYPE_CANONICAL, NULL, NULL, status);
278 if (U_FAILURE(status)) {
279 if (status == U_MISSING_RESOURCE_ERROR) {
280 /* This error is generally caused by data not being present. However, an infinite loop will occur
281 * because the thread thinks that the test data is never done so we should treat the data as done.
283 log.dataerrln("TimeZone::createTimeZoneIDEnumeration failed - %s", u_errorName(status));
284 data.numDone = data.nLocales;
286 log.errln("TimeZone::createTimeZoneIDEnumeration failed: %s", u_errorName(status));
292 UDate times[NUM_PATTERNS];
293 for (int32_t i = 0; i < NUM_PATTERNS; i++) {
297 int32_t testCounts = 0;
300 umtx_lock(NULL); // Lock to increment the index
301 for (int32_t i = 0; i < NUM_PATTERNS; i++) {
302 data.times[i] += times[i];
303 data.testCounts += testCounts;
305 if (data.index < data.nLocales) {
311 umtx_unlock(NULL); // Unlock for other threads to use
314 log.logln((UnicodeString) "Thread " + index + " is done.");
318 log.logln((UnicodeString) "\nThread " + index + ": Locale: " + UnicodeString(data.locales[locidx].getName()));
320 for (int32_t patidx = 0; patidx < NUM_PATTERNS; patidx++) {
321 log.logln((UnicodeString) " Pattern: " + PATTERNS[patidx]);
324 UnicodeString pattern(BASEPATTERN);
325 pattern.append(" ").append(PATTERNS[patidx]);
327 SimpleDateFormat *sdf = new SimpleDateFormat(pattern, data.locales[locidx], status);
328 if (U_FAILURE(status)) {
329 log.errcheckln(status, (UnicodeString) "new SimpleDateFormat failed for pattern " +
330 pattern + " for locale " + data.locales[locidx].getName() + " - " + u_errorName(status));
331 status = U_ZERO_ERROR;
335 tzids->reset(status);
336 const UnicodeString *tzid;
338 timer = Calendar::getNow();
340 while ((tzid = tzids->snext(status))) {
341 BasicTimeZone *tz = (BasicTimeZone*) TimeZone::createTimeZone(*tzid);
342 sdf->setTimeZone(*tz);
344 UDate t = data.START_TIME;
345 TimeZoneTransition tzt;
346 UBool tztAvail = FALSE;
349 while (t < data.END_TIME) {
352 expectedRoundTrip[0] = TRUE;
355 int32_t fromOffset = tzt.getFrom()->getRawOffset() + tzt.getFrom()->getDSTSavings();
356 int32_t toOffset = tzt.getTo()->getRawOffset() + tzt.getTo()->getDSTSavings();
357 int32_t delta = toOffset - fromOffset;
359 UBool isDstDecession = tzt.getFrom()->getDSTSavings() > 0 && tzt.getTo()->getDSTSavings() == 0;
360 testTimes[0] = t + delta - 1;
361 expectedRoundTrip[0] = TRUE;
362 testTimes[1] = t + delta;
363 expectedRoundTrip[1] = isDstDecession ? !AMBIGUOUS_DST_DECESSION[patidx] : !AMBIGUOUS_NEGATIVE_SHIFT[patidx];
364 testTimes[2] = t - 1;
365 expectedRoundTrip[2] = isDstDecession ? !AMBIGUOUS_DST_DECESSION[patidx] : !AMBIGUOUS_NEGATIVE_SHIFT[patidx];
367 expectedRoundTrip[3] = TRUE;
370 testTimes[0] = t - 1;
371 expectedRoundTrip[0] = TRUE;
373 expectedRoundTrip[1] = TRUE;
377 for (int32_t testidx = 0; testidx < testLen; testidx++) {
379 // reduce regular test time
380 if (!expectedRoundTrip[testidx]) {
388 FieldPosition fpos(0);
389 sdf->format(testTimes[testidx], text, fpos);
391 UDate parsedDate = sdf->parse(text, status);
392 if (U_FAILURE(status)) {
393 log.errln((UnicodeString) "Parse failure for text=" + text + ", tzid=" + *tzid + ", locale=" + data.locales[locidx].getName()
394 + ", pattern=" + PATTERNS[patidx] + ", time=" + testTimes[testidx]);
395 status = U_ZERO_ERROR;
398 if (parsedDate != testTimes[testidx]) {
399 UnicodeString msg = (UnicodeString) "Time round trip failed for " + "tzid=" + *tzid + ", locale=" + data.locales[locidx].getName() + ", pattern=" + PATTERNS[patidx]
400 + ", text=" + text + ", time=" + testTimes[testidx] + ", restime=" + parsedDate + ", diff=" + (parsedDate - testTimes[testidx]);
401 if (expectedRoundTrip[testidx]) {
402 log.errln((UnicodeString) "FAIL: " + msg);
403 } else if (REALLY_VERBOSE) {
408 tztAvail = tz->getNextTransition(t, FALSE, tzt);
413 // Test the date in the middle of two transitions.
414 t += (int64_t) ((tzt.getTime() - t) / 2);
423 times[patidx] += (Calendar::getNow() - timer);
439 TimeZoneFormatTest::TestTimeRoundTrip(void) {
440 int32_t nThreads = threadCount;
441 const Locale *LOCALES;
443 int32_t testCounts = 0;
445 UErrorCode status = U_ZERO_ERROR;
446 Calendar *cal = Calendar::createInstance(TimeZone::createTimeZone((UnicodeString) "UTC"), status);
447 if (U_FAILURE(status)) {
448 dataerrln("Calendar::createInstance failed: %s", u_errorName(status));
452 const char* testAllProp = getProperty("TimeZoneRoundTripAll");
453 UBool bTestAll = (testAllProp && uprv_strcmp(testAllProp, "true") == 0);
455 UDate START_TIME, END_TIME;
456 if (bTestAll || !quick) {
457 cal->set(1900, UCAL_JANUARY, 1);
459 cal->set(1990, UCAL_JANUARY, 1);
461 START_TIME = cal->getTime(status);
463 cal->set(2015, UCAL_JANUARY, 1);
464 END_TIME = cal->getTime(status);
466 if (U_FAILURE(status)) {
467 errln("getTime failed");
471 UDate times[NUM_PATTERNS];
472 for (int32_t i = 0; i < NUM_PATTERNS; i++) {
476 // Set up test locales
477 const Locale locales1[] = {Locale("en")};
478 const Locale locales2[] = {
479 Locale("ar_EG"), Locale("bg_BG"), Locale("ca_ES"), Locale("da_DK"), Locale("de"),
480 Locale("de_DE"), Locale("el_GR"), Locale("en"), Locale("en_AU"), Locale("en_CA"),
481 Locale("en_US"), Locale("es"), Locale("es_ES"), Locale("es_MX"), Locale("fi_FI"),
482 Locale("fr"), Locale("fr_CA"), Locale("fr_FR"), Locale("he_IL"), Locale("hu_HU"),
483 Locale("it"), Locale("it_IT"), Locale("ja"), Locale("ja_JP"), Locale("ko"),
484 Locale("ko_KR"), Locale("nb_NO"), Locale("nl_NL"), Locale("nn_NO"), Locale("pl_PL"),
485 Locale("pt"), Locale("pt_BR"), Locale("pt_PT"), Locale("ru_RU"), Locale("sv_SE"),
486 Locale("th_TH"), Locale("tr_TR"), Locale("zh"), Locale("zh_Hans"), Locale("zh_Hans_CN"),
487 Locale("zh_Hant"), Locale("zh_Hant_TW")
491 LOCALES = Locale::getAvailableLocales(nLocales);
494 nLocales = sizeof(locales1)/sizeof(Locale);
497 nLocales = sizeof(locales2)/sizeof(Locale);
502 data.testCounts = testCounts;
504 data.locales = LOCALES;
505 data.nLocales = nLocales;
507 data.START_TIME = START_TIME;
508 data.END_TIME = END_TIME;
511 #if (ICU_USE_THREADS==0)
512 TestTimeRoundTripThread fakeThread(*this, data, 0);
515 TestTimeRoundTripThread **threads = new TestTimeRoundTripThread*[threadCount];
517 for (i = 0; i < nThreads; i++) {
518 threads[i] = new TestTimeRoundTripThread(*this, data, i);
519 if (threads[i]->start() != 0) {
520 errln("Error starting thread %d", i);
527 if (data.numDone == nLocales) {
533 SimpleThread::sleep(1000);
536 for (i = 0; i < nThreads; i++) {
543 logln("### Elapsed time by patterns ###");
544 for (int32_t i = 0; i < NUM_PATTERNS; i++) {
545 logln(UnicodeString("") + data.times[i] + "ms (" + PATTERNS[i] + ")");
546 total += data.times[i];
548 logln((UnicodeString) "Total: " + total + "ms");
549 logln((UnicodeString) "Iteration: " + data.testCounts);
554 #endif /* #if !UCONFIG_NO_FORMATTING */