• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 *******************************************************************************
5 *
6 *   Copyright (C) 2007-2016, International Business Machines
7 *   Corporation and others.  All Rights Reserved.
8 *
9 *******************************************************************************
10 *   file name:  udatpg_test.c
11 *   encoding:   UTF-8
12 *   tab size:   8 (not used)
13 *   indentation:4
14 *
15 *   created on: 2007aug01
16 *   created by: Markus W. Scherer
17 *
18 *   Test of the C wrapper for the DateTimePatternGenerator.
19 *   Calls each C API function and exercises code paths in the wrapper,
20 *   but the full functionality is tested in the C++ intltest.
21 *
22 *   One item to note: C API functions which return a const UChar *
23 *   should return a NUL-terminated string.
24 *   (The C++ implementation needs to use getTerminatedBuffer()
25 *   on UnicodeString objects which end up being returned this way.)
26 */
27 
28 #include "unicode/utypes.h"
29 
30 #if !UCONFIG_NO_FORMATTING
31 
32 #include <stdbool.h>
33 #include <stdio.h> // for sprintf()
34 
35 #include "unicode/udat.h"
36 #include "unicode/udatpg.h"
37 #include "unicode/ustring.h"
38 #include "cintltst.h"
39 #include "cmemory.h"
40 
41 void addDateTimePatternGeneratorTest(TestNode** root);
42 
43 #define TESTCASE(x) addTest(root, &x, "tsformat/udatpg_test/" #x)
44 
45 static void TestOpenClose(void);
46 static void TestUsage(void);
47 static void TestBuilder(void);
48 static void TestOptions(void);
49 static void TestGetFieldDisplayNames(void);
50 static void TestGetDefaultHourCycle(void);
51 static void TestGetDefaultHourCycleOnEmptyInstance(void);
52 static void TestEras(void);
53 static void TestDateTimePatterns(void);
54 static void TestRegionOverride(void);
55 static void TestISO8601(void);
56 
57 
addDateTimePatternGeneratorTest(TestNode ** root)58 void addDateTimePatternGeneratorTest(TestNode** root) {
59     TESTCASE(TestOpenClose);
60     TESTCASE(TestUsage);
61     TESTCASE(TestBuilder);
62     TESTCASE(TestOptions);
63     TESTCASE(TestGetFieldDisplayNames);
64     TESTCASE(TestGetDefaultHourCycle);
65     TESTCASE(TestGetDefaultHourCycleOnEmptyInstance);
66     TESTCASE(TestEras);
67     TESTCASE(TestDateTimePatterns);
68     TESTCASE(TestRegionOverride);
69     TESTCASE(TestISO8601);
70 }
71 
72 /*
73  * Pipe symbol '|'. We pass only the first UChar without NUL-termination.
74  * The second UChar is just to verify that the API does not pick that up.
75  */
76 static const UChar pipeString[]={ 0x7c, 0x0a };
77 
78 static const UChar testSkeleton1[]={ 0x48, 0x48, 0x6d, 0x6d, 0 }; /* HHmm */
79 static const UChar expectingBestPattern[]={ 0x48, 0x2e, 0x6d, 0x6d, 0 }; /* H.mm */
80 static const UChar testPattern[]={ 0x48, 0x48, 0x3a, 0x6d, 0x6d, 0 }; /* HH:mm */
81 static const UChar expectingSkeleton[]= { 0x48, 0x48, 0x6d, 0x6d, 0 }; /* HHmm */
82 static const UChar expectingBaseSkeleton[]= { 0x48, 0x6d, 0 }; /* HHmm */
83 static const UChar redundantPattern[]={ 0x79, 0x79, 0x4d, 0x4d, 0x4d, 0 }; /* yyMMM */
84 static const UChar testFormat[]= {0x7B, 0x31, 0x7D, 0x20, 0x7B, 0x30, 0x7D, 0};  /* {1} {0} */
85 static const UChar appendItemName[]= {0x68, 0x72, 0};  /* hr */
86 static const UChar testPattern2[]={ 0x48, 0x48, 0x3a, 0x6d, 0x6d, 0x20, 0x76, 0 }; /* HH:mm v */
87 static const UChar replacedStr[]={ 0x76, 0x76, 0x76, 0x76, 0 }; /* vvvv */
88 /* results for getBaseSkeletons() - {Hmv}, {yMMM} */
89 static const UChar resultBaseSkeletons[2][10] = {{0x48,0x6d, 0x76, 0}, {0x79, 0x4d, 0x4d, 0x4d, 0 } };
90 static const UChar sampleFormatted[] = {0x31, 0x30, 0x20, 0x6A, 0x75, 0x69, 0x6C, 0x2E, 0}; /* 10 juil. */
91 static const UChar skeleton[]= {0x4d, 0x4d, 0x4d, 0x64, 0};  /* MMMd */
92 static const UChar timeZoneGMT[] = { 0x0047, 0x004d, 0x0054, 0x0000 };  /* "GMT" */
93 
TestOpenClose(void)94 static void TestOpenClose(void) {
95     UErrorCode errorCode=U_ZERO_ERROR;
96     UDateTimePatternGenerator *dtpg, *dtpg2;
97     const UChar *s;
98     int32_t length;
99 
100     /* Open a DateTimePatternGenerator for the default locale. */
101     dtpg=udatpg_open(NULL, &errorCode);
102     if(U_FAILURE(errorCode)) {
103         log_err_status(errorCode, "udatpg_open(NULL) failed - %s\n", u_errorName(errorCode));
104         return;
105     }
106     udatpg_close(dtpg);
107 
108     /* Now one for German. */
109     dtpg=udatpg_open("de", &errorCode);
110     if(U_FAILURE(errorCode)) {
111         log_err("udatpg_open(de) failed - %s\n", u_errorName(errorCode));
112         return;
113     }
114 
115     /* Make some modification which we verify gets passed on to the clone. */
116     udatpg_setDecimal(dtpg, pipeString, 1);
117 
118     /* Clone the generator. */
119     dtpg2=udatpg_clone(dtpg, &errorCode);
120     if(U_FAILURE(errorCode) || dtpg2==NULL) {
121         log_err("udatpg_clone() failed - %s\n", u_errorName(errorCode));
122         return;
123     }
124 
125     /* Verify that the clone has the custom decimal symbol. */
126     s=udatpg_getDecimal(dtpg2, &length);
127     if(s==pipeString || length!=1 || 0!=u_memcmp(s, pipeString, length) || s[length]!=0) {
128         log_err("udatpg_getDecimal(cloned object) did not return the expected string\n");
129         return;
130     }
131 
132     udatpg_close(dtpg);
133     udatpg_close(dtpg2);
134 }
135 
136 typedef struct {
137     UDateTimePatternField field;
138     UChar name[12];
139 } AppendItemNameData;
140 
141 static const AppendItemNameData appendItemNameData[] = { /* for Finnish */
142     { UDATPG_YEAR_FIELD,    {0x0076,0x0075,0x006F,0x0073,0x0069,0} }, /* "vuosi" */
143     { UDATPG_MONTH_FIELD,   {0x006B,0x0075,0x0075,0x006B,0x0061,0x0075,0x0073,0x0069,0} }, /* "kuukausi" */
144     { UDATPG_WEEKDAY_FIELD, {0x0076,0x0069,0x0069,0x006B,0x006F,0x006E,0x0070,0x00E4,0x0069,0x0076,0x00E4,0} },
145     { UDATPG_DAY_FIELD,     {0x0070,0x00E4,0x0069,0x0076,0x00E4,0} },
146     { UDATPG_HOUR_FIELD,    {0x0074,0x0075,0x006E,0x0074,0x0069,0} }, /* "tunti" */
147     { UDATPG_FIELD_COUNT,   {0}        }  /* terminator */
148 };
149 
TestUsage(void)150 static void TestUsage(void) {
151     UErrorCode errorCode=U_ZERO_ERROR;
152     UDateTimePatternGenerator *dtpg;
153     const AppendItemNameData * appItemNameDataPtr;
154     UChar bestPattern[20];
155     UChar result[20];
156     int32_t length;
157     UChar *s;
158     const UChar *r;
159 
160     dtpg=udatpg_open("fi", &errorCode);
161     if(U_FAILURE(errorCode)) {
162         log_err_status(errorCode, "udatpg_open(fi) failed - %s\n", u_errorName(errorCode));
163         return;
164     }
165     length = udatpg_getBestPattern(dtpg, testSkeleton1, 4,
166                                    bestPattern, 20, &errorCode);
167     if(U_FAILURE(errorCode)) {
168         log_err("udatpg_getBestPattern failed - %s\n", u_errorName(errorCode));
169         return;
170     }
171     if((u_memcmp(bestPattern, expectingBestPattern, length)!=0) || bestPattern[length]!=0) {
172         log_err("udatpg_getBestPattern did not return the expected string\n");
173         return;
174     }
175 
176 
177     /* Test skeleton == NULL */
178     s=NULL;
179     length = udatpg_getBestPattern(dtpg, s, 0, bestPattern, 20, &errorCode);
180     if(!U_FAILURE(errorCode)&&(length!=0) ) {
181         log_err("udatpg_getBestPattern failed in illegal argument - skeleton is NULL.\n");
182         return;
183     }
184 
185     /* Test udatpg_getSkeleton */
186     length = udatpg_getSkeleton(dtpg, testPattern, 5, result, 20,  &errorCode);
187     if(U_FAILURE(errorCode)) {
188         log_err("udatpg_getSkeleton failed - %s\n", u_errorName(errorCode));
189         return;
190     }
191     if((u_memcmp(result, expectingSkeleton, length)!=0) || result[length]!=0) {
192         log_err("udatpg_getSkeleton did not return the expected string\n");
193         return;
194     }
195 
196     /* Test pattern == NULL */
197     s=NULL;
198     length = udatpg_getSkeleton(dtpg, s, 0, result, 20, &errorCode);
199     if(!U_FAILURE(errorCode)&&(length!=0) ) {
200         log_err("udatpg_getSkeleton failed in illegal argument - pattern is NULL.\n");
201         return;
202     }
203 
204     /* Test udatpg_getBaseSkeleton */
205     length = udatpg_getBaseSkeleton(dtpg, testPattern, 5, result, 20,  &errorCode);
206     if(U_FAILURE(errorCode)) {
207         log_err("udatpg_getBaseSkeleton failed - %s\n", u_errorName(errorCode));
208         return;
209     }
210     if((u_memcmp(result, expectingBaseSkeleton, length)!=0) || result[length]!=0) {
211         log_err("udatpg_getBaseSkeleton did not return the expected string\n");
212         return;
213     }
214 
215     /* Test pattern == NULL */
216     s=NULL;
217     length = udatpg_getBaseSkeleton(dtpg, s, 0, result, 20, &errorCode);
218     if(!U_FAILURE(errorCode)&&(length!=0) ) {
219         log_err("udatpg_getBaseSkeleton failed in illegal argument - pattern is NULL.\n");
220         return;
221     }
222 
223     /* set append format to {1}{0} */
224     udatpg_setAppendItemFormat( dtpg, UDATPG_MONTH_FIELD, testFormat, 7 );
225     r = udatpg_getAppendItemFormat(dtpg, UDATPG_MONTH_FIELD, &length);
226 
227 
228     if(length!=7 || 0!=u_memcmp(r, testFormat, length) || r[length]!=0) {
229         log_err("udatpg_setAppendItemFormat did not return the expected string\n");
230         return;
231     }
232 
233     for (appItemNameDataPtr = appendItemNameData; appItemNameDataPtr->field <  UDATPG_FIELD_COUNT; appItemNameDataPtr++) {
234         int32_t nameLength;
235         const UChar * namePtr = udatpg_getAppendItemName(dtpg, appItemNameDataPtr->field, &nameLength);
236         if ( namePtr == NULL || u_strncmp(appItemNameDataPtr->name, namePtr, nameLength) != 0 ) {
237             log_err("udatpg_getAppendItemName returns invalid name for field %d\n", (int)appItemNameDataPtr->field);
238         }
239     }
240 
241     /* set append name to hr */
242     udatpg_setAppendItemName(dtpg, UDATPG_HOUR_FIELD, appendItemName, 2);
243     r = udatpg_getAppendItemName(dtpg, UDATPG_HOUR_FIELD, &length);
244 
245     if(length!=2 || 0!=u_memcmp(r, appendItemName, length) || r[length]!=0) {
246         log_err("udatpg_setAppendItemName did not return the expected string\n");
247         return;
248     }
249 
250     /* set date time format to {1}{0} */
251     udatpg_setDateTimeFormat( dtpg, testFormat, 7 );
252     r = udatpg_getDateTimeFormat(dtpg, &length);
253 
254     if(length!=7 || 0!=u_memcmp(r, testFormat, length) || r[length]!=0) {
255         log_err("udatpg_setDateTimeFormat did not return the expected string\n");
256         return;
257     }
258     udatpg_close(dtpg);
259 }
260 
TestBuilder(void)261 static void TestBuilder(void) {
262     UErrorCode errorCode=U_ZERO_ERROR;
263     UDateTimePatternGenerator *dtpg;
264     UDateTimePatternConflict conflict;
265     UEnumeration *en;
266     UChar result[20];
267     int32_t length, pLength;
268     const UChar *s, *p;
269     const UChar* ptrResult[2];
270     int32_t count=0;
271     UDateTimePatternGenerator *generator;
272     int32_t formattedCapacity, resultLen,patternCapacity ;
273     UChar   pattern[40], formatted[40];
274     UDateFormat *formatter;
275     UDate sampleDate = 837039928046.0;
276     static const char locale[]= "fr";
277     UErrorCode status=U_ZERO_ERROR;
278 
279     /* test create an empty DateTimePatternGenerator */
280     dtpg=udatpg_openEmpty(&errorCode);
281     if(U_FAILURE(errorCode)) {
282         log_err("udatpg_openEmpty() failed - %s\n", u_errorName(errorCode));
283         return;
284     }
285 
286     /* Add a pattern */
287     conflict = udatpg_addPattern(dtpg, redundantPattern, 5, false, result, 20,
288                                  &length, &errorCode);
289     if(U_FAILURE(errorCode)) {
290         log_err("udatpg_addPattern() failed - %s\n", u_errorName(errorCode));
291         return;
292     }
293     /* Add a redundant pattern */
294     conflict = udatpg_addPattern(dtpg, redundantPattern, 5, false, result, 20,
295                                  &length, &errorCode);
296     if(conflict == UDATPG_NO_CONFLICT) {
297         log_err("udatpg_addPattern() failed to find the duplicate pattern.\n");
298         return;
299     }
300     /* Test pattern == NULL */
301     s=NULL;
302     length = udatpg_addPattern(dtpg, s, 0, false, result, 20,
303                                &length, &errorCode);
304     if(!U_FAILURE(errorCode)&&(length!=0) ) {
305         log_err("udatpg_addPattern failed in illegal argument - pattern is NULL.\n");
306         return;
307     }
308 
309     /* replace field type */
310     errorCode=U_ZERO_ERROR;
311     conflict = udatpg_addPattern(dtpg, testPattern2, 7, false, result, 20,
312                                  &length, &errorCode);
313     if((conflict != UDATPG_NO_CONFLICT)||U_FAILURE(errorCode)) {
314         log_err("udatpg_addPattern() failed to add HH:mm v. - %s\n", u_errorName(errorCode));
315         return;
316     }
317     length = udatpg_replaceFieldTypes(dtpg, testPattern2, 7, replacedStr, 4,
318                                       result, 20, &errorCode);
319     if (U_FAILURE(errorCode) || (length==0) ) {
320         log_err("udatpg_replaceFieldTypes failed!\n");
321         return;
322     }
323 
324     /* Get all skeletons and the crroespong pattern for each skeleton. */
325     ptrResult[0] = testPattern2;
326     ptrResult[1] = redundantPattern;
327     count=0;
328     en = udatpg_openSkeletons(dtpg, &errorCode);
329     if (U_FAILURE(errorCode) || (length==0) ) {
330         log_err("udatpg_openSkeletons failed!\n");
331         return;
332     }
333     while ( (s=uenum_unext(en, &length, &errorCode))!= NULL) {
334         p = udatpg_getPatternForSkeleton(dtpg, s, length, &pLength);
335         if (U_FAILURE(errorCode) || p==NULL || u_memcmp(p, ptrResult[count], pLength)!=0 ) {
336             log_err("udatpg_getPatternForSkeleton failed!\n");
337             return;
338         }
339         count++;
340     }
341     uenum_close(en);
342 
343     /* Get all baseSkeletons */
344     en = udatpg_openBaseSkeletons(dtpg, &errorCode);
345     count=0;
346     while ( (s=uenum_unext(en, &length, &errorCode))!= NULL) {
347         p = udatpg_getPatternForSkeleton(dtpg, s, length, &pLength);
348         if (U_FAILURE(errorCode) || p==NULL || u_memcmp(p, resultBaseSkeletons[count], pLength)!=0 ) {
349             log_err("udatpg_getPatternForSkeleton failed!\n");
350             return;
351         }
352         count++;
353     }
354     if (U_FAILURE(errorCode) || (length==0) ) {
355         log_err("udatpg_openSkeletons failed!\n");
356         return;
357     }
358     uenum_close(en);
359 
360     udatpg_close(dtpg);
361 
362     /* sample code in Userguide */
363     patternCapacity = UPRV_LENGTHOF(pattern);
364     status=U_ZERO_ERROR;
365     generator=udatpg_open(locale, &status);
366     if(U_FAILURE(status)) {
367         return;
368     }
369 
370     /* get a pattern for an abbreviated month and day */
371     length = udatpg_getBestPattern(generator, skeleton, 4,
372                                    pattern, patternCapacity, &status);
373     formatter = udat_open(UDAT_PATTERN, UDAT_PATTERN, locale, timeZoneGMT, -1,
374                           pattern, length, &status);
375     if (formatter==NULL) {
376         log_err("Failed to initialize the UDateFormat of the sample code in Userguide.\n");
377         udatpg_close(generator);
378         return;
379     }
380 
381     /* use it to format (or parse) */
382     formattedCapacity = UPRV_LENGTHOF(formatted);
383     resultLen=udat_format(formatter, ucal_getNow(), formatted, formattedCapacity,
384                           NULL, &status);
385     /* for French, the result is "13 sept." */
386 
387     /* cannot use the result from ucal_getNow() because the value change evreyday. */
388     resultLen=udat_format(formatter, sampleDate, formatted, formattedCapacity,
389                           NULL, &status);
390     if ( u_memcmp(sampleFormatted, formatted, resultLen) != 0 ) {
391         log_err("Failed udat_format() of sample code in Userguide.\n");
392     }
393     udatpg_close(generator);
394     udat_close(formatter);
395 }
396 
397 typedef struct DTPtnGenOptionsData {
398     const char *                    locale;
399     const UChar *                   skel;
400     UDateTimePatternMatchOptions    options;
401     const UChar *                   expectedPattern;
402 } DTPtnGenOptionsData;
403 enum { kTestOptionsPatLenMax = 32 };
404 
405 static const UChar skel_Hmm[]     = u"Hmm";
406 static const UChar skel_HHmm[]    = u"HHmm";
407 static const UChar skel_hhmm[]    = u"hhmm";
408 static const UChar patn_hcmm_a[]  = u"h:mm\u202Fa";
409 static const UChar patn_HHcmm[]   = u"HH:mm";
410 static const UChar patn_hhcmm_a[] = u"hh:mm\u202Fa";
411 static const UChar patn_HHpmm[]   = u"HH.mm";
412 static const UChar patn_hpmm_a[]  = u"h.mm\u202Fa";
413 static const UChar patn_Hpmm[]    = u"H.mm";
414 static const UChar patn_hhpmm_a[] = u"hh.mm\u202Fa";
415 
TestOptions(void)416 static void TestOptions(void) {
417     const DTPtnGenOptionsData testData[] = {
418         /*loc   skel       options                       expectedPattern */
419         { "en", skel_Hmm,  UDATPG_MATCH_NO_OPTIONS,        patn_HHcmm   },
420         { "en", skel_HHmm, UDATPG_MATCH_NO_OPTIONS,        patn_HHcmm   },
421         { "en", skel_hhmm, UDATPG_MATCH_NO_OPTIONS,        patn_hcmm_a  },
422         { "en", skel_Hmm,  UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_HHcmm   },
423         { "en", skel_HHmm, UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_HHcmm   },
424         { "en", skel_hhmm, UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_hhcmm_a },
425         { "da", skel_Hmm,  UDATPG_MATCH_NO_OPTIONS,        patn_HHpmm   },
426         { "da", skel_HHmm, UDATPG_MATCH_NO_OPTIONS,        patn_HHpmm   },
427         { "da", skel_hhmm, UDATPG_MATCH_NO_OPTIONS,        patn_hpmm_a  },
428         { "da", skel_Hmm,  UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_Hpmm    },
429         { "da", skel_HHmm, UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_HHpmm   },
430         { "da", skel_hhmm, UDATPG_MATCH_HOUR_FIELD_LENGTH, patn_hhpmm_a },
431 
432         // tests for ICU-22669
433         { "zh_TW",           u"jjm",  UDATPG_MATCH_NO_OPTIONS,        u"ah:mm" },
434         { "zh_TW",           u"jjm",  UDATPG_MATCH_ALL_FIELDS_LENGTH, u"ahh:mm" },
435         { "zh_TW",           u"jjms", UDATPG_MATCH_NO_OPTIONS,        u"ah:mm:ss" },
436         { "zh_TW",           u"jjms", UDATPG_MATCH_ALL_FIELDS_LENGTH, u"ahh:mm:ss" },
437         { "zh_TW@hours=h23", u"jjm",  UDATPG_MATCH_NO_OPTIONS,        u"HH:mm" },
438         { "zh_TW@hours=h23", u"jjm",  UDATPG_MATCH_ALL_FIELDS_LENGTH, u"HH:mm" }, // (without the fix, we get "HH:m" here)
439         { "zh_TW@hours=h23", u"jjms", UDATPG_MATCH_NO_OPTIONS,        u"HH:mm:ss" },
440         { "zh_TW@hours=h23", u"jjms", UDATPG_MATCH_ALL_FIELDS_LENGTH, u"HH:mm:ss" },
441     };
442 
443     int count = UPRV_LENGTHOF(testData);
444     const DTPtnGenOptionsData * testDataPtr = testData;
445 
446     for (; count-- > 0; ++testDataPtr) {
447         UErrorCode status = U_ZERO_ERROR;
448         UDateTimePatternGenerator * dtpgen = udatpg_open(testDataPtr->locale, &status);
449         if ( U_SUCCESS(status) ) {
450             UChar pattern[kTestOptionsPatLenMax];
451             int32_t patLen = udatpg_getBestPatternWithOptions(dtpgen, testDataPtr->skel, -1,
452                                                               testDataPtr->options, pattern,
453                                                               kTestOptionsPatLenMax, &status);
454             if ( U_FAILURE(status) || u_strncmp(pattern, testDataPtr->expectedPattern, patLen+1) != 0 ) {
455                 char skelBytes[kTestOptionsPatLenMax];
456                 char expectedPatternBytes[kTestOptionsPatLenMax];
457                 char patternBytes[kTestOptionsPatLenMax];
458                 log_err("ERROR udatpg_getBestPatternWithOptions, locale %s, skeleton %s, options 0x%04X, expected pattern %s, got %s, status %d\n",
459                         testDataPtr->locale, u_austrncpy(skelBytes,testDataPtr->skel,kTestOptionsPatLenMax), testDataPtr->options,
460                         u_austrncpy(expectedPatternBytes,testDataPtr->expectedPattern,kTestOptionsPatLenMax),
461                         u_austrncpy(patternBytes,pattern,kTestOptionsPatLenMax), status );
462             }
463             udatpg_close(dtpgen);
464         } else {
465             log_data_err("ERROR udatpg_open failed for locale %s : %s - (Are you missing data?)\n", testDataPtr->locale, myErrorName(status));
466         }
467     }
468 }
469 
470 typedef struct FieldDisplayNameData {
471     const char *            locale;
472     UDateTimePatternField   field;
473     UDateTimePGDisplayWidth width;
474     const char *            expected;
475 } FieldDisplayNameData;
476 enum { kFieldDisplayNameMax = 32, kFieldDisplayNameBytesMax  = 64};
477 
TestGetFieldDisplayNames(void)478 static void TestGetFieldDisplayNames(void) {
479     const FieldDisplayNameData testData[] = {
480         /*loc      field                              width               expectedName */
481         { "de",    UDATPG_QUARTER_FIELD,              UDATPG_WIDE,        "Quartal" },
482         { "de",    UDATPG_QUARTER_FIELD,              UDATPG_ABBREVIATED, "Quart." },
483         { "de",    UDATPG_QUARTER_FIELD,              UDATPG_NARROW,      "Q" },
484         { "en",    UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_WIDE,        "weekday of the month" },
485         { "en",    UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_ABBREVIATED, "wkday. of mo." },
486         { "en",    UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_NARROW,      "wkday. of mo." }, // fallback
487         { "en_GB", UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_WIDE,        "weekday of the month" },
488         { "en_GB", UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_ABBREVIATED, "wkday of mo" }, // override
489         { "en_GB", UDATPG_DAY_OF_WEEK_IN_MONTH_FIELD, UDATPG_NARROW,      "wkday of mo" },
490         { "it",    UDATPG_SECOND_FIELD,               UDATPG_WIDE,        "secondo" },
491         { "it",    UDATPG_SECOND_FIELD,               UDATPG_ABBREVIATED, "s" },
492         { "it",    UDATPG_SECOND_FIELD,               UDATPG_NARROW,      "s" },
493     };
494 
495     int count = UPRV_LENGTHOF(testData);
496     const FieldDisplayNameData * testDataPtr = testData;
497     for (; count-- > 0; ++testDataPtr) {
498         UErrorCode status = U_ZERO_ERROR;
499         UDateTimePatternGenerator * dtpgen = udatpg_open(testDataPtr->locale, &status);
500         if ( U_FAILURE(status) ) {
501             log_data_err("ERROR udatpg_open failed for locale %s : %s - (Are you missing data?)\n", testDataPtr->locale, myErrorName(status));
502         } else {
503             UChar expName[kFieldDisplayNameMax];
504             UChar getName[kFieldDisplayNameMax];
505             u_unescape(testDataPtr->expected, expName, kFieldDisplayNameMax);
506 
507             int32_t getLen = udatpg_getFieldDisplayName(dtpgen, testDataPtr->field, testDataPtr->width,
508                                                         getName, kFieldDisplayNameMax, &status);
509             if ( U_FAILURE(status) ) {
510                 log_err("ERROR udatpg_getFieldDisplayName locale %s field %d width %d, got status %s, len %d\n",
511                         testDataPtr->locale, testDataPtr->field, testDataPtr->width, u_errorName(status), getLen);
512             } else if ( u_strncmp(expName, getName, kFieldDisplayNameMax) != 0 ) {
513                 char expNameB[kFieldDisplayNameBytesMax];
514                 char getNameB[kFieldDisplayNameBytesMax];
515                 log_err("ERROR udatpg_getFieldDisplayName locale %s field %d width %d, expected %s, got %s, status %s\n",
516                         testDataPtr->locale, testDataPtr->field, testDataPtr->width,
517                         u_austrncpy(expNameB,expName,kFieldDisplayNameBytesMax),
518                         u_austrncpy(getNameB,getName,kFieldDisplayNameBytesMax), u_errorName(status) );
519             } else if (testDataPtr->width == UDATPG_WIDE && getLen > 1) {
520                 // test preflight & inadequate buffer
521                 int32_t getNewLen;
522                 status = U_ZERO_ERROR;
523                 getNewLen = udatpg_getFieldDisplayName(dtpgen, testDataPtr->field, UDATPG_WIDE, NULL, 0, &status);
524                 if (U_FAILURE(status) || getNewLen != getLen) {
525                     log_err("ERROR udatpg_getFieldDisplayName locale %s field %d width %d, preflight expected len %d, got %d, status %s\n",
526                         testDataPtr->locale, testDataPtr->field, testDataPtr->width, getLen, getNewLen, u_errorName(status) );
527                 }
528                 status = U_ZERO_ERROR;
529                 getNewLen = udatpg_getFieldDisplayName(dtpgen, testDataPtr->field, UDATPG_WIDE, getName, getLen-1, &status);
530                 if (status!=U_BUFFER_OVERFLOW_ERROR || getNewLen != getLen) {
531                     log_err("ERROR udatpg_getFieldDisplayName locale %s field %d width %d, overflow expected len %d & BUFFER_OVERFLOW_ERROR, got %d & status %s\n",
532                         testDataPtr->locale, testDataPtr->field, testDataPtr->width, getLen, getNewLen, u_errorName(status) );
533                 }
534             }
535             udatpg_close(dtpgen);
536         }
537     }
538 }
539 
540 typedef struct HourCycleData {
541     const char *         locale;
542     UDateFormatHourCycle   expected;
543 } HourCycleData;
544 
TestGetDefaultHourCycle(void)545 static void TestGetDefaultHourCycle(void) {
546     const HourCycleData testData[] = {
547         /*loc      expected */
548         { "ar_EG",    UDAT_HOUR_CYCLE_12 },
549         { "de_DE",    UDAT_HOUR_CYCLE_23 },
550         { "en_AU",    UDAT_HOUR_CYCLE_12 },
551         { "en_CA",    UDAT_HOUR_CYCLE_12 },
552         { "en_US",    UDAT_HOUR_CYCLE_12 },
553         { "es_ES",    UDAT_HOUR_CYCLE_23 },
554         { "fi",       UDAT_HOUR_CYCLE_23 },
555         { "fr",       UDAT_HOUR_CYCLE_23 },
556         { "ja_JP",    UDAT_HOUR_CYCLE_23 },
557         { "zh_CN",    UDAT_HOUR_CYCLE_23 },
558         { "zh_HK",    UDAT_HOUR_CYCLE_12 },
559         { "zh_TW",    UDAT_HOUR_CYCLE_12 },
560         { "ko_KR",    UDAT_HOUR_CYCLE_12 },
561     };
562     int count = UPRV_LENGTHOF(testData);
563     const HourCycleData * testDataPtr = testData;
564     for (; count-- > 0; ++testDataPtr) {
565         UErrorCode status = U_ZERO_ERROR;
566         UDateTimePatternGenerator * dtpgen =
567             udatpg_open(testDataPtr->locale, &status);
568         if ( U_FAILURE(status) ) {
569             log_data_err( "ERROR udatpg_open failed for locale %s : %s - (Are you missing data?)\n",
570                          testDataPtr->locale, myErrorName(status));
571         } else {
572             UDateFormatHourCycle actual = udatpg_getDefaultHourCycle(dtpgen, &status);
573             if (U_FAILURE(status) || testDataPtr->expected != actual) {
574                 log_err("ERROR dtpgen locale %s udatpg_getDefaultHourCycle expected to get %d but get %d\n",
575                         testDataPtr->locale, testDataPtr->expected, actual);
576             }
577             udatpg_close(dtpgen);
578         }
579     }
580 }
581 
582 // Ensure that calling udatpg_getDefaultHourCycle on an empty instance doesn't call UPRV_UNREACHABLE_EXIT/abort.
TestGetDefaultHourCycleOnEmptyInstance(void)583 static void TestGetDefaultHourCycleOnEmptyInstance(void) {
584     UErrorCode status = U_ZERO_ERROR;
585     UDateTimePatternGenerator * dtpgen = udatpg_openEmpty(&status);
586 
587     if (U_FAILURE(status)) {
588         log_data_err("ERROR udatpg_openEmpty failed, status: %s \n", myErrorName(status));
589         return;
590     }
591 
592     (void)udatpg_getDefaultHourCycle(dtpgen, &status);
593     if (!U_FAILURE(status)) {
594         log_data_err("ERROR expected udatpg_getDefaultHourCycle on an empty instance to fail, status: %s", myErrorName(status));
595     }
596 
597     status = U_USELESS_COLLATOR_ERROR;
598     (void)udatpg_getDefaultHourCycle(dtpgen, &status);
599     if (status != U_USELESS_COLLATOR_ERROR) {
600         log_data_err("ERROR udatpg_getDefaultHourCycle shouldn't modify status if it is already failed, status: %s", myErrorName(status));
601     }
602 
603     udatpg_close(dtpgen);
604 }
605 
606 // Test for ICU-21202: Make sure DateTimePatternGenerator supplies an era field for year formats using the
607 // Buddhist and Japanese calendars for all English-speaking locales.
TestEras(void)608 static void TestEras(void) {
609     const char* localeIDs[] = {
610         "en_US@calendar=japanese",
611         "en_GB@calendar=japanese",
612         "en_150@calendar=japanese",
613         "en_001@calendar=japanese",
614         "en@calendar=japanese",
615         "en_US@calendar=buddhist",
616         "en_GB@calendar=buddhist",
617         "en_150@calendar=buddhist",
618         "en_001@calendar=buddhist",
619         "en@calendar=buddhist",
620     };
621 
622     UErrorCode err = U_ZERO_ERROR;
623     for (int32_t i = 0; i < UPRV_LENGTHOF(localeIDs); i++) {
624         const char* locale = localeIDs[i];
625         UDateTimePatternGenerator* dtpg = udatpg_open(locale, &err);
626         if (U_SUCCESS(err)) {
627             UChar pattern[200];
628             udatpg_getBestPattern(dtpg, u"y", 1, pattern, 200, &err);
629 
630             if (u_strchr(pattern, u'G') == NULL) {
631                 log_err("missing era field for locale %s\n", locale);
632             }
633         }
634         udatpg_close(dtpg);
635     }
636 }
637 
638 enum { kNumDateTimePatterns = 4 };
639 
640 typedef struct {
641     const char* localeID;
642     const UChar* expectPat[kNumDateTimePatterns];
643 } DTPLocaleAndResults;
644 
645 static void doDTPatternTest(UDateTimePatternGenerator* udtpg,
646                             const UChar** skeletons,
647                             DTPLocaleAndResults* localeAndResultsPtr);
648 
TestDateTimePatterns(void)649 static void TestDateTimePatterns(void) {
650     const UChar* skeletons[kNumDateTimePatterns] = {
651         u"yMMMMEEEEdjmm", // full date, short time
652         u"yMMMMdjmm",     // long date, short time
653         u"yMMMdjmm",      // medium date, short time
654         u"yMdjmm"         // short date, short time
655     };
656     // The following tests some locales in which there are differences between the
657     // DateTimePatterns of various length styles.
658     DTPLocaleAndResults localeAndResults[] = {
659         { "en", { u"EEEE, MMMM d, y 'at' h:mm\u202Fa", // long != medium
660                   u"MMMM d, y 'at' h:mm\u202Fa",
661                   u"MMM d, y, h:mm\u202Fa",
662                   u"M/d/y, h:mm\u202Fa" } },
663         { "fr", { u"EEEE d MMMM y 'à' HH:mm", // medium != short
664                   u"d MMMM y 'à' HH:mm",
665                   u"d MMM y, HH:mm",
666                   u"dd/MM/y HH:mm" } },
667         { "ha", { u"EEEE d MMMM, y 'da' HH:mm",
668                   u"d MMMM, y 'da' HH:mm",
669                   u"d MMM, y, HH:mm",
670                   u"y-MM-dd, HH:mm" } },
671         { NULL, { NULL, NULL, NULL, NULL } } // terminator
672     };
673 
674     const UChar* enDTPatterns[kNumDateTimePatterns] = {
675         u"{1} 'at' {0}",
676         u"{1} 'at' {0}",
677         u"{1}, {0}",
678         u"{1}, {0}"
679     };
680     const UChar* modDTPatterns[kNumDateTimePatterns] = {
681         u"{1} _0_ {0}",
682         u"{1} _1_ {0}",
683         u"{1} _2_ {0}",
684         u"{1} _3_ {0}"
685     };
686     DTPLocaleAndResults enModResults = { "en", { u"EEEE, MMMM d, y _0_ h:mm\u202Fa",
687                                                  u"MMMM d, y _1_ h:mm\u202Fa",
688                                                  u"MMM d, y _2_ h:mm\u202Fa",
689                                                  u"M/d/y _3_ h:mm\u202Fa" }
690     };
691 
692     // Test various locales with standard data
693     UErrorCode status;
694     UDateTimePatternGenerator* udtpg;
695     DTPLocaleAndResults* localeAndResultsPtr = localeAndResults;
696     for (; localeAndResultsPtr->localeID != NULL; localeAndResultsPtr++) {
697         status = U_ZERO_ERROR;
698         udtpg = udatpg_open(localeAndResultsPtr->localeID, &status);
699         if (U_FAILURE(status)) {
700             log_data_err("FAIL: udatpg_open for locale %s: %s", localeAndResultsPtr->localeID, myErrorName(status));
701         } else {
702             doDTPatternTest(udtpg, skeletons, localeAndResultsPtr);
703             udatpg_close(udtpg);
704         }
705     }
706     // Test getting and modifying date-time combining patterns
707     status = U_ZERO_ERROR;
708     udtpg = udatpg_open("en", &status);
709     if (U_FAILURE(status)) {
710         log_data_err("FAIL: udatpg_open #2 for locale en: %s", myErrorName(status));
711     } else {
712         char bExpect[64];
713         char bGet[64];
714         const UChar* uGet;
715         int32_t uGetLen, uExpectLen;
716 
717         // Test error: style out of range
718         status = U_ZERO_ERROR;
719         uGet = udatpg_getDateTimeFormatForStyle(udtpg, UDAT_NONE, &uGetLen, &status);
720         if (status != U_ILLEGAL_ARGUMENT_ERROR || uGetLen != 0 || uGet==NULL || *uGet!= 0) {
721             if (uGet==NULL) {
722                 log_err("FAIL: udatpg_getDateTimeFormatForStyle with invalid style, expected U_ILLEGAL_ARGUMENT_ERROR "
723                         "and ptr to empty string but got %s, len %d, ptr = NULL\n", myErrorName(status), uGetLen);
724             } else {
725                 log_err("FAIL: udatpg_getDateTimeFormatForStyle with invalid style, expected U_ILLEGAL_ARGUMENT_ERROR "
726                         "and ptr to empty string but got %s, len %d, *ptr = %04X\n", myErrorName(status), uGetLen, *uGet);
727             }
728         }
729 
730         // Test normal getting and setting
731         for (int32_t patStyle = 0; patStyle < kNumDateTimePatterns; patStyle++) {
732             status = U_ZERO_ERROR;
733             uExpectLen = u_strlen(enDTPatterns[patStyle]);
734             uGet = udatpg_getDateTimeFormatForStyle(udtpg, patStyle, &uGetLen, &status);
735             if (U_FAILURE(status)) {
736                 log_err("FAIL udatpg_getDateTimeFormatForStyle %d (en before mod), get %s\n", patStyle, myErrorName(status));
737             } else if (uGetLen != uExpectLen || u_strncmp(uGet, enDTPatterns[patStyle], uExpectLen) != 0) {
738                 u_austrcpy(bExpect, enDTPatterns[patStyle]);
739                 u_austrcpy(bGet, uGet);
740                 log_err("ERROR udatpg_getDateTimeFormatForStyle %d (en before mod), expect %d:\"%s\", get %d:\"%s\"\n",
741                         patStyle, uExpectLen, bExpect, uGetLen, bGet);
742             }
743             status = U_ZERO_ERROR;
744             udatpg_setDateTimeFormatForStyle(udtpg, patStyle, modDTPatterns[patStyle], -1, &status);
745             if (U_FAILURE(status)) {
746                 log_err("FAIL udatpg_setDateTimeFormatForStyle %d (en), get %s\n", patStyle, myErrorName(status));
747             } else {
748                 uExpectLen = u_strlen(modDTPatterns[patStyle]);
749                 uGet = udatpg_getDateTimeFormatForStyle(udtpg, patStyle, &uGetLen, &status);
750                 if (U_FAILURE(status)) {
751                     log_err("FAIL udatpg_getDateTimeFormatForStyle %d (en after  mod), get %s\n", patStyle, myErrorName(status));
752                 } else if (uGetLen != uExpectLen || u_strncmp(uGet, modDTPatterns[patStyle], uExpectLen) != 0) {
753                     u_austrcpy(bExpect, modDTPatterns[patStyle]);
754                     u_austrcpy(bGet, uGet);
755                     log_err("ERROR udatpg_getDateTimeFormatForStyle %d (en after  mod), expect %d:\"%s\", get %d:\"%s\"\n",
756                             patStyle, uExpectLen, bExpect, uGetLen, bGet);
757                 }
758             }
759         }
760         // Test result of setting
761         doDTPatternTest(udtpg, skeletons, &enModResults);
762         // Test old get/set functions
763         uExpectLen = u_strlen(modDTPatterns[UDAT_MEDIUM]);
764         uGet = udatpg_getDateTimeFormat(udtpg, &uGetLen);
765         if (uGetLen != uExpectLen || u_strncmp(uGet, modDTPatterns[UDAT_MEDIUM], uExpectLen) != 0) {
766             u_austrcpy(bExpect, modDTPatterns[UDAT_MEDIUM]);
767             u_austrcpy(bGet, uGet);
768             log_err("ERROR udatpg_getDateTimeFormat (en after  mod), expect %d:\"%s\", get %d:\"%s\"\n",
769                     uExpectLen, bExpect, uGetLen, bGet);
770         }
771         udatpg_setDateTimeFormat(udtpg, modDTPatterns[UDAT_SHORT], -1); // set all dateTimePatterns to the short format
772         uExpectLen = u_strlen(modDTPatterns[UDAT_SHORT]);
773         u_austrcpy(bExpect, modDTPatterns[UDAT_SHORT]);
774         for (int32_t patStyle = 0; patStyle < kNumDateTimePatterns; patStyle++) {
775             status = U_ZERO_ERROR;
776             uGet = udatpg_getDateTimeFormatForStyle(udtpg, patStyle, &uGetLen, &status);
777             if (U_FAILURE(status)) {
778                 log_err("FAIL udatpg_getDateTimeFormatForStyle %d (en after second mod), get %s\n", patStyle, myErrorName(status));
779             } else if (uGetLen != uExpectLen || u_strncmp(uGet, modDTPatterns[UDAT_SHORT], uExpectLen) != 0) {
780                 u_austrcpy(bGet, uGet);
781                 log_err("ERROR udatpg_getDateTimeFormatForStyle %d (en after second mod), expect %d:\"%s\", get %d:\"%s\"\n",
782                         patStyle, uExpectLen, bExpect, uGetLen, bGet);
783             }
784         }
785 
786         udatpg_close(udtpg);
787     }
788 }
789 
doDTPatternTest(UDateTimePatternGenerator * udtpg,const UChar ** skeletons,DTPLocaleAndResults * localeAndResultsPtr)790 static void doDTPatternTest(UDateTimePatternGenerator* udtpg,
791                             const UChar** skeletons,
792                             DTPLocaleAndResults* localeAndResultsPtr) {
793     for (int32_t patStyle = 0; patStyle < kNumDateTimePatterns; patStyle++) {
794         UChar uGet[64];
795         int32_t uGetLen, uExpectLen;
796         UErrorCode status = U_ZERO_ERROR;
797         uExpectLen = u_strlen(localeAndResultsPtr->expectPat[patStyle]);
798         uGetLen = udatpg_getBestPattern(udtpg, skeletons[patStyle], -1, uGet, 64, &status);
799         if (U_FAILURE(status)) {
800             log_err("FAIL udatpg_getBestPattern locale %s style %d: %s\n", localeAndResultsPtr->localeID, patStyle, myErrorName(status));
801         } else if (uGetLen != uExpectLen || u_strncmp(uGet, localeAndResultsPtr->expectPat[patStyle], uExpectLen) != 0) {
802             char bExpect[64];
803             char bGet[64];
804             u_austrcpy(bExpect, localeAndResultsPtr->expectPat[patStyle]);
805             u_austrcpy(bGet, uGet);
806             log_err("ERROR udatpg_getBestPattern locale %s style %d, expect %d:\"%s\", get %d:\"%s\"\n",
807                     localeAndResultsPtr->localeID, patStyle, uExpectLen, bExpect, uGetLen, bGet);
808         }
809     }
810 }
811 
TestRegionOverride(void)812 static void TestRegionOverride(void) {
813     typedef struct RegionOverrideTest {
814         const char* locale;
815         const UChar* expectedPattern;
816         UDateFormatHourCycle expectedHourCycle;
817     } RegionOverrideTest;
818 
819     const RegionOverrideTest testCases[] = {
820         { "en_US",           u"h:mm\u202fa", UDAT_HOUR_CYCLE_12 },
821         { "en_GB",           u"HH:mm",  UDAT_HOUR_CYCLE_23 },
822         { "en_US@rg=GBZZZZ", u"HH:mm",  UDAT_HOUR_CYCLE_23 },
823         { "en_US@hours=h23", u"HH:mm",  UDAT_HOUR_CYCLE_23 },
824     };
825 
826     for (int32_t i = 0; i < UPRV_LENGTHOF(testCases); i++) {
827         UErrorCode err = U_ZERO_ERROR;
828         UChar actualPattern[200];
829         UDateTimePatternGenerator* dtpg = udatpg_open(testCases[i].locale, &err);
830 
831         if (assertSuccess("Error creating dtpg", &err)) {
832             UDateFormatHourCycle actualHourCycle = udatpg_getDefaultHourCycle(dtpg, &err);
833             udatpg_getBestPattern(dtpg, u"jmm", -1, actualPattern, 200, &err);
834 
835             if (assertSuccess("Error using dtpg", &err)) {
836                 assertIntEquals("Wrong hour cycle", testCases[i].expectedHourCycle, actualHourCycle);
837                 assertUEquals("Wrong pattern", testCases[i].expectedPattern, actualPattern);
838             }
839         }
840         udatpg_close(dtpg);
841     }
842 }
843 
TestISO8601(void)844 static void TestISO8601(void) {
845     typedef struct TestCase {
846         const char* locale;
847         const UChar* skeleton;
848         const UChar* expectedPattern;
849     } TestCase;
850 
851     const TestCase testCases[] = {
852         { "en_GB@calendar=iso8601;rg=uszzzz", u"EEEEyMMMMdjmm", u"y MMMM d, EEEE 'at' h:mm a" },
853         { "en_GB@calendar=iso8601;rg=uszzzz", u"EEEEyMMMMdHmm", u"y MMMM d, EEEE 'at' HH:mm" },
854         { "en_GB@calendar=iso8601;rg=uszzzz", u"Edjmm",         u"d, EEE, h:mm a" },
855         { "en_GB@calendar=iso8601;rg=uszzzz", u"EdHmm",         u"d, EEE, HH:mm" },
856 
857         { "en_US@calendar=iso8601",           u"EEEEyMMMMdjmm", u"y MMMM d, EEEE 'at' h:mm a" },
858         { "en_US@calendar=iso8601",           u"EEEEyMMMMdHmm", u"y MMMM d, EEEE 'at' HH:mm" },
859         { "en_US@calendar=iso8601",           u"Edjmm",         u"d, EEE, h:mm a" },
860         { "en_US@calendar=iso8601",           u"EdHmm",         u"d, EEE, HH:mm" },
861 
862         { "en_US",                            u"EEEEyMMMMdjmm", u"EEEE, MMMM d, y 'at' h:mm a" },
863         { "en_US",                            u"EEEEyMMMMdHmm", u"EEEE, MMMM d, y 'at' HH:mm" },
864         { "en_US",                            u"Edjmm",         u"d EEE, h:mm a" },
865         { "en_US",                            u"EdHmm",         u"d EEE, HH:mm" },
866     };
867 
868     for (int32_t i = 0; i < UPRV_LENGTHOF(testCases); i++) {
869         UErrorCode err = U_ZERO_ERROR;
870         UDateTimePatternGenerator* dtpg = udatpg_open(testCases[i].locale, &err);
871 
872         if (assertSuccess("Error creating dtpg", &err)) {
873             UChar actualPattern[200];
874 
875             udatpg_getBestPatternWithOptions(dtpg, testCases[i].skeleton, -1, 0, actualPattern, UPRV_LENGTHOF(actualPattern), &err);
876             if (assertSuccess("Error getting best pattern", &err)) {
877                 char errorMessage[200];
878                 snprintf(errorMessage, UPRV_LENGTHOF(errorMessage), "Wrong pattern for %s and %s", testCases[i].locale, austrdup(testCases[i].skeleton));
879                 assertUEquals(errorMessage, testCases[i].expectedPattern, actualPattern);
880             }
881         }
882         udatpg_close(dtpg);
883     }
884 }
885 #endif
886