• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /********************************************************************
2  * COPYRIGHT:
3  * Copyright (c) 1997-2013, International Business Machines Corporation and
4  * others. All Rights Reserved.
5  ********************************************************************/
6 
7 #include "loctest.h"
8 #include "unicode/decimfmt.h"
9 #include "unicode/ucurr.h"
10 #include "unicode/smpdtfmt.h"
11 #include "unicode/dtfmtsym.h"
12 #include "unicode/brkiter.h"
13 #include "unicode/coll.h"
14 #include "cstring.h"
15 #include <stdio.h>
16 #include <string.h>
17 #include "putilimp.h"
18 #include "unicode/ustring.h"
19 
20 static const char* const rawData[33][8] = {
21 
22         // language code
23         {   "en",   "fr",   "ca",   "el",   "no",   "it",   "xx",   "zh"  },
24         // script code
25         {   "",     "",     "",     "",     "",     "",     "",     "Hans" },
26         // country code
27         {   "US",   "FR",   "ES",   "GR",   "NO",   "",     "YY",   "CN"  },
28         // variant code
29         {   "",     "",     "",     "",     "NY",   "",     "",   ""    },
30         // full name
31         {   "en_US",    "fr_FR",    "ca_ES",    "el_GR",    "no_NO_NY", "it",   "xx_YY",   "zh_Hans_CN" },
32         // ISO-3 language
33         {   "eng",  "fra",  "cat",  "ell",  "nor",  "ita",  "",   "zho"   },
34         // ISO-3 country
35         {   "USA",  "FRA",  "ESP",  "GRC",  "NOR",  "",     "",   "CHN"   },
36         // LCID
37         {   "409", "40c", "403", "408", "814", "10",     "0",   "804"  },
38 
39         // display langage (English)
40         {   "English",  "French",   "Catalan", "Greek",    "Norwegian",    "Italian",  "xx",   "Chinese" },
41         // display script (English)
42         {   "",     "",     "",     "",     "",   "",     "",   "Simplified Han" },
43         // display country (English)
44         {   "United States",    "France",   "Spain",  "Greece",   "Norway",   "",     "YY",   "China" },
45         // display variant (English)
46         {   "",     "",     "",     "",     "NY",   "",     "",   ""},
47         // display name (English)
48         // Updated no_NO_NY English display name for new pattern-based algorithm
49         // (part of Euro support).
50         {   "English (United States)", "French (France)", "Catalan (Spain)", "Greek (Greece)", "Norwegian (Norway, NY)", "Italian", "xx (YY)", "Chinese (Simplified, China)" },
51 
52         // display langage (French)
53         {   "anglais",  "fran\\u00E7ais",   "catalan", "grec",    "norv\\u00E9gien",    "italien", "xx", "chinois" },
54         // display script (French)
55         {   "",     "",     "",     "",     "",     "",     "",   "sinogrammes simplifi\\u00E9s" },
56         // display country (French)
57         {   "\\u00C9tats-Unis",    "France",   "Espagne",  "Gr\\u00E8ce",   "Norv\\u00E8ge", "", "YY", "Chine" },
58         // display variant (French)
59         {   "",     "",     "",     "",     "NY",     "",     "",   "" },
60         // display name (French)
61         //{   "anglais (Etats-Unis)", "francais (France)", "catalan (Espagne)", "grec (Grece)", "norvegien (Norvege,Nynorsk)", "italien", "xx (YY)" },
62         {   "anglais (\\u00C9tats-Unis)", "fran\\u00E7ais (France)", "catalan (Espagne)", "grec (Gr\\u00E8ce)", "norv\\u00E9gien (Norv\\u00E8ge, NY)", "italien", "xx (YY)", "chinois (simplifi\\u00E9, Chine)" },
63 
64 
65         /* display language (Catalan) */
66         {   "angl\\u00E8s", "franc\\u00E8s", "catal\\u00E0", "grec",  "noruec", "itali\\u00E0", "", "xin\\u00E8s" },
67         /* display script (Catalan) */
68         {   "", "", "",                    "", "", "", "", "han simplificat" },
69         /* display country (Catalan) */
70         {   "Estats Units", "Fran\\u00E7a", "Espanya",  "Gr\\u00E8cia", "Noruega", "", "", "Xina" },
71         /* display variant (Catalan) */
72         {   "", "", "",                    "", "NY", "", "" },
73         /* display name (Catalan) */
74         {   "angl\\u00E8s (Estats Units)", "franc\\u00E8s (Fran\\u00E7a)", "catal\\u00E0 (Espanya)", "grec (Gr\\u00E8cia)", "noruec (Noruega, NY)", "itali\\u00E0", "", "xin\\u00E8s (simplificat, Xina)" },
75 
76         // display langage (Greek)[actual values listed below]
77         {   "\\u0391\\u03b3\\u03b3\\u03bb\\u03b9\\u03ba\\u03ac",
78             "\\u0393\\u03b1\\u03bb\\u03bb\\u03b9\\u03ba\\u03ac",
79             "\\u039a\\u03b1\\u03c4\\u03b1\\u03bb\\u03b1\\u03bd\\u03b9\\u03ba\\u03ac",
80             "\\u0395\\u03bb\\u03bb\\u03b7\\u03bd\\u03b9\\u03ba\\u03ac",
81             "\\u039d\\u03bf\\u03c1\\u03b2\\u03b7\\u03b3\\u03b9\\u03ba\\u03ac",
82             "\\u0399\\u03c4\\u03b1\\u03bb\\u03b9\\u03ba\\u03ac",
83             "",
84             "\\u039A\\u03B9\\u03BD\\u03B5\\u03B6\\u03B9\\u03BA\\u03AC"
85         },
86         // display script (Greek)
87         {   "", "", "", "", "", "", "", "\\u0391\\u03c0\\u03bb\\u03bf\\u03c0\\u03bf\\u03b9\\u03b7\\u03bc\\u03ad\\u03bd\\u03bf \\u03a7\\u03b1\\u03bd" },
88         // display country (Greek)[actual values listed below]
89         {   "\\u0397\\u03BD\\u03C9\\u03BC\\u03AD\\u03BD\\u03B5\\u03C2 \\u03A0\\u03BF\\u03BB\\u03B9\\u03C4\\u03B5\\u03AF\\u03B5\\u03C2",
90             "\\u0393\\u03b1\\u03bb\\u03bb\\u03af\\u03b1",
91             "\\u0399\\u03c3\\u03c0\\u03b1\\u03bd\\u03af\\u03b1",
92             "\\u0395\\u03bb\\u03bb\\u03ac\\u03b4\\u03b1",
93             "\\u039d\\u03bf\\u03c1\\u03b2\\u03b7\\u03b3\\u03af\\u03b1",
94             "",
95             "",
96             "\\u039A\\u03AF\\u03BD\\u03B1"
97         },
98         // display variant (Greek)
99         {   "", "", "", "", "NY", "", "" },
100         // display name (Greek)[actual values listed below]
101         {   "\\u0391\\u03b3\\u03b3\\u03bb\\u03b9\\u03ba\\u03ac (\\u0397\\u03BD\\u03C9\\u03BC\\u03AD\\u03BD\\u03B5\\u03C2 \\u03A0\\u03BF\\u03BB\\u03B9\\u03C4\\u03B5\\u03AF\\u03B5\\u03C2)",
102             "\\u0393\\u03b1\\u03bb\\u03bb\\u03b9\\u03ba\\u03ac (\\u0393\\u03b1\\u03bb\\u03bb\\u03af\\u03b1)",
103             "\\u039a\\u03b1\\u03c4\\u03b1\\u03bb\\u03b1\\u03bd\\u03b9\\u03ba\\u03ac (\\u0399\\u03c3\\u03c0\\u03b1\\u03bd\\u03af\\u03b1)",
104             "\\u0395\\u03bb\\u03bb\\u03b7\\u03bd\\u03b9\\u03ba\\u03ac (\\u0395\\u03bb\\u03bb\\u03ac\\u03b4\\u03b1)",
105             "\\u039d\\u03bf\\u03c1\\u03b2\\u03b7\\u03b3\\u03b9\\u03ba\\u03ac (\\u039d\\u03bf\\u03c1\\u03b2\\u03b7\\u03b3\\u03af\\u03b1, NY)",
106             "\\u0399\\u03c4\\u03b1\\u03bb\\u03b9\\u03ba\\u03ac",
107             "",
108             "\\u039A\\u03B9\\u03BD\\u03B5\\u03B6\\u03B9\\u03BA\\u03AC (\\u0391\\u03c0\\u03bb\\u03bf\\u03c0\\u03bf\\u03b9\\u03b7\\u03bc\\u03ad\\u03bd\\u03bf, \\u039A\\u03AF\\u03BD\\u03B1)"
109         },
110 
111         // display langage (<root>)
112         {   "English",  "French",   "Catalan", "Greek",    "Norwegian",    "Italian",  "xx", "" },
113         // display script (<root>)
114         {   "",     "",     "",     "",     "",   "",     "", ""},
115         // display country (<root>)
116         {   "United States",    "France",   "Spain",  "Greece",   "Norway",   "",     "YY", "" },
117         // display variant (<root>)
118         {   "",     "",     "",     "",     "Nynorsk",   "",     "", ""},
119         // display name (<root>)
120         //{   "English (United States)", "French (France)", "Catalan (Spain)", "Greek (Greece)", "Norwegian (Norway,Nynorsk)", "Italian", "xx (YY)" },
121         {   "English (United States)", "French (France)", "Catalan (Spain)", "Greek (Greece)", "Norwegian (Norway,NY)", "Italian", "xx (YY)", "" }
122 };
123 
124 
125 /*
126  Usage:
127     test_assert(    Test (should be TRUE)  )
128 
129    Example:
130        test_assert(i==3);
131 
132    the macro is ugly but makes the tests pretty.
133 */
134 
135 #define test_assert(test) \
136     { \
137         if(!(test)) \
138             errln("FAIL: " #test " was not true. In " __FILE__ " on line %d", __LINE__ ); \
139         else \
140             logln("PASS: asserted " #test); \
141     }
142 
143 /*
144  Usage:
145     test_assert_print(    Test (should be TRUE),  printable  )
146 
147    Example:
148        test_assert(i==3, toString(i));
149 
150    the macro is ugly but makes the tests pretty.
151 */
152 
153 #define test_assert_print(test,print) \
154     { \
155         if(!(test)) \
156             errln("FAIL: " #test " was not true. " + UnicodeString(print) ); \
157         else \
158             logln("PASS: asserted " #test "-> " + UnicodeString(print)); \
159     }
160 
161 
162 #define test_dumpLocale(l) { logln(#l " = " + UnicodeString(l.getName(), "")); }
163 
LocaleTest()164 LocaleTest::LocaleTest()
165 : dataTable(NULL)
166 {
167     setUpDataTable();
168 }
169 
~LocaleTest()170 LocaleTest::~LocaleTest()
171 {
172     if (dataTable != 0) {
173         for (int32_t i = 0; i < 33; i++) {
174             delete []dataTable[i];
175         }
176         delete []dataTable;
177         dataTable = 0;
178     }
179 }
180 
runIndexedTest(int32_t index,UBool exec,const char * & name,char *)181 void LocaleTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
182 {
183     switch (index) {
184         TESTCASE(0, TestBasicGetters);
185         TESTCASE(1, TestSimpleResourceInfo);
186         TESTCASE(2, TestDisplayNames);
187         TESTCASE(3, TestSimpleObjectStuff);
188         TESTCASE(4, TestPOSIXParsing);
189         TESTCASE(5, TestGetAvailableLocales);
190         TESTCASE(6, TestDataDirectory);
191         TESTCASE(7, TestISO3Fallback);
192         TESTCASE(8, TestGetLangsAndCountries);
193         TESTCASE(9, TestSimpleDisplayNames);
194         TESTCASE(10, TestUninstalledISO3Names);
195         TESTCASE(11, TestAtypicalLocales);
196 #if !UCONFIG_NO_FORMATTING
197         TESTCASE(12, TestThaiCurrencyFormat);
198         TESTCASE(13, TestEuroSupport);
199 #endif
200         TESTCASE(14, TestToString);
201 #if !UCONFIG_NO_FORMATTING
202         TESTCASE(15, Test4139940);
203         TESTCASE(16, Test4143951);
204 #endif
205         TESTCASE(17, Test4147315);
206         TESTCASE(18, Test4147317);
207         TESTCASE(19, Test4147552);
208         TESTCASE(20, TestVariantParsing);
209 #if !UCONFIG_NO_FORMATTING
210         TESTCASE(21, Test4105828);
211 #endif
212         TESTCASE(22, TestSetIsBogus);
213         TESTCASE(23, TestParallelAPIValues);
214         TESTCASE(24, TestKeywordVariants);
215         TESTCASE(25, TestKeywordVariantParsing);
216         TESTCASE(26, TestSetKeywordValue);
217         TESTCASE(27, TestGetBaseName);
218 #if !UCONFIG_NO_FILE_IO
219         TESTCASE(28, TestGetLocale);
220 #endif
221         TESTCASE(29, TestVariantWithOutCountry);
222         TESTCASE(30, TestCanonicalization);
223         TESTCASE(31, TestCurrencyByDate);
224 	TESTCASE(32, TestGetVariantWithKeywords);
225 
226         // keep the last index in sync with the condition in default:
227 
228         default:
229             if (index <= 28) { // keep this in sync with the last index!
230                 name = "(test omitted by !UCONFIG_NO_FORMATTING)";
231             } else {
232                 name = "";
233             }
234             break; //needed to end loop
235     }
236 }
237 
TestBasicGetters()238 void LocaleTest::TestBasicGetters() {
239     UnicodeString   temp;
240 
241     int32_t i;
242     for (i = 0; i <= MAX_LOCALES; i++) {
243         Locale testLocale("");
244         if (rawData[SCRIPT][i] && rawData[SCRIPT][i][0] != 0) {
245             testLocale = Locale(rawData[LANG][i], rawData[SCRIPT][i], rawData[CTRY][i], rawData[VAR][i]);
246         }
247         else {
248             testLocale = Locale(rawData[LANG][i], rawData[CTRY][i], rawData[VAR][i]);
249         }
250         logln("Testing " + (UnicodeString)testLocale.getName() + "...");
251 
252         if ( (temp=testLocale.getLanguage()) != (dataTable[LANG][i]))
253             errln("  Language code mismatch: " + temp + " versus "
254                         + dataTable[LANG][i]);
255         if ( (temp=testLocale.getScript()) != (dataTable[SCRIPT][i]))
256             errln("  Script code mismatch: " + temp + " versus "
257                         + dataTable[SCRIPT][i]);
258         if ( (temp=testLocale.getCountry()) != (dataTable[CTRY][i]))
259             errln("  Country code mismatch: " + temp + " versus "
260                         + dataTable[CTRY][i]);
261         if ( (temp=testLocale.getVariant()) != (dataTable[VAR][i]))
262             errln("  Variant code mismatch: " + temp + " versus "
263                         + dataTable[VAR][i]);
264         if ( (temp=testLocale.getName()) != (dataTable[NAME][i]))
265             errln("  Locale name mismatch: " + temp + " versus "
266                         + dataTable[NAME][i]);
267     }
268 
269     logln("Same thing without variant codes...");
270     for (i = 0; i <= MAX_LOCALES; i++) {
271         Locale testLocale("");
272         if (rawData[SCRIPT][i] && rawData[SCRIPT][i][0] != 0) {
273             testLocale = Locale(rawData[LANG][i], rawData[SCRIPT][i], rawData[CTRY][i]);
274         }
275         else {
276             testLocale = Locale(rawData[LANG][i], rawData[CTRY][i]);
277         }
278         logln("Testing " + (temp=testLocale.getName()) + "...");
279 
280         if ( (temp=testLocale.getLanguage()) != (dataTable[LANG][i]))
281             errln("Language code mismatch: " + temp + " versus "
282                         + dataTable[LANG][i]);
283         if ( (temp=testLocale.getScript()) != (dataTable[SCRIPT][i]))
284             errln("Script code mismatch: " + temp + " versus "
285                         + dataTable[SCRIPT][i]);
286         if ( (temp=testLocale.getCountry()) != (dataTable[CTRY][i]))
287             errln("Country code mismatch: " + temp + " versus "
288                         + dataTable[CTRY][i]);
289         if (testLocale.getVariant()[0] != 0)
290             errln("Variant code mismatch: something versus \"\"");
291     }
292 
293     logln("Testing long language names and getters");
294     Locale  test8 = Locale::createFromName("x-klingon-latn-zx.utf32be@special");
295 
296     temp = test8.getLanguage();
297     if (temp != UnicodeString("x-klingon") )
298         errln("Language code mismatch: " + temp + "  versus \"x-klingon\"");
299 
300     temp = test8.getScript();
301     if (temp != UnicodeString("Latn") )
302         errln("Script code mismatch: " + temp + "  versus \"Latn\"");
303 
304     temp = test8.getCountry();
305     if (temp != UnicodeString("ZX") )
306         errln("Country code mismatch: " + temp + "  versus \"ZX\"");
307 
308     temp = test8.getVariant();
309     //if (temp != UnicodeString("SPECIAL") )
310     //    errln("Variant code mismatch: " + temp + "  versus \"SPECIAL\"");
311     // As of 3.0, the "@special" will *not* be parsed by uloc_getName()
312     if (temp != UnicodeString("") )
313         errln("Variant code mismatch: " + temp + "  versus \"\"");
314 
315     if (Locale::getDefault() != Locale::createFromName(NULL))
316         errln("Locale::getDefault() == Locale::createFromName(NULL)");
317 
318     /*----------*/
319     // NOTE: There used to be a special test for locale names that had language or
320     // country codes that were longer than two letters.  The new version of Locale
321     // doesn't support anything that isn't an officially recognized language or
322     // country code, so we no longer support this feature.
323 
324     Locale bogusLang("THISISABOGUSLANGUAGE"); // Jitterbug 2864: language code too long
325     if(!bogusLang.isBogus()) {
326         errln("Locale(\"THISISABOGUSLANGUAGE\").isBogus()==FALSE");
327     }
328 
329     bogusLang=Locale("eo");
330     if( bogusLang.isBogus() ||
331         strcmp(bogusLang.getLanguage(), "eo")!=0 ||
332         *bogusLang.getCountry()!=0 ||
333         *bogusLang.getVariant()!=0 ||
334         strcmp(bogusLang.getName(), "eo")!=0
335     ) {
336         errln("assignment to bogus Locale does not unbogus it or sets bad data");
337     }
338 
339     Locale a("eo_DE@currency=DEM");
340     Locale *pb=a.clone();
341     if(pb==&a || *pb!=a) {
342         errln("Locale.clone() failed");
343     }
344     delete pb;
345 }
346 
TestParallelAPIValues()347 void LocaleTest::TestParallelAPIValues() {
348     logln("Test synchronization between C and C++ API");
349     if (strcmp(Locale::getChinese().getName(), ULOC_CHINESE) != 0) {
350         errln("Differences for ULOC_CHINESE Locale");
351     }
352     if (strcmp(Locale::getEnglish().getName(), ULOC_ENGLISH) != 0) {
353         errln("Differences for ULOC_ENGLISH Locale");
354     }
355     if (strcmp(Locale::getFrench().getName(), ULOC_FRENCH) != 0) {
356         errln("Differences for ULOC_FRENCH Locale");
357     }
358     if (strcmp(Locale::getGerman().getName(), ULOC_GERMAN) != 0) {
359         errln("Differences for ULOC_GERMAN Locale");
360     }
361     if (strcmp(Locale::getItalian().getName(), ULOC_ITALIAN) != 0) {
362         errln("Differences for ULOC_ITALIAN Locale");
363     }
364     if (strcmp(Locale::getJapanese().getName(), ULOC_JAPANESE) != 0) {
365         errln("Differences for ULOC_JAPANESE Locale");
366     }
367     if (strcmp(Locale::getKorean().getName(), ULOC_KOREAN) != 0) {
368         errln("Differences for ULOC_KOREAN Locale");
369     }
370     if (strcmp(Locale::getSimplifiedChinese().getName(), ULOC_SIMPLIFIED_CHINESE) != 0) {
371         errln("Differences for ULOC_SIMPLIFIED_CHINESE Locale");
372     }
373     if (strcmp(Locale::getTraditionalChinese().getName(), ULOC_TRADITIONAL_CHINESE) != 0) {
374         errln("Differences for ULOC_TRADITIONAL_CHINESE Locale");
375     }
376 
377 
378     if (strcmp(Locale::getCanada().getName(), ULOC_CANADA) != 0) {
379         errln("Differences for ULOC_CANADA Locale");
380     }
381     if (strcmp(Locale::getCanadaFrench().getName(), ULOC_CANADA_FRENCH) != 0) {
382         errln("Differences for ULOC_CANADA_FRENCH Locale");
383     }
384     if (strcmp(Locale::getChina().getName(), ULOC_CHINA) != 0) {
385         errln("Differences for ULOC_CHINA Locale");
386     }
387     if (strcmp(Locale::getPRC().getName(), ULOC_PRC) != 0) {
388         errln("Differences for ULOC_PRC Locale");
389     }
390     if (strcmp(Locale::getFrance().getName(), ULOC_FRANCE) != 0) {
391         errln("Differences for ULOC_FRANCE Locale");
392     }
393     if (strcmp(Locale::getGermany().getName(), ULOC_GERMANY) != 0) {
394         errln("Differences for ULOC_GERMANY Locale");
395     }
396     if (strcmp(Locale::getItaly().getName(), ULOC_ITALY) != 0) {
397         errln("Differences for ULOC_ITALY Locale");
398     }
399     if (strcmp(Locale::getJapan().getName(), ULOC_JAPAN) != 0) {
400         errln("Differences for ULOC_JAPAN Locale");
401     }
402     if (strcmp(Locale::getKorea().getName(), ULOC_KOREA) != 0) {
403         errln("Differences for ULOC_KOREA Locale");
404     }
405     if (strcmp(Locale::getTaiwan().getName(), ULOC_TAIWAN) != 0) {
406         errln("Differences for ULOC_TAIWAN Locale");
407     }
408     if (strcmp(Locale::getUK().getName(), ULOC_UK) != 0) {
409         errln("Differences for ULOC_UK Locale");
410     }
411     if (strcmp(Locale::getUS().getName(), ULOC_US) != 0) {
412         errln("Differences for ULOC_US Locale");
413     }
414 }
415 
416 
TestSimpleResourceInfo()417 void LocaleTest::TestSimpleResourceInfo() {
418     UnicodeString   temp;
419     char            temp2[20];
420     UErrorCode err = U_ZERO_ERROR;
421     int32_t i = 0;
422 
423     for (i = 0; i <= MAX_LOCALES; i++) {
424         Locale testLocale(rawData[LANG][i], rawData[CTRY][i], rawData[VAR][i]);
425         logln("Testing " + (temp=testLocale.getName()) + "...");
426 
427         if ( (temp=testLocale.getISO3Language()) != (dataTable[LANG3][i]))
428             errln("  ISO-3 language code mismatch: " + temp
429                 + " versus " + dataTable[LANG3][i]);
430         if ( (temp=testLocale.getISO3Country()) != (dataTable[CTRY3][i]))
431             errln("  ISO-3 country code mismatch: " + temp
432                 + " versus " + dataTable[CTRY3][i]);
433 
434         sprintf(temp2, "%x", (int)testLocale.getLCID());
435         if (UnicodeString(temp2) != dataTable[LCID][i])
436             errln((UnicodeString)"  LCID mismatch: " + temp2 + " versus "
437                 + dataTable[LCID][i]);
438 
439         if(U_FAILURE(err))
440         {
441             errln((UnicodeString)"Some error on number " + i + u_errorName(err));
442         }
443         err = U_ZERO_ERROR;
444     }
445 
446     Locale locale("en");
447     if(strcmp(locale.getName(), "en") != 0||
448         strcmp(locale.getLanguage(), "en") != 0) {
449         errln("construction of Locale(en) failed\n");
450     }
451     /*-----*/
452 
453 }
454 
455 /*
456  * Jitterbug 2439 -- markus 20030425
457  *
458  * The lookup of display names must not fall back through the default
459  * locale because that yields useless results.
460  */
461 void
TestDisplayNames()462 LocaleTest::TestDisplayNames()
463 {
464     Locale  english("en", "US");
465     Locale  french("fr", "FR");
466     Locale  croatian("ca", "ES");
467     Locale  greek("el", "GR");
468 
469     logln("  In locale = en_US...");
470     doTestDisplayNames(english, DLANG_EN);
471     logln("  In locale = fr_FR...");
472     doTestDisplayNames(french, DLANG_FR);
473     logln("  In locale = ca_ES...");
474     doTestDisplayNames(croatian, DLANG_CA);
475     logln("  In locale = el_GR...");
476     doTestDisplayNames(greek, DLANG_EL);
477 
478     UnicodeString s;
479     UErrorCode status = U_ZERO_ERROR;
480 
481 #if !UCONFIG_NO_FORMATTING
482     DecimalFormatSymbols symb(status);
483     /* Check to see if ICU supports this locale */
484     if (symb.getLocale(ULOC_VALID_LOCALE, status) != Locale("root")) {
485         /* test that the default locale has a display name for its own language */
486         /* Currently, there is no language information in the "tl" data file so this test will fail if default locale is "tl" */
487         if (uprv_strcmp(Locale().getLanguage(), "tl") != 0) {
488             Locale().getDisplayLanguage(Locale(), s);
489             if(s.length()<=3 && s.charAt(0)<=0x7f) {
490                 /* check <=3 to reject getting the language code as a display name */
491                 dataerrln("unable to get a display string for the language of the default locale: " + s);
492             }
493 
494             /*
495              * API coverage improvements: call
496              * Locale::getDisplayLanguage(UnicodeString &) and
497              * Locale::getDisplayCountry(UnicodeString &)
498              */
499             s.remove();
500             Locale().getDisplayLanguage(s);
501             if(s.length()<=3 && s.charAt(0)<=0x7f) {
502                 dataerrln("unable to get a display string for the language of the default locale [2]: " + s);
503             }
504         }
505     }
506     else {
507         logln("Default locale %s is unsupported by ICU\n", Locale().getName());
508     }
509     s.remove();
510 #endif
511 
512     french.getDisplayCountry(s);
513     if(s.isEmpty()) {
514         errln("unable to get any default-locale display string for the country of fr_FR\n");
515     }
516     s.remove();
517     Locale("zh", "Hant").getDisplayScript(s);
518     if(s.isEmpty()) {
519         errln("unable to get any default-locale display string for the country of zh_Hant\n");
520     }
521 }
522 
TestSimpleObjectStuff()523 void LocaleTest::TestSimpleObjectStuff() {
524     Locale  test1("aa", "AA");
525     Locale  test2("aa", "AA");
526     Locale  test3(test1);
527     Locale  test4("zz", "ZZ");
528     Locale  test5("aa", "AA", "");
529     Locale  test6("aa", "AA", "ANTARES");
530     Locale  test7("aa", "AA", "JUPITER");
531     Locale  test8 = Locale::createFromName("aa-aa-jupiTER"); // was "aa-aa.utf8@jupiter" but in 3.0 getName won't normalize that
532 
533     // now list them all for debugging usage.
534     test_dumpLocale(test1);
535     test_dumpLocale(test2);
536     test_dumpLocale(test3);
537     test_dumpLocale(test4);
538     test_dumpLocale(test5);
539     test_dumpLocale(test6);
540     test_dumpLocale(test7);
541     test_dumpLocale(test8);
542 
543     // Make sure things compare to themselves!
544     test_assert(test1 == test1);
545     test_assert(test2 == test2);
546     test_assert(test3 == test3);
547     test_assert(test4 == test4);
548     test_assert(test5 == test5);
549     test_assert(test6 == test6);
550     test_assert(test7 == test7);
551     test_assert(test8 == test8);
552 
553     // make sure things are not equal to themselves.
554     test_assert(!(test1 != test1));
555     test_assert(!(test2 != test2));
556     test_assert(!(test3 != test3));
557     test_assert(!(test4 != test4));
558     test_assert(!(test5 != test5));
559     test_assert(!(test6 != test6));
560     test_assert(!(test7 != test7));
561     test_assert(!(test8 != test8));
562 
563     // make sure things that are equal to each other don't show up as unequal.
564     test_assert(!(test1 != test2));
565     test_assert(!(test2 != test1));
566     test_assert(!(test1 != test3));
567     test_assert(!(test2 != test3));
568     test_assert(test5 == test1);
569     test_assert(test6 != test2);
570     test_assert(test6 != test5);
571 
572     test_assert(test6 != test7);
573 
574     // test for things that shouldn't compare equal.
575     test_assert(!(test1 == test4));
576     test_assert(!(test2 == test4));
577     test_assert(!(test3 == test4));
578 
579     test_assert(test7 == test8);
580 
581     // test for hash codes to be the same.
582     int32_t hash1 = test1.hashCode();
583     int32_t hash2 = test2.hashCode();
584     int32_t hash3 = test3.hashCode();
585 
586     test_assert(hash1 == hash2);
587     test_assert(hash1 == hash3);
588     test_assert(hash2 == hash3);
589 
590     // test that the assignment operator works.
591     test4 = test1;
592     logln("test4=test1;");
593     test_dumpLocale(test4);
594     test_assert(test4 == test4);
595 
596     test_assert(!(test1 != test4));
597     test_assert(!(test2 != test4));
598     test_assert(!(test3 != test4));
599     test_assert(test1 == test4);
600     test_assert(test4 == test1);
601 
602     // test assignments with a variant
603     logln("test7 = test6");
604     test7 = test6;
605     test_dumpLocale(test7);
606     test_assert(test7 == test7);
607     test_assert(test7 == test6);
608     test_assert(test7 != test5);
609 
610     logln("test6 = test1");
611     test6=test1;
612     test_dumpLocale(test6);
613     test_assert(test6 != test7);
614     test_assert(test6 == test1);
615     test_assert(test6 == test6);
616 }
617 
618 // A class which exposes constructors that are implemented in terms of the POSIX parsing code.
619 class POSIXLocale : public Locale
620 {
621 public:
POSIXLocale(const UnicodeString & l)622     POSIXLocale(const UnicodeString& l)
623         :Locale()
624     {
625       char *ch;
626       ch = new char[l.length() + 1];
627       ch[l.extract(0, 0x7fffffff, ch, "")] = 0;
628       setFromPOSIXID(ch);
629       delete [] ch;
630     }
POSIXLocale(const char * l)631     POSIXLocale(const char *l)
632         :Locale()
633     {
634         setFromPOSIXID(l);
635     }
636 };
637 
TestPOSIXParsing()638 void LocaleTest::TestPOSIXParsing()
639 {
640     POSIXLocale  test1("ab_AB");
641     POSIXLocale  test2(UnicodeString("ab_AB"));
642     Locale  test3("ab","AB");
643 
644     POSIXLocale test4("ab_AB_Antares");
645     POSIXLocale test5(UnicodeString("ab_AB_Antares"));
646     Locale  test6("ab", "AB", "Antares");
647 
648     test_dumpLocale(test1);
649     test_dumpLocale(test2);
650     test_dumpLocale(test3);
651     test_dumpLocale(test4);
652     test_dumpLocale(test5);
653     test_dumpLocale(test6);
654 
655     test_assert(test1 == test1);
656 
657     test_assert(test1 == test2);
658     test_assert(test2 == test3);
659     test_assert(test3 == test1);
660 
661     test_assert(test4 == test5);
662     test_assert(test5 == test6);
663     test_assert(test6 == test4);
664 
665     test_assert(test1 != test4);
666     test_assert(test5 != test3);
667     test_assert(test5 != test2);
668 
669     int32_t hash1 = test1.hashCode();
670     int32_t hash2 = test2.hashCode();
671     int32_t hash3 = test3.hashCode();
672 
673     test_assert(hash1 == hash2);
674     test_assert(hash2 == hash3);
675     test_assert(hash3 == hash1);
676 }
677 
TestGetAvailableLocales()678 void LocaleTest::TestGetAvailableLocales()
679 {
680     int32_t locCount = 0;
681     const Locale* locList = Locale::getAvailableLocales(locCount);
682 
683     if (locCount == 0)
684         dataerrln("getAvailableLocales() returned an empty list!");
685     else {
686         logln(UnicodeString("Number of locales returned = ") + locCount);
687         UnicodeString temp;
688         for(int32_t i = 0; i < locCount; ++i)
689             logln(locList[i].getName());
690     }
691     // I have no idea how to test this function...
692 }
693 
694 // This test isn't applicable anymore - getISO3Language is
695 // independent of the data directory
TestDataDirectory()696 void LocaleTest::TestDataDirectory()
697 {
698 /*
699     char            oldDirectory[80];
700     const char*     temp;
701     UErrorCode       err = U_ZERO_ERROR;
702     UnicodeString   testValue;
703 
704     temp = Locale::getDataDirectory();
705     strcpy(oldDirectory, temp);
706     logln(UnicodeString("oldDirectory = ") + oldDirectory);
707 
708     Locale  test(Locale::US);
709     test.getISO3Language(testValue);
710     logln("first fetch of language retrieved " + testValue);
711     if (testValue != "eng")
712         errln("Initial check of ISO3 language failed: expected \"eng\", got \"" + testValue + "\"");
713 
714     {
715         char *path;
716         path=IntlTest::getTestDirectory();
717         Locale::setDataDirectory( path );
718     }
719 
720     test.getISO3Language(testValue);
721     logln("second fetch of language retrieved " + testValue);
722     if (testValue != "xxx")
723         errln("setDataDirectory() failed: expected \"xxx\", got \"" + testValue + "\"");
724 
725     Locale::setDataDirectory(oldDirectory);
726     test.getISO3Language(testValue);
727     logln("third fetch of language retrieved " + testValue);
728     if (testValue != "eng")
729         errln("get/setDataDirectory() failed: expected \"eng\", got \"" + testValue + "\"");
730 */
731 }
732 
733 //===========================================================
734 
doTestDisplayNames(Locale & displayLocale,int32_t compareIndex)735 void LocaleTest::doTestDisplayNames(Locale& displayLocale, int32_t compareIndex) {
736     UnicodeString   temp;
737 
738     for (int32_t i = 0; i <= MAX_LOCALES; i++) {
739         Locale testLocale("");
740         if (rawData[SCRIPT][i] && rawData[SCRIPT][i][0] != 0) {
741             testLocale = Locale(rawData[LANG][i], rawData[SCRIPT][i], rawData[CTRY][i], rawData[VAR][i]);
742         }
743         else {
744             testLocale = Locale(rawData[LANG][i], rawData[CTRY][i], rawData[VAR][i]);
745         }
746         logln("  Testing " + (temp=testLocale.getName()) + "...");
747 
748         UnicodeString  testLang;
749         UnicodeString  testScript;
750         UnicodeString  testCtry;
751         UnicodeString  testVar;
752         UnicodeString  testName;
753 
754         testLocale.getDisplayLanguage(displayLocale, testLang);
755         testLocale.getDisplayScript(displayLocale, testScript);
756         testLocale.getDisplayCountry(displayLocale, testCtry);
757         testLocale.getDisplayVariant(displayLocale, testVar);
758         testLocale.getDisplayName(displayLocale, testName);
759 
760         UnicodeString  expectedLang;
761         UnicodeString  expectedScript;
762         UnicodeString  expectedCtry;
763         UnicodeString  expectedVar;
764         UnicodeString  expectedName;
765 
766         expectedLang = dataTable[compareIndex][i];
767         if (expectedLang.length() == 0)
768             expectedLang = dataTable[DLANG_EN][i];
769 
770         expectedScript = dataTable[compareIndex + 1][i];
771         if (expectedScript.length() == 0)
772             expectedScript = dataTable[DSCRIPT_EN][i];
773 
774         expectedCtry = dataTable[compareIndex + 2][i];
775         if (expectedCtry.length() == 0)
776             expectedCtry = dataTable[DCTRY_EN][i];
777 
778         expectedVar = dataTable[compareIndex + 3][i];
779         if (expectedVar.length() == 0)
780             expectedVar = dataTable[DVAR_EN][i];
781 
782         expectedName = dataTable[compareIndex + 4][i];
783         if (expectedName.length() == 0)
784             expectedName = dataTable[DNAME_EN][i];
785 
786         if (testLang != expectedLang)
787             dataerrln("Display language (" + UnicodeString(displayLocale.getName()) + ") of (" + UnicodeString(testLocale.getName()) + ") got " + testLang + " expected " + expectedLang);
788         if (testScript != expectedScript)
789             dataerrln("Display script (" + UnicodeString(displayLocale.getName()) + ") of (" + UnicodeString(testLocale.getName()) + ") got " + testScript + " expected " + expectedScript);
790         if (testCtry != expectedCtry)
791             dataerrln("Display country (" + UnicodeString(displayLocale.getName()) + ") of (" + UnicodeString(testLocale.getName()) + ") got " + testCtry + " expected " + expectedCtry);
792         if (testVar != expectedVar)
793             dataerrln("Display variant (" + UnicodeString(displayLocale.getName()) + ") of (" + UnicodeString(testLocale.getName()) + ") got " + testVar + " expected " + expectedVar);
794         if (testName != expectedName)
795             dataerrln("Display name (" + UnicodeString(displayLocale.getName()) + ") of (" + UnicodeString(testLocale.getName()) + ") got " + testName + " expected " + expectedName);
796     }
797 }
798 
799 //---------------------------------------------------
800 // table of valid data
801 //---------------------------------------------------
802 
803 
804 
setUpDataTable()805 void LocaleTest::setUpDataTable()
806 {
807     if (dataTable == 0) {
808         dataTable = new UnicodeString*[33];
809 
810         for (int32_t i = 0; i < 33; i++) {
811             dataTable[i] = new UnicodeString[8];
812             for (int32_t j = 0; j < 8; j++) {
813                 dataTable[i][j] = CharsToUnicodeString(rawData[i][j]);
814             }
815         }
816     }
817 }
818 
819 // ====================
820 
821 
822 /**
823  * @bug 4011756 4011380
824  */
825 void
TestISO3Fallback()826 LocaleTest::TestISO3Fallback()
827 {
828     Locale test("xx", "YY");
829 
830     const char * result;
831 
832     result = test.getISO3Language();
833 
834     // Conform to C API usage
835 
836     if (!result || (result[0] != 0))
837         errln("getISO3Language() on xx_YY returned " + UnicodeString(result) + " instead of \"\"");
838 
839     result = test.getISO3Country();
840 
841     if (!result || (result[0] != 0))
842         errln("getISO3Country() on xx_YY returned " + UnicodeString(result) + " instead of \"\"");
843 }
844 
845 /**
846  * @bug 4106155 4118587
847  */
848 void
TestGetLangsAndCountries()849 LocaleTest::TestGetLangsAndCountries()
850 {
851     // It didn't seem right to just do an exhaustive test of everything here, so I check
852     // for the following things:
853     // 1) Does each list have the right total number of entries?
854     // 2) Does each list contain certain language and country codes we think are important
855     //     (the G7 countries, plus a couple others)?
856     // 3) Does each list have every entry formatted correctly? (i.e., two characters,
857     //     all lower case for the language codes, all upper case for the country codes)
858     // 4) Is each list in sorted order?
859     int32_t testCount = 0;
860     const char * const * test = Locale::getISOLanguages();
861     const char spotCheck1[ ][4] = { "en", "es", "fr", "de", "it",
862                                     "ja", "ko", "zh", "th", "he",
863                                     "id", "iu", "ug", "yi", "za" };
864 
865     int32_t i;
866 
867     for(testCount = 0;test[testCount];testCount++)
868       ;
869 
870     /* TODO: Change this test to be more like the cloctst version? */
871     if (testCount != 560)
872         errln("Expected getISOLanguages() to return 560 languages; it returned %d", testCount);
873     else {
874         for (i = 0; i < 15; i++) {
875             int32_t j;
876             for (j = 0; j < testCount; j++)
877               if (uprv_strcmp(test[j],spotCheck1[i])== 0)
878                     break;
879             if (j == testCount || (uprv_strcmp(test[j],spotCheck1[i])!=0))
880                 errln("Couldn't find " + (UnicodeString)spotCheck1[i] + " in language list.");
881         }
882     }
883     for (i = 0; i < testCount; i++) {
884         UnicodeString testee(test[i],"");
885         UnicodeString lc(test[i],"");
886         if (testee != lc.toLower())
887             errln(lc + " is not all lower case.");
888         if ( (testee.length() != 2) && (testee.length() != 3))
889             errln(testee + " is not two or three characters long.");
890         if (i > 0 && testee.compare(test[i - 1]) <= 0)
891             errln(testee + " appears in an out-of-order position in the list.");
892     }
893 
894     test = Locale::getISOCountries();
895     UnicodeString spotCheck2 [] = { "US", "CA", "GB", "FR", "DE",
896                                     "IT", "JP", "KR", "CN", "TW",
897                                     "TH" };
898     int32_t spot2Len = 11;
899     for(testCount=0;test[testCount];testCount++)
900       ;
901 
902     if (testCount != 249){
903         errln("Expected getISOCountries to return 249 countries; it returned %d", testCount);
904     }else {
905         for (i = 0; i < spot2Len; i++) {
906             int32_t j;
907             for (j = 0; j < testCount; j++)
908               {
909                 UnicodeString testee(test[j],"");
910 
911                 if (testee == spotCheck2[i])
912                     break;
913               }
914                 UnicodeString testee(test[j],"");
915             if (j == testCount || testee != spotCheck2[i])
916                 errln("Couldn't find " + spotCheck2[i] + " in country list.");
917         }
918     }
919     for (i = 0; i < testCount; i++) {
920         UnicodeString testee(test[i],"");
921         UnicodeString uc(test[i],"");
922         if (testee != uc.toUpper())
923             errln(testee + " is not all upper case.");
924         if (testee.length() != 2)
925             errln(testee + " is not two characters long.");
926         if (i > 0 && testee.compare(test[i - 1]) <= 0)
927             errln(testee + " appears in an out-of-order position in the list.");
928     }
929 
930     // This getAvailableLocales and getISO3Language
931     {
932         int32_t numOfLocales;
933         Locale  enLoc ("en");
934         const Locale *pLocales = Locale::getAvailableLocales(numOfLocales);
935 
936         for (int i = 0; i < numOfLocales; i++) {
937             const Locale    &loc(pLocales[i]);
938             UnicodeString   name;
939             char        szName[200];
940 
941             loc.getDisplayName (enLoc, name);
942             name.extract (0, 200, szName, sizeof(szName));
943 
944             if (strlen(loc.getISO3Language()) == 0) {
945                 errln("getISO3Language() returned an empty string for: " + name);
946             }
947         }
948     }
949 }
950 
951 /**
952  * @bug 4118587
953  */
954 void
TestSimpleDisplayNames()955 LocaleTest::TestSimpleDisplayNames()
956 {
957     // This test is different from TestDisplayNames because TestDisplayNames checks
958     // fallback behavior, combination of language and country names to form locale
959     // names, and other stuff like that.  This test just checks specific language
960     // and country codes to make sure we have the correct names for them.
961     char languageCodes[] [4] = { "he", "id", "iu", "ug", "yi", "za" };
962     UnicodeString languageNames [] = { "Hebrew", "Indonesian", "Inuktitut", "Uyghur", "Yiddish",
963                                "Zhuang" };
964 
965     for (int32_t i = 0; i < 6; i++) {
966         UnicodeString test;
967         Locale l(languageCodes[i], "", "");
968         l.getDisplayLanguage(Locale::getUS(), test);
969         if (test != languageNames[i])
970             dataerrln("Got wrong display name for " + UnicodeString(languageCodes[i]) + ": Expected \"" +
971                   languageNames[i] + "\", got \"" + test + "\".");
972     }
973 }
974 
975 /**
976  * @bug 4118595
977  */
978 void
TestUninstalledISO3Names()979 LocaleTest::TestUninstalledISO3Names()
980 {
981     // This test checks to make sure getISO3Language and getISO3Country work right
982     // even for locales that are not installed.
983     const char iso2Languages [][4] = {     "am", "ba", "fy", "mr", "rn",
984                                         "ss", "tw", "zu" };
985     const char iso3Languages [][5] = {     "amh", "bak", "fry", "mar", "run",
986                                         "ssw", "twi", "zul" };
987 
988     int32_t i;
989 
990     for (i = 0; i < 8; i++) {
991       UErrorCode err = U_ZERO_ERROR;
992 
993       UnicodeString test;
994         Locale l(iso2Languages[i], "", "");
995         test = l.getISO3Language();
996         if((test != iso3Languages[i]) || U_FAILURE(err))
997             errln("Got wrong ISO3 code for " + UnicodeString(iso2Languages[i]) + ": Expected \"" +
998                     iso3Languages[i] + "\", got \"" + test + "\"." + UnicodeString(u_errorName(err)));
999     }
1000 
1001     char iso2Countries [][4] = {     "AF", "BW", "KZ", "MO", "MN",
1002                                         "SB", "TC", "ZW" };
1003     char iso3Countries [][4] = {     "AFG", "BWA", "KAZ", "MAC", "MNG",
1004                                         "SLB", "TCA", "ZWE" };
1005 
1006     for (i = 0; i < 8; i++) {
1007       UErrorCode err = U_ZERO_ERROR;
1008         Locale l("", iso2Countries[i], "");
1009         UnicodeString test(l.getISO3Country(), "");
1010         if (test != iso3Countries[i])
1011             errln("Got wrong ISO3 code for " + UnicodeString(iso2Countries[i]) + ": Expected \"" +
1012                     UnicodeString(iso3Countries[i]) + "\", got \"" + test + "\"." + u_errorName(err));
1013     }
1014 }
1015 
1016 /**
1017  * @bug 4092475
1018  * I could not reproduce this bug.  I'm pretty convinced it was fixed with the
1019  * big locale-data reorg of 10/28/97.  The lookup logic for language and country
1020  * display names was also changed at that time in that check-in.    --rtg 3/20/98
1021  */
1022 void
TestAtypicalLocales()1023 LocaleTest::TestAtypicalLocales()
1024 {
1025     Locale localesToTest [] = { Locale("de", "CA"),
1026                                   Locale("ja", "ZA"),
1027                                    Locale("ru", "MX"),
1028                                    Locale("en", "FR"),
1029                                    Locale("es", "DE"),
1030                                    Locale("", "HR"),
1031                                    Locale("", "SE"),
1032                                    Locale("", "DO"),
1033                                    Locale("", "BE") };
1034 
1035     UnicodeString englishDisplayNames [] = { "German (Canada)",
1036                                      "Japanese (South Africa)",
1037                                      "Russian (Mexico)",
1038                                      "English (France)",
1039                                      "Spanish (Germany)",
1040                                      "Croatia",
1041                                      "Sweden",
1042                                      "Dominican Republic",
1043                                      "Belgium" };
1044     UnicodeString frenchDisplayNames []= { "allemand (Canada)",
1045                                     "japonais (Afrique du Sud)",
1046                                     "russe (Mexique)",
1047                                      "anglais (France)",
1048                                      "espagnol (Allemagne)",
1049                                     "Croatie",
1050                                     CharsToUnicodeString("Su\\u00E8de"),
1051                                     CharsToUnicodeString("R\\u00E9publique dominicaine"),
1052                                     "Belgique" };
1053     UnicodeString spanishDisplayNames [] = {
1054                                      CharsToUnicodeString("alem\\u00E1n (Canad\\u00E1)"),
1055                                      CharsToUnicodeString("japon\\u00E9s (Sud\\u00E1frica)"),
1056                                      CharsToUnicodeString("ruso (M\\u00E9xico)"),
1057                                      CharsToUnicodeString("ingl\\u00E9s (Francia)"),
1058                                      CharsToUnicodeString("espa\\u00F1ol (Alemania)"),
1059                                      "Croacia",
1060                                      "Suecia",
1061                                      CharsToUnicodeString("Rep\\u00FAblica Dominicana"),
1062                                      CharsToUnicodeString("B\\u00E9lgica") };
1063     // De-Anglicizing root required the change from
1064     // English display names to ISO Codes - ram 2003/09/26
1065     UnicodeString invDisplayNames [] = { "German (Canada)",
1066                                      "Japanese (South Africa)",
1067                                      "Russian (Mexico)",
1068                                      "English (France)",
1069                                      "Spanish (Germany)",
1070                                      "Croatia",
1071                                      "Sweden",
1072                                      "Dominican Republic",
1073                                      "Belgium" };
1074 
1075     int32_t i;
1076     UErrorCode status = U_ZERO_ERROR;
1077     Locale saveLocale;
1078     Locale::setDefault(Locale::getUS(), status);
1079     for (i = 0; i < 9; ++i) {
1080         UnicodeString name;
1081         localesToTest[i].getDisplayName(Locale::getUS(), name);
1082         logln(name);
1083         if (name != englishDisplayNames[i])
1084         {
1085             dataerrln("Lookup in English failed: expected \"" + englishDisplayNames[i]
1086                         + "\", got \"" + name + "\"");
1087             logln("Locale name was-> " + (name=localesToTest[i].getName()));
1088         }
1089     }
1090 
1091     for (i = 0; i < 9; i++) {
1092         UnicodeString name;
1093         localesToTest[i].getDisplayName(Locale("es", "ES"), name);
1094         logln(name);
1095         if (name != spanishDisplayNames[i])
1096             dataerrln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i]
1097                         + "\", got \"" + name + "\"");
1098     }
1099 
1100     for (i = 0; i < 9; i++) {
1101         UnicodeString name;
1102         localesToTest[i].getDisplayName(Locale::getFrance(), name);
1103         logln(name);
1104         if (name != frenchDisplayNames[i])
1105             dataerrln("Lookup in French failed: expected \"" + frenchDisplayNames[i]
1106                         + "\", got \"" + name + "\"");
1107     }
1108 
1109     for (i = 0; i < 9; i++) {
1110         UnicodeString name;
1111         localesToTest[i].getDisplayName(Locale("inv", "IN"), name);
1112         logln(name + " Locale fallback to be, and data fallback to root");
1113         if (name != invDisplayNames[i])
1114             dataerrln("Lookup in INV failed: expected \"" + prettify(invDisplayNames[i])
1115                         + "\", got \"" + prettify(name) + "\"");
1116         localesToTest[i].getDisplayName(Locale("inv", "BD"), name);
1117         logln(name + " Data fallback to root");
1118         if (name != invDisplayNames[i])
1119             dataerrln("Lookup in INV failed: expected \"" + prettify(invDisplayNames[i])
1120                         + "\", got \"" + prettify(name )+ "\"");
1121     }
1122     Locale::setDefault(saveLocale, status);
1123 }
1124 
1125 #if !UCONFIG_NO_FORMATTING
1126 
1127 /**
1128  * @bug 4135752
1129  * This would be better tested by the LocaleDataTest.  Will move it when I
1130  * get the LocaleDataTest working again.
1131  */
1132 void
TestThaiCurrencyFormat()1133 LocaleTest::TestThaiCurrencyFormat()
1134 {
1135     UErrorCode status = U_ZERO_ERROR;
1136     DecimalFormat *thaiCurrency = (DecimalFormat*)NumberFormat::createCurrencyInstance(
1137                     Locale("th", "TH"), status);
1138     UChar posPrefix = 0x0e3f;
1139     UnicodeString temp;
1140 
1141     if(U_FAILURE(status) || !thaiCurrency)
1142     {
1143         dataerrln("Couldn't get th_TH currency -> " + UnicodeString(u_errorName(status)));
1144         return;
1145     }
1146     if (thaiCurrency->getPositivePrefix(temp) != UnicodeString(&posPrefix, 1, 1))
1147         errln("Thai currency prefix wrong: expected 0x0e3f, got \"" +
1148                         thaiCurrency->getPositivePrefix(temp) + "\"");
1149     if (thaiCurrency->getPositiveSuffix(temp) != "")
1150         errln("Thai currency suffix wrong: expected \"\", got \"" +
1151                         thaiCurrency->getPositiveSuffix(temp) + "\"");
1152 
1153     delete thaiCurrency;
1154 }
1155 
1156 /**
1157  * @bug 4122371
1158  * Confirm that Euro support works.  This test is pretty rudimentary; all it does
1159  * is check that any locales with the EURO variant format a number using the
1160  * Euro currency symbol.
1161  *
1162  * ASSUME: All locales encode the Euro character "\u20AC".
1163  * If this is changed to use the single-character Euro symbol, this
1164  * test must be updated.
1165  *
1166  */
1167 void
TestEuroSupport()1168 LocaleTest::TestEuroSupport()
1169 {
1170     UChar euro = 0x20ac;
1171     const UnicodeString EURO_CURRENCY(&euro, 1, 1); // Look for this UnicodeString in formatted Euro currency
1172     const char* localeArr[] = {
1173                             "ca_ES",
1174                             "de_AT",
1175                             "de_DE",
1176                             "de_LU",
1177                             "el_GR",
1178                             "en_BE",
1179                             "en_IE",
1180                             "en_GB_EURO",
1181                             "en_US_EURO",
1182                             "es_ES",
1183                             "eu_ES",
1184                             "fi_FI",
1185                             "fr_BE",
1186                             "fr_FR",
1187                             "fr_LU",
1188                             "ga_IE",
1189                             "gl_ES",
1190                             "it_IT",
1191                             "nl_BE",
1192                             "nl_NL",
1193                             "pt_PT",
1194                             NULL
1195                         };
1196     const char** locales = localeArr;
1197 
1198     UErrorCode status = U_ZERO_ERROR;
1199 
1200     UnicodeString temp;
1201 
1202     for (;*locales!=NULL;locales++) {
1203         Locale loc (*locales);
1204         UnicodeString temp;
1205         NumberFormat *nf = NumberFormat::createCurrencyInstance(loc, status);
1206         UnicodeString pos;
1207 
1208         if (U_FAILURE(status)) {
1209             dataerrln("Error calling NumberFormat::createCurrencyInstance(%s)", *locales);
1210             continue;
1211         }
1212 
1213         nf->format(271828.182845, pos);
1214         UnicodeString neg;
1215         nf->format(-271828.182845, neg);
1216         if (pos.indexOf(EURO_CURRENCY) >= 0 &&
1217             neg.indexOf(EURO_CURRENCY) >= 0) {
1218             logln("Ok: " + (temp=loc.getName()) +
1219                 ": " + pos + " / " + neg);
1220         }
1221         else {
1222             errln("Fail: " + (temp=loc.getName()) +
1223                 " formats without " + EURO_CURRENCY +
1224                 ": " + pos + " / " + neg +
1225                 "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***");
1226         }
1227 
1228         delete nf;
1229     }
1230 
1231     UnicodeString dollarStr("USD", ""), euroStr("EUR", ""), genericStr((UChar)0x00a4), resultStr;
1232     UChar tmp[4];
1233     status = U_ZERO_ERROR;
1234 
1235     ucurr_forLocale("en_US", tmp, 4, &status);
1236     resultStr.setTo(tmp);
1237     if (dollarStr != resultStr) {
1238         errcheckln(status, "Fail: en_US didn't return USD - %s", u_errorName(status));
1239     }
1240     ucurr_forLocale("en_US_EURO", tmp, 4, &status);
1241     resultStr.setTo(tmp);
1242     if (euroStr != resultStr) {
1243         errcheckln(status, "Fail: en_US_EURO didn't return EUR - %s", u_errorName(status));
1244     }
1245     ucurr_forLocale("en_GB_EURO", tmp, 4, &status);
1246     resultStr.setTo(tmp);
1247     if (euroStr != resultStr) {
1248         errcheckln(status, "Fail: en_GB_EURO didn't return EUR - %s", u_errorName(status));
1249     }
1250     ucurr_forLocale("en_US_PREEURO", tmp, 4, &status);
1251     resultStr.setTo(tmp);
1252     if (dollarStr != resultStr) {
1253         errcheckln(status, "Fail: en_US_PREEURO didn't fallback to en_US - %s", u_errorName(status));
1254     }
1255     ucurr_forLocale("en_US_Q", tmp, 4, &status);
1256     resultStr.setTo(tmp);
1257     if (dollarStr != resultStr) {
1258         errcheckln(status, "Fail: en_US_Q didn't fallback to en_US - %s", u_errorName(status));
1259     }
1260     int32_t invalidLen = ucurr_forLocale("en_QQ", tmp, 4, &status);
1261     if (invalidLen || U_SUCCESS(status)) {
1262         errln("Fail: en_QQ didn't return NULL");
1263     }
1264 }
1265 
1266 #endif
1267 
1268 /**
1269  * @bug 4139504
1270  * toString() doesn't work with language_VARIANT.
1271  */
1272 void
TestToString()1273 LocaleTest::TestToString() {
1274     Locale DATA [] = {
1275         Locale("xx", "", ""),
1276         Locale("", "YY", ""),
1277         Locale("", "", "ZZ"),
1278         Locale("xx", "YY", ""),
1279         Locale("xx", "", "ZZ"),
1280         Locale("", "YY", "ZZ"),
1281         Locale("xx", "YY", "ZZ"),
1282     };
1283 
1284     const char DATA_S [][20] = {
1285         "xx",
1286         "_YY",
1287         "__ZZ",
1288         "xx_YY",
1289         "xx__ZZ",
1290         "_YY_ZZ",
1291         "xx_YY_ZZ",
1292     };
1293 
1294     for (int32_t i=0; i < 7; ++i) {
1295       const char *name;
1296       name = DATA[i].getName();
1297 
1298       if (strcmp(name, DATA_S[i]) != 0)
1299         {
1300             errln("Fail: Locale.getName(), got:" + UnicodeString(name) + ", expected: " + DATA_S[i]);
1301         }
1302         else
1303             logln("Pass: Locale.getName(), got:" + UnicodeString(name) );
1304     }
1305 }
1306 
1307 #if !UCONFIG_NO_FORMATTING
1308 
1309 /**
1310  * @bug 4139940
1311  * Couldn't reproduce this bug -- probably was fixed earlier.
1312  *
1313  * ORIGINAL BUG REPORT:
1314  * -- basically, hungarian for monday shouldn't have an \u00f4
1315  * (o circumflex)in it instead it should be an o with 2 inclined
1316  * (right) lines over it..
1317  *
1318  * You may wonder -- why do all this -- why not just add a line to
1319  * LocaleData?  Well, I could see by inspection that the locale file had the
1320  * right character in it, so I wanted to check the rest of the pipeline -- a
1321  * very remote possibility, but I wanted to be sure.  The other possibility
1322  * is that something is wrong with the font mapping subsystem, but we can't
1323  * test that here.
1324  */
1325 void
Test4139940()1326 LocaleTest::Test4139940()
1327 {
1328     Locale mylocale("hu", "", "");
1329     UDate mydate = date(98,3,13); // A Monday
1330     UErrorCode status = U_ZERO_ERROR;
1331     SimpleDateFormat df_full("EEEE", mylocale, status);
1332     if(U_FAILURE(status)){
1333         dataerrln(UnicodeString("Could not create SimpleDateFormat object for locale hu. Error: ") + UnicodeString(u_errorName(status)));
1334         return;
1335     }
1336     UnicodeString str;
1337     FieldPosition pos(FieldPosition::DONT_CARE);
1338     df_full.format(mydate, str, pos);
1339     // Make sure that o circumflex (\u00F4) is NOT there, and
1340     // o double acute (\u0151) IS.
1341     UChar ocf = 0x00f4;
1342     UChar oda = 0x0151;
1343     if (str.indexOf(oda) < 0 || str.indexOf(ocf) >= 0) {
1344       /* If the default locale is "th" this test will fail because of the buddhist calendar. */
1345       if (strcmp(Locale::getDefault().getLanguage(), "th") != 0) {
1346         errln("Fail: Monday in Hungarian is wrong - oda's index is %d and ocf's is %d",
1347               str.indexOf(oda), str.indexOf(ocf));
1348       } else {
1349         logln(UnicodeString("An error is produce in buddhist calendar."));
1350       }
1351       logln(UnicodeString("String is: ") + str );
1352     }
1353 }
1354 
1355 UDate
date(int32_t y,int32_t m,int32_t d,int32_t hr,int32_t min,int32_t sec)1356 LocaleTest::date(int32_t y, int32_t m, int32_t d, int32_t hr, int32_t min, int32_t sec)
1357 {
1358     UErrorCode status = U_ZERO_ERROR;
1359     Calendar *cal = Calendar::createInstance(status);
1360     if (cal == 0)
1361         return 0.0;
1362     cal->clear();
1363     cal->set(1900 + y, m, d, hr, min, sec); // Add 1900 to follow java.util.Date protocol
1364     UDate dt = cal->getTime(status);
1365     if (U_FAILURE(status))
1366         return 0.0;
1367 
1368     delete cal;
1369     return dt;
1370 }
1371 
1372 /**
1373  * @bug 4143951
1374  * Russian first day of week should be Monday. Confirmed.
1375  */
1376 void
Test4143951()1377 LocaleTest::Test4143951()
1378 {
1379     UErrorCode status = U_ZERO_ERROR;
1380     Calendar *cal = Calendar::createInstance(Locale("ru", "", ""), status);
1381     if(U_SUCCESS(status)) {
1382       if (cal->getFirstDayOfWeek(status) != UCAL_MONDAY) {
1383           dataerrln("Fail: First day of week in Russia should be Monday");
1384       }
1385     }
1386     delete cal;
1387 }
1388 
1389 #endif
1390 
1391 /**
1392  * @bug 4147315
1393  * java.util.Locale.getISO3Country() works wrong for non ISO-3166 codes.
1394  * Should throw an exception for unknown locales
1395  */
1396 void
Test4147315()1397 LocaleTest::Test4147315()
1398 {
1399   UnicodeString temp;
1400     // Try with codes that are the wrong length but happen to match text
1401     // at a valid offset in the mapping table
1402     Locale locale("xxx", "CCC");
1403 
1404     const char *result = locale.getISO3Country();
1405 
1406     // Change to conform to C api usage
1407     if((result==NULL)||(result[0] != 0))
1408       errln("ERROR: getISO3Country() returns: " + UnicodeString(result,"") +
1409                 " for locale '" + (temp=locale.getName()) + "' rather than exception" );
1410 }
1411 
1412 /**
1413  * @bug 4147317
1414  * java.util.Locale.getISO3Language() works wrong for non ISO-3166 codes.
1415  * Should throw an exception for unknown locales
1416  */
1417 void
Test4147317()1418 LocaleTest::Test4147317()
1419 {
1420     UnicodeString temp;
1421     // Try with codes that are the wrong length but happen to match text
1422     // at a valid offset in the mapping table
1423     Locale locale("xxx", "CCC");
1424 
1425     const char *result = locale.getISO3Language();
1426 
1427     // Change to conform to C api usage
1428     if((result==NULL)||(result[0] != 0))
1429       errln("ERROR: getISO3Language() returns: " + UnicodeString(result,"") +
1430                 " for locale '" + (temp=locale.getName()) + "' rather than exception" );
1431 }
1432 
1433 /*
1434  * @bug 4147552
1435  */
1436 void
Test4147552()1437 LocaleTest::Test4147552()
1438 {
1439     Locale locales [] = {     Locale("no", "NO"),
1440                             Locale("no", "NO", "B"),
1441                              Locale("no", "NO", "NY")
1442     };
1443 
1444     UnicodeString edn("Norwegian (Norway, B)");
1445     UnicodeString englishDisplayNames [] = {
1446                                                 "Norwegian (Norway)",
1447                                                  edn,
1448                                                  // "Norwegian (Norway,B)",
1449                                                  //"Norwegian (Norway,NY)"
1450                                                  "Norwegian (Norway, NY)"
1451     };
1452     UnicodeString ndn("norsk (Norge, B");
1453     UnicodeString norwegianDisplayNames [] = {
1454                                                 "norsk (Norge)",
1455                                                 "norsk (Norge, B)",
1456                                                 //ndn,
1457                                                  "norsk (Noreg, NY)"
1458                                                  //"Norsk (Noreg, Nynorsk)"
1459     };
1460     UErrorCode status = U_ZERO_ERROR;
1461 
1462     Locale saveLocale;
1463     Locale::setDefault(Locale::getEnglish(), status);
1464     for (int32_t i = 0; i < 3; ++i) {
1465         Locale loc = locales[i];
1466         UnicodeString temp;
1467         if (loc.getDisplayName(temp) != englishDisplayNames[i])
1468            dataerrln("English display-name mismatch: expected " +
1469                    englishDisplayNames[i] + ", got " + loc.getDisplayName(temp));
1470         if (loc.getDisplayName(loc, temp) != norwegianDisplayNames[i])
1471             dataerrln("Norwegian display-name mismatch: expected " +
1472                    norwegianDisplayNames[i] + ", got " +
1473                    loc.getDisplayName(loc, temp));
1474     }
1475     Locale::setDefault(saveLocale, status);
1476 }
1477 
1478 void
TestVariantParsing()1479 LocaleTest::TestVariantParsing()
1480 {
1481     Locale en_US_custom("en", "US", "De Anza_Cupertino_California_United States_Earth");
1482 
1483     UnicodeString dispName("English (United States, DE ANZA_CUPERTINO_CALIFORNIA_UNITED STATES_EARTH)");
1484     UnicodeString dispVar("DE ANZA_CUPERTINO_CALIFORNIA_UNITED STATES_EARTH");
1485 
1486     UnicodeString got;
1487 
1488     en_US_custom.getDisplayVariant(Locale::getUS(), got);
1489     if(got != dispVar) {
1490         errln("FAIL: getDisplayVariant()");
1491         errln("Wanted: " + dispVar);
1492         errln("Got   : " + got);
1493     }
1494 
1495     en_US_custom.getDisplayName(Locale::getUS(), got);
1496     if(got != dispName) {
1497         dataerrln("FAIL: getDisplayName()");
1498         dataerrln("Wanted: " + dispName);
1499         dataerrln("Got   : " + got);
1500     }
1501 
1502     Locale shortVariant("fr", "FR", "foo");
1503     shortVariant.getDisplayVariant(got);
1504 
1505     if(got != "FOO") {
1506         errln("FAIL: getDisplayVariant()");
1507         errln("Wanted: foo");
1508         errln("Got   : " + got);
1509     }
1510 
1511     Locale bogusVariant("fr", "FR", "_foo");
1512     bogusVariant.getDisplayVariant(got);
1513 
1514     if(got != "FOO") {
1515         errln("FAIL: getDisplayVariant()");
1516         errln("Wanted: foo");
1517         errln("Got   : " + got);
1518     }
1519 
1520     Locale bogusVariant2("fr", "FR", "foo_");
1521     bogusVariant2.getDisplayVariant(got);
1522 
1523     if(got != "FOO") {
1524         errln("FAIL: getDisplayVariant()");
1525         errln("Wanted: foo");
1526         errln("Got   : " + got);
1527     }
1528 
1529     Locale bogusVariant3("fr", "FR", "_foo_");
1530     bogusVariant3.getDisplayVariant(got);
1531 
1532     if(got != "FOO") {
1533         errln("FAIL: getDisplayVariant()");
1534         errln("Wanted: foo");
1535         errln("Got   : " + got);
1536     }
1537 }
1538 
1539 #if !UCONFIG_NO_FORMATTING
1540 
1541 /**
1542  * @bug 4105828
1543  * Currency symbol in zh is wrong.  We will test this at the NumberFormat
1544  * end to test the whole pipe.
1545  */
1546 void
Test4105828()1547 LocaleTest::Test4105828()
1548 {
1549     Locale LOC [] = { Locale::getChinese(),  Locale("zh", "CN", ""),
1550                      Locale("zh", "TW", ""), Locale("zh", "HK", "") };
1551     UErrorCode status = U_ZERO_ERROR;
1552     for (int32_t i = 0; i < 4; ++i) {
1553         NumberFormat *fmt = NumberFormat::createPercentInstance(LOC[i], status);
1554         if(U_FAILURE(status)) {
1555             dataerrln("Couldn't create NumberFormat - %s", u_errorName(status));
1556             return;
1557         }
1558         UnicodeString result;
1559         FieldPosition pos(0);
1560         fmt->format((int32_t)1, result, pos);
1561         UnicodeString temp;
1562         if(result != "100%") {
1563             errln(UnicodeString("Percent for ") + LOC[i].getDisplayName(temp) + " should be 100%, got " + result);
1564         }
1565         delete fmt;
1566     }
1567 }
1568 
1569 #endif
1570 
1571 // Tests setBogus and isBogus APIs for Locale
1572 // Jitterbug 1735
1573 void
TestSetIsBogus()1574 LocaleTest::TestSetIsBogus() {
1575     Locale l("en_US");
1576     l.setToBogus();
1577     if(l.isBogus() != TRUE) {
1578         errln("After setting bogus, didn't return TRUE");
1579     }
1580     l = "en_US"; // This should reset bogus
1581     if(l.isBogus() != FALSE) {
1582         errln("After resetting bogus, didn't return FALSE");
1583     }
1584 }
1585 
1586 
1587 void
TestKeywordVariants(void)1588 LocaleTest::TestKeywordVariants(void) {
1589     static const struct {
1590         const char *localeID;
1591         const char *expectedLocaleID;
1592         //const char *expectedLocaleIDNoKeywords;
1593         //const char *expectedCanonicalID;
1594         const char *expectedKeywords[10];
1595         int32_t numKeywords;
1596         UErrorCode expectedStatus;
1597     } testCases[] = {
1598         {
1599             "de_DE@  currency = euro; C o ll A t i o n   = Phonebook   ; C alen dar = buddhist   ",
1600             "de_DE@calendar=buddhist;collation=Phonebook;currency=euro",
1601             //"de_DE",
1602             //"de_DE@calendar=buddhist;collation=Phonebook;currency=euro",
1603             {"calendar", "collation", "currency"},
1604             3,
1605             U_ZERO_ERROR
1606         },
1607         {
1608             "de_DE@euro",
1609             "de_DE@euro",
1610             //"de_DE",
1611             //"de_DE@currency=EUR",
1612             {"","","","","","",""},
1613             0,
1614             U_INVALID_FORMAT_ERROR /* must have '=' after '@' */
1615         }
1616     };
1617     UErrorCode status = U_ZERO_ERROR;
1618 
1619     int32_t i = 0, j = 0;
1620     const char *result = NULL;
1621     StringEnumeration *keywords;
1622     int32_t keyCount = 0;
1623     const char *keyword = NULL;
1624     const UnicodeString *keywordString;
1625     int32_t keywordLen = 0;
1626 
1627     for(i = 0; i < (int32_t)(sizeof(testCases)/sizeof(testCases[0])); i++) {
1628         status = U_ZERO_ERROR;
1629         Locale l(testCases[i].localeID);
1630         keywords = l.createKeywords(status);
1631 
1632         if(status != testCases[i].expectedStatus) {
1633             err("Expected to get status %s. Got %s instead\n",
1634                 u_errorName(testCases[i].expectedStatus), u_errorName(status));
1635         }
1636         status = U_ZERO_ERROR;
1637         if(keywords) {
1638             if((keyCount = keywords->count(status)) != testCases[i].numKeywords) {
1639                 err("Expected to get %i keywords, got %i\n", testCases[i].numKeywords, keyCount);
1640             }
1641             if(keyCount) {
1642                 for(j = 0;;) {
1643                     if((j&1)==0) {
1644                         if((keyword = keywords->next(&keywordLen, status)) == NULL) {
1645                             break;
1646                         }
1647                         if(strcmp(keyword, testCases[i].expectedKeywords[j]) != 0) {
1648                             err("Expected to get keyword value %s, got %s\n", testCases[i].expectedKeywords[j], keyword);
1649                         }
1650                     } else {
1651                         if((keywordString = keywords->snext(status)) == NULL) {
1652                             break;
1653                         }
1654                         if(*keywordString != UnicodeString(testCases[i].expectedKeywords[j], "")) {
1655                             err("Expected to get keyword UnicodeString %s, got %s\n", testCases[i].expectedKeywords[j], keyword);
1656                         }
1657                     }
1658                     j++;
1659 
1660                     if(j == keyCount / 2) {
1661                         // replace keywords with a clone of itself
1662                         StringEnumeration *k2 = keywords->clone();
1663                         if(k2 == NULL || keyCount != k2->count(status)) {
1664                             errln("KeywordEnumeration.clone() failed");
1665                         } else {
1666                             delete keywords;
1667                             keywords = k2;
1668                         }
1669                     }
1670                 }
1671                 keywords->reset(status); // Make sure that reset works.
1672                 for(j = 0;;) {
1673                     if((keyword = keywords->next(&keywordLen, status)) == NULL) {
1674                         break;
1675                     }
1676                     if(strcmp(keyword, testCases[i].expectedKeywords[j]) != 0) {
1677                         err("Expected to get keyword value %s, got %s\n", testCases[i].expectedKeywords[j], keyword);
1678                     }
1679                     j++;
1680                 }
1681             }
1682             delete keywords;
1683         }
1684         result = l.getName();
1685         if(uprv_strcmp(testCases[i].expectedLocaleID, result) != 0) {
1686             err("Expected to get \"%s\" from \"%s\". Got \"%s\" instead\n",
1687                 testCases[i].expectedLocaleID, testCases[i].localeID, result);
1688         }
1689 
1690     }
1691 
1692 }
1693 
1694 void
TestKeywordVariantParsing(void)1695 LocaleTest::TestKeywordVariantParsing(void) {
1696     static const struct {
1697         const char *localeID;
1698         const char *keyword;
1699         const char *expectedValue;
1700     } testCases[] = {
1701         { "de_DE@  C o ll A t i o n   = Phonebook   ", "collation", "Phonebook" },
1702         { "de_DE", "collation", ""},
1703         { "de_DE@collation= PHONEBOOK", "collation", "PHONEBOOK" },
1704         { "de_DE@ currency = euro   ; CoLLaTion   = PHONEBOOk   ", "collation", "PHONEBOOk" },
1705     };
1706 
1707     UErrorCode status = U_ZERO_ERROR;
1708 
1709     int32_t i = 0;
1710     int32_t resultLen = 0;
1711     char buffer[256];
1712 
1713     for(i = 0; i < (int32_t)(sizeof(testCases)/sizeof(testCases[0])); i++) {
1714         *buffer = 0;
1715         Locale l(testCases[i].localeID);
1716         resultLen = l.getKeywordValue(testCases[i].keyword, buffer, 256, status);
1717         (void)resultLen;  // Suppress unused variable warning.
1718         if(uprv_strcmp(testCases[i].expectedValue, buffer) != 0) {
1719             err("Expected to extract \"%s\" from \"%s\" for keyword \"%s\". Got \"%s\" instead\n",
1720                 testCases[i].expectedValue, testCases[i].localeID, testCases[i].keyword, buffer);
1721         }
1722     }
1723 }
1724 
1725 void
TestSetKeywordValue(void)1726 LocaleTest::TestSetKeywordValue(void) {
1727     static const struct {
1728         const char *keyword;
1729         const char *value;
1730     } testCases[] = {
1731         { "collation", "phonebook" },
1732         { "currency", "euro" },
1733         { "calendar", "buddhist" }
1734     };
1735 
1736     UErrorCode status = U_ZERO_ERROR;
1737 
1738     int32_t i = 0;
1739     int32_t resultLen = 0;
1740     char buffer[256];
1741 
1742     Locale l(Locale::getGerman());
1743 
1744     for(i = 0; i < (int32_t)(sizeof(testCases)/sizeof(testCases[0])); i++) {
1745         l.setKeywordValue(testCases[i].keyword, testCases[i].value, status);
1746         if(U_FAILURE(status)) {
1747             err("FAIL: Locale::setKeywordValue failed - %s\n", u_errorName(status));
1748         }
1749 
1750         *buffer = 0;
1751         resultLen = l.getKeywordValue(testCases[i].keyword, buffer, 256, status);
1752         (void)resultLen;  // Suppress unused variable warning.
1753         if(uprv_strcmp(testCases[i].value, buffer) != 0) {
1754             err("Expected to extract \"%s\" for keyword \"%s\". Got \"%s\" instead\n",
1755                 testCases[i].value, testCases[i].keyword, buffer);
1756         }
1757     }
1758 }
1759 
1760 void
TestGetBaseName(void)1761 LocaleTest::TestGetBaseName(void) {
1762     static const struct {
1763         const char *localeID;
1764         const char *baseName;
1765     } testCases[] = {
1766         { "de_DE@  C o ll A t i o n   = Phonebook   ", "de_DE" },
1767         { "de@currency = euro; CoLLaTion   = PHONEBOOk", "de" },
1768         { "ja@calendar = buddhist", "ja" }
1769     };
1770 
1771     int32_t i = 0;
1772 
1773     for(i = 0; i < (int32_t)(sizeof(testCases)/sizeof(testCases[0])); i++) {
1774         Locale loc(testCases[i].localeID);
1775         if(strcmp(testCases[i].baseName, loc.getBaseName())) {
1776             errln("For locale \"%s\" expected baseName \"%s\", but got \"%s\"",
1777                 testCases[i].localeID, testCases[i].baseName, loc.getBaseName());
1778             return;
1779         }
1780     }
1781 }
1782 
1783 /**
1784  * Compare two locale IDs.  If they are equal, return 0.  If `string'
1785  * starts with `prefix' plus an additional element, that is, string ==
1786  * prefix + '_' + x, then return 1.  Otherwise return a value < 0.
1787  */
_loccmp(const char * string,const char * prefix)1788 static UBool _loccmp(const char* string, const char* prefix) {
1789     int32_t slen = (int32_t)strlen(string),
1790             plen = (int32_t)strlen(prefix);
1791     int32_t c = uprv_strncmp(string, prefix, plen);
1792     /* 'root' is "less than" everything */
1793     if (uprv_strcmp(prefix, "root") == 0) {
1794         return (uprv_strcmp(string, "root") == 0) ? 0 : 1;
1795     }
1796     if (c) return -1; /* mismatch */
1797     if (slen == plen) return 0;
1798     if (string[plen] == '_') return 1;
1799     return -2; /* false match, e.g. "en_USX" cmp "en_US" */
1800 }
1801 
1802 /**
1803  * Check the relationship between requested locales, and report problems.
1804  * The caller specifies the expected relationships between requested
1805  * and valid (expReqValid) and between valid and actual (expValidActual).
1806  * Possible values are:
1807  * "gt" strictly greater than, e.g., en_US > en
1808  * "ge" greater or equal,      e.g., en >= en
1809  * "eq" equal,                 e.g., en == en
1810  */
_checklocs(const char * label,const char * req,const Locale & validLoc,const Locale & actualLoc,const char * expReqValid,const char * expValidActual)1811 void LocaleTest::_checklocs(const char* label,
1812                             const char* req,
1813                             const Locale& validLoc,
1814                             const Locale& actualLoc,
1815                             const char* expReqValid,
1816                             const char* expValidActual) {
1817     const char* valid = validLoc.getName();
1818     const char* actual = actualLoc.getName();
1819     int32_t reqValid = _loccmp(req, valid);
1820     int32_t validActual = _loccmp(valid, actual);
1821     if (((0 == uprv_strcmp(expReqValid, "gt") && reqValid > 0) ||
1822          (0 == uprv_strcmp(expReqValid, "ge") && reqValid >= 0) ||
1823          (0 == uprv_strcmp(expReqValid, "eq") && reqValid == 0)) &&
1824         ((0 == uprv_strcmp(expValidActual, "gt") && validActual > 0) ||
1825          (0 == uprv_strcmp(expValidActual, "ge") && validActual >= 0) ||
1826          (0 == uprv_strcmp(expValidActual, "eq") && validActual == 0))) {
1827         logln("%s; req=%s, valid=%s, actual=%s",
1828               label, req, valid, actual);
1829     } else {
1830         dataerrln("FAIL: %s; req=%s, valid=%s, actual=%s.  Require (R %s V) and (V %s A)",
1831               label, req, valid, actual,
1832               expReqValid, expValidActual);
1833     }
1834 }
1835 
TestGetLocale(void)1836 void LocaleTest::TestGetLocale(void) {
1837 #if !UCONFIG_NO_SERVICE
1838     UErrorCode ec = U_ZERO_ERROR;
1839     const char *req;
1840     Locale valid, actual, reqLoc;
1841 
1842     // Calendar
1843 #if !UCONFIG_NO_FORMATTING
1844     req = "en_US_BROOKLYN";
1845     Calendar* cal = Calendar::createInstance(Locale::createFromName(req), ec);
1846     if (U_FAILURE(ec)) {
1847         dataerrln("FAIL: Calendar::createInstance failed - %s", u_errorName(ec));
1848     } else {
1849         valid = cal->getLocale(ULOC_VALID_LOCALE, ec);
1850         actual = cal->getLocale(ULOC_ACTUAL_LOCALE, ec);
1851         if (U_FAILURE(ec)) {
1852             errln("FAIL: Calendar::getLocale() failed");
1853         } else {
1854             _checklocs("Calendar", req, valid, actual);
1855         }
1856         /* Make sure that it fails correctly */
1857         ec = U_FILE_ACCESS_ERROR;
1858         if (cal->getLocale(ULOC_VALID_LOCALE, ec).getName()[0] != 0) {
1859             errln("FAIL: Calendar::getLocale() failed to fail correctly. It should have returned \"\"");
1860         }
1861         ec = U_ZERO_ERROR;
1862     }
1863     delete cal;
1864 #endif
1865 
1866     // DecimalFormat, DecimalFormatSymbols
1867 #if !UCONFIG_NO_FORMATTING
1868     req = "fr_FR_NICE";
1869     NumberFormat* nf = NumberFormat::createInstance(Locale::createFromName(req), ec);
1870     if (U_FAILURE(ec)) {
1871         dataerrln("FAIL: NumberFormat::createInstance failed - %s", u_errorName(ec));
1872     } else {
1873         DecimalFormat* dec = dynamic_cast<DecimalFormat*>(nf);
1874         if (dec == NULL) {
1875             errln("FAIL: NumberFormat::createInstance does not return a DecimalFormat");
1876             return;
1877         }
1878         valid = dec->getLocale(ULOC_VALID_LOCALE, ec);
1879         actual = dec->getLocale(ULOC_ACTUAL_LOCALE, ec);
1880         if (U_FAILURE(ec)) {
1881             errln("FAIL: DecimalFormat::getLocale() failed");
1882         } else {
1883             _checklocs("DecimalFormat", req, valid, actual);
1884         }
1885 
1886         const DecimalFormatSymbols* sym = dec->getDecimalFormatSymbols();
1887         if (sym == NULL) {
1888             errln("FAIL: getDecimalFormatSymbols returned NULL");
1889             return;
1890         }
1891         valid = sym->getLocale(ULOC_VALID_LOCALE, ec);
1892         actual = sym->getLocale(ULOC_ACTUAL_LOCALE, ec);
1893         if (U_FAILURE(ec)) {
1894             errln("FAIL: DecimalFormatSymbols::getLocale() failed");
1895         } else {
1896             _checklocs("DecimalFormatSymbols", req, valid, actual);
1897         }
1898     }
1899     delete nf;
1900 #endif
1901 
1902     // DateFormat, DateFormatSymbols
1903 #if !UCONFIG_NO_FORMATTING
1904     req = "de_CH_LUCERNE";
1905     DateFormat* df =
1906         DateFormat::createDateInstance(DateFormat::kDefault,
1907                                        Locale::createFromName(req));
1908     if (df == 0){
1909         dataerrln("Error calling DateFormat::createDateInstance()");
1910     } else {
1911         SimpleDateFormat* dat = dynamic_cast<SimpleDateFormat*>(df);
1912         if (dat == NULL) {
1913             errln("FAIL: DateFormat::createInstance does not return a SimpleDateFormat");
1914             return;
1915         }
1916         valid = dat->getLocale(ULOC_VALID_LOCALE, ec);
1917         actual = dat->getLocale(ULOC_ACTUAL_LOCALE, ec);
1918         if (U_FAILURE(ec)) {
1919             errln("FAIL: SimpleDateFormat::getLocale() failed");
1920         } else {
1921             _checklocs("SimpleDateFormat", req, valid, actual);
1922         }
1923 
1924         const DateFormatSymbols* sym = dat->getDateFormatSymbols();
1925         if (sym == NULL) {
1926             errln("FAIL: getDateFormatSymbols returned NULL");
1927             return;
1928         }
1929         valid = sym->getLocale(ULOC_VALID_LOCALE, ec);
1930         actual = sym->getLocale(ULOC_ACTUAL_LOCALE, ec);
1931         if (U_FAILURE(ec)) {
1932             errln("FAIL: DateFormatSymbols::getLocale() failed");
1933         } else {
1934             _checklocs("DateFormatSymbols", req, valid, actual);
1935         }
1936     }
1937     delete df;
1938 #endif
1939 
1940     // BreakIterator
1941 #if !UCONFIG_NO_BREAK_ITERATION
1942     req = "es_ES_BARCELONA";
1943     reqLoc = Locale::createFromName(req);
1944     BreakIterator* brk = BreakIterator::createWordInstance(reqLoc, ec);
1945     if (U_FAILURE(ec)) {
1946         dataerrln("FAIL: BreakIterator::createWordInstance failed - %s", u_errorName(ec));
1947     } else {
1948         valid = brk->getLocale(ULOC_VALID_LOCALE, ec);
1949         actual = brk->getLocale(ULOC_ACTUAL_LOCALE, ec);
1950         if (U_FAILURE(ec)) {
1951             errln("FAIL: BreakIterator::getLocale() failed");
1952         } else {
1953             _checklocs("BreakIterator", req, valid, actual);
1954         }
1955 
1956         // After registering something, the behavior should be different
1957         URegistryKey key = BreakIterator::registerInstance(brk, reqLoc, UBRK_WORD, ec);
1958         brk = 0; // registerInstance adopts
1959         if (U_FAILURE(ec)) {
1960             errln("FAIL: BreakIterator::registerInstance() failed");
1961         } else {
1962             brk = BreakIterator::createWordInstance(reqLoc, ec);
1963             if (U_FAILURE(ec)) {
1964                 errln("FAIL: BreakIterator::createWordInstance failed");
1965             } else {
1966                 valid = brk->getLocale(ULOC_VALID_LOCALE, ec);
1967                 actual = brk->getLocale(ULOC_ACTUAL_LOCALE, ec);
1968                 if (U_FAILURE(ec)) {
1969                     errln("FAIL: BreakIterator::getLocale() failed");
1970                 } else {
1971                     // N.B.: now expect valid==actual==req
1972                     _checklocs("BreakIterator(registered)",
1973                                req, valid, actual, "eq", "eq");
1974                 }
1975             }
1976             // No matter what, unregister
1977             BreakIterator::unregister(key, ec);
1978             if (U_FAILURE(ec)) {
1979                 errln("FAIL: BreakIterator::unregister() failed");
1980             }
1981             delete brk;
1982             brk = 0;
1983         }
1984 
1985         // After unregistering, should behave normally again
1986         brk = BreakIterator::createWordInstance(reqLoc, ec);
1987         if (U_FAILURE(ec)) {
1988             errln("FAIL: BreakIterator::createWordInstance failed");
1989         } else {
1990             valid = brk->getLocale(ULOC_VALID_LOCALE, ec);
1991             actual = brk->getLocale(ULOC_ACTUAL_LOCALE, ec);
1992             if (U_FAILURE(ec)) {
1993                 errln("FAIL: BreakIterator::getLocale() failed");
1994             } else {
1995                 _checklocs("BreakIterator(unregistered)", req, valid, actual);
1996             }
1997         }
1998     }
1999     delete brk;
2000 #endif
2001 
2002     // Collator
2003 #if !UCONFIG_NO_COLLATION
2004     req = "hi_IN_BHOPAL";
2005     reqLoc = Locale::createFromName(req);
2006     Collator* coll = Collator::createInstance(reqLoc, ec);
2007     if (U_FAILURE(ec)) {
2008         dataerrln("FAIL: Collator::createInstance failed - %s", u_errorName(ec));
2009     } else {
2010         valid = coll->getLocale(ULOC_VALID_LOCALE, ec);
2011         actual = coll->getLocale(ULOC_ACTUAL_LOCALE, ec);
2012         if (U_FAILURE(ec)) {
2013             errln("FAIL: Collator::getLocale() failed");
2014         } else {
2015             _checklocs("Collator", req, valid, actual);
2016         }
2017 
2018         // After registering something, the behavior should be different
2019         URegistryKey key = Collator::registerInstance(coll, reqLoc, ec);
2020         coll = 0; // registerInstance adopts
2021         if (U_FAILURE(ec)) {
2022             errln("FAIL: Collator::registerInstance() failed");
2023         } else {
2024             coll = Collator::createInstance(reqLoc, ec);
2025             if (U_FAILURE(ec)) {
2026                 errln("FAIL: Collator::createWordInstance failed");
2027             } else {
2028                 valid = coll->getLocale(ULOC_VALID_LOCALE, ec);
2029                 actual = coll->getLocale(ULOC_ACTUAL_LOCALE, ec);
2030                 if (U_FAILURE(ec)) {
2031                     errln("FAIL: Collator::getLocale() failed");
2032                 } else {
2033                     // N.B.: now expect valid==actual==req
2034                     _checklocs("Collator(registered)",
2035                                req, valid, actual, "eq", "eq");
2036                 }
2037             }
2038             // No matter what, unregister
2039             Collator::unregister(key, ec);
2040             if (U_FAILURE(ec)) {
2041                 errln("FAIL: Collator::unregister() failed");
2042             }
2043             delete coll;
2044             coll = 0;
2045         }
2046 
2047         // After unregistering, should behave normally again
2048         coll = Collator::createInstance(reqLoc, ec);
2049         if (U_FAILURE(ec)) {
2050             errln("FAIL: Collator::createInstance failed");
2051         } else {
2052             valid = coll->getLocale(ULOC_VALID_LOCALE, ec);
2053             actual = coll->getLocale(ULOC_ACTUAL_LOCALE, ec);
2054             if (U_FAILURE(ec)) {
2055                 errln("FAIL: Collator::getLocale() failed");
2056             } else {
2057                 _checklocs("Collator(unregistered)", req, valid, actual);
2058             }
2059         }
2060     }
2061     delete coll;
2062 #endif
2063 #endif
2064 }
2065 
TestVariantWithOutCountry(void)2066 void LocaleTest::TestVariantWithOutCountry(void) {
2067     Locale loc("en","","POSIX");
2068     if (0 != strcmp(loc.getVariant(), "POSIX")) {
2069         errln("FAIL: en__POSIX didn't get parsed correctly - name is %s - expected %s got %s", loc.getName(), "POSIX", loc.getVariant());
2070     }
2071     Locale loc2("en","","FOUR");
2072     if (0 != strcmp(loc2.getVariant(), "FOUR")) {
2073         errln("FAIL: en__FOUR didn't get parsed correctly - name is %s - expected %s got %s", loc2.getName(), "FOUR", loc2.getVariant());
2074     }
2075     Locale loc3("en","Latn","","FOUR");
2076     if (0 != strcmp(loc3.getVariant(), "FOUR")) {
2077         errln("FAIL: en_Latn__FOUR didn't get parsed correctly - name is %s - expected %s got %s", loc3.getName(), "FOUR", loc3.getVariant());
2078     }
2079     Locale loc4("","Latn","","FOUR");
2080     if (0 != strcmp(loc4.getVariant(), "FOUR")) {
2081         errln("FAIL: _Latn__FOUR didn't get parsed correctly - name is %s - expected %s got %s", loc4.getName(), "FOUR", loc4.getVariant());
2082     }
2083     Locale loc5("","Latn","US","FOUR");
2084     if (0 != strcmp(loc5.getVariant(), "FOUR")) {
2085         errln("FAIL: _Latn_US_FOUR didn't get parsed correctly - name is %s - expected %s got %s", loc5.getName(), "FOUR", loc5.getVariant());
2086     }
2087     Locale loc6("de-1901");
2088     if (0 != strcmp(loc6.getVariant(), "1901")) {
2089         errln("FAIL: de-1901 didn't get parsed correctly - name is %s - expected %s got %s", loc6.getName(), "1901", loc6.getVariant());
2090     }
2091 }
2092 
_canonicalize(int32_t selector,const char * localeID)2093 static Locale _canonicalize(int32_t selector, /* 0==createFromName, 1==createCanonical, 2==Locale ct */
2094                             const char* localeID) {
2095     switch (selector) {
2096     case 0:
2097         return Locale::createFromName(localeID);
2098     case 1:
2099         return Locale::createCanonical(localeID);
2100     case 2:
2101         return Locale(localeID);
2102     default:
2103         return Locale("");
2104     }
2105 }
2106 
TestCanonicalization(void)2107 void LocaleTest::TestCanonicalization(void)
2108 {
2109     static const struct {
2110         const char *localeID;    /* input */
2111         const char *getNameID;   /* expected getName() result */
2112         const char *canonicalID; /* expected canonicalize() result */
2113     } testCases[] = {
2114         { "", "", "en_US_POSIX" },
2115         { "C", "c", "en_US_POSIX" },
2116         { "POSIX", "posix", "en_US_POSIX" },
2117         { "ca_ES_PREEURO-with-extra-stuff-that really doesn't make any sense-unless-you're trying to increase code coverage",
2118           "ca_ES_PREEURO_WITH_EXTRA_STUFF_THAT REALLY DOESN'T MAKE ANY SENSE_UNLESS_YOU'RE TRYING TO INCREASE CODE COVERAGE",
2119           "ca_ES_PREEURO_WITH_EXTRA_STUFF_THAT REALLY DOESN'T MAKE ANY SENSE_UNLESS_YOU'RE TRYING TO INCREASE CODE COVERAGE"},
2120         { "ca_ES_PREEURO", "ca_ES_PREEURO", "ca_ES@currency=ESP" },
2121         { "de_AT_PREEURO", "de_AT_PREEURO", "de_AT@currency=ATS" },
2122         { "de_DE_PREEURO", "de_DE_PREEURO", "de_DE@currency=DEM" },
2123         { "de_LU_PREEURO", "de_LU_PREEURO", "de_LU@currency=LUF" },
2124         { "el_GR_PREEURO", "el_GR_PREEURO", "el_GR@currency=GRD" },
2125         { "en_BE_PREEURO", "en_BE_PREEURO", "en_BE@currency=BEF" },
2126         { "en_IE_PREEURO", "en_IE_PREEURO", "en_IE@currency=IEP" },
2127         { "es_ES_PREEURO", "es_ES_PREEURO", "es_ES@currency=ESP" },
2128         { "eu_ES_PREEURO", "eu_ES_PREEURO", "eu_ES@currency=ESP" },
2129         { "fi_FI_PREEURO", "fi_FI_PREEURO", "fi_FI@currency=FIM" },
2130         { "fr_BE_PREEURO", "fr_BE_PREEURO", "fr_BE@currency=BEF" },
2131         { "fr_FR_PREEURO", "fr_FR_PREEURO", "fr_FR@currency=FRF" },
2132         { "fr_LU_PREEURO", "fr_LU_PREEURO", "fr_LU@currency=LUF" },
2133         { "ga_IE_PREEURO", "ga_IE_PREEURO", "ga_IE@currency=IEP" },
2134         { "gl_ES_PREEURO", "gl_ES_PREEURO", "gl_ES@currency=ESP" },
2135         { "it_IT_PREEURO", "it_IT_PREEURO", "it_IT@currency=ITL" },
2136         { "nl_BE_PREEURO", "nl_BE_PREEURO", "nl_BE@currency=BEF" },
2137         { "nl_NL_PREEURO", "nl_NL_PREEURO", "nl_NL@currency=NLG" },
2138         { "pt_PT_PREEURO", "pt_PT_PREEURO", "pt_PT@currency=PTE" },
2139         { "de__PHONEBOOK", "de__PHONEBOOK", "de@collation=phonebook" },
2140         { "en_GB_EURO", "en_GB_EURO", "en_GB@currency=EUR" },
2141         { "en_GB@EURO", "en_GB@EURO", "en_GB@currency=EUR" }, /* POSIX ID */
2142         { "es__TRADITIONAL", "es__TRADITIONAL", "es@collation=traditional" },
2143         { "hi__DIRECT", "hi__DIRECT", "hi@collation=direct" },
2144         { "ja_JP_TRADITIONAL", "ja_JP_TRADITIONAL", "ja_JP@calendar=japanese" },
2145         { "th_TH_TRADITIONAL", "th_TH_TRADITIONAL", "th_TH@calendar=buddhist" },
2146         { "zh_TW_STROKE", "zh_TW_STROKE", "zh_TW@collation=stroke" },
2147         { "zh__PINYIN", "zh__PINYIN", "zh@collation=pinyin" },
2148         { "zh@collation=pinyin", "zh@collation=pinyin", "zh@collation=pinyin" },
2149         { "zh_CN@collation=pinyin", "zh_CN@collation=pinyin", "zh_CN@collation=pinyin" },
2150         { "zh_CN_CA@collation=pinyin", "zh_CN_CA@collation=pinyin", "zh_CN_CA@collation=pinyin" },
2151         { "en_US_POSIX", "en_US_POSIX", "en_US_POSIX" },
2152         { "hy_AM_REVISED", "hy_AM_REVISED", "hy_AM_REVISED" },
2153         { "no_NO_NY", "no_NO_NY", "no_NO_NY" /* not: "nn_NO" [alan ICU3.0] */ },
2154         { "no@ny", "no@ny", "no__NY" /* not: "nn" [alan ICU3.0] */ }, /* POSIX ID */
2155         { "no-no.utf32@B", "no_NO.utf32@B", "no_NO_B" /* not: "nb_NO_B" [alan ICU3.0] */ }, /* POSIX ID */
2156         { "qz-qz@Euro", "qz_QZ@Euro", "qz_QZ@currency=EUR" }, /* qz-qz uses private use iso codes */
2157         // NOTE: uloc_getName() works on en-BOONT, but Locale() parser considers it BOGUS
2158         // TODO: unify this behavior
2159         { "en-BOONT", "en__BOONT", "en__BOONT" }, /* registered name */
2160         { "de-1901", "de__1901", "de__1901" }, /* registered name */
2161         { "de-1906", "de__1906", "de__1906" }, /* registered name */
2162         { "sr-SP-Cyrl", "sr_SP_CYRL", "sr_Cyrl_RS" }, /* .NET name */
2163         { "sr-SP-Latn", "sr_SP_LATN", "sr_Latn_RS" }, /* .NET name */
2164         { "sr_YU_CYRILLIC", "sr_YU_CYRILLIC", "sr_Cyrl_RS" }, /* Linux name */
2165         { "uz-UZ-Cyrl", "uz_UZ_CYRL", "uz_Cyrl_UZ" }, /* .NET name */
2166         { "uz-UZ-Latn", "uz_UZ_LATN", "uz_Latn_UZ" }, /* .NET name */
2167         { "zh-CHS", "zh_CHS", "zh_Hans" }, /* .NET name */
2168         { "zh-CHT", "zh_CHT", "zh_Hant" }, /* .NET name This may change back to zh_Hant */
2169 
2170         /* posix behavior that used to be performed by getName */
2171         { "mr.utf8", "mr.utf8", "mr" },
2172         { "de-tv.koi8r", "de_TV.koi8r", "de_TV" },
2173         { "x-piglatin_ML.MBE", "x-piglatin_ML.MBE", "x-piglatin_ML" },
2174         { "i-cherokee_US.utf7", "i-cherokee_US.utf7", "i-cherokee_US" },
2175         { "x-filfli_MT_FILFLA.gb-18030", "x-filfli_MT_FILFLA.gb-18030", "x-filfli_MT_FILFLA" },
2176         { "no-no-ny.utf8@B", "no_NO_NY.utf8@B", "no_NO_NY_B" /* not: "nn_NO" [alan ICU3.0] */ }, /* @ ignored unless variant is empty */
2177 
2178         /* fleshing out canonicalization */
2179         /* trim space and sort keywords, ';' is separator so not present at end in canonical form */
2180         { "en_Hant_IL_VALLEY_GIRL@ currency = EUR; calendar = Japanese ;", "en_Hant_IL_VALLEY_GIRL@calendar=Japanese;currency=EUR", "en_Hant_IL_VALLEY_GIRL@calendar=Japanese;currency=EUR" },
2181         /* already-canonical ids are not changed */
2182         { "en_Hant_IL_VALLEY_GIRL@calendar=Japanese;currency=EUR", "en_Hant_IL_VALLEY_GIRL@calendar=Japanese;currency=EUR", "en_Hant_IL_VALLEY_GIRL@calendar=Japanese;currency=EUR" },
2183         /* PRE_EURO and EURO conversions don't affect other keywords */
2184         { "es_ES_PREEURO@CALendar=Japanese", "es_ES_PREEURO@calendar=Japanese", "es_ES@calendar=Japanese;currency=ESP" },
2185         { "es_ES_EURO@SHOUT=zipeedeedoodah", "es_ES_EURO@shout=zipeedeedoodah", "es_ES@currency=EUR;shout=zipeedeedoodah" },
2186         /* currency keyword overrides PRE_EURO and EURO currency */
2187         { "es_ES_PREEURO@currency=EUR", "es_ES_PREEURO@currency=EUR", "es_ES@currency=EUR" },
2188         { "es_ES_EURO@currency=ESP", "es_ES_EURO@currency=ESP", "es_ES@currency=ESP" },
2189         /* norwegian is just too weird, if we handle things in their full generality */
2190         { "no-Hant-GB_NY@currency=$$$", "no_Hant_GB_NY@currency=$$$", "no_Hant_GB_NY@currency=$$$" /* not: "nn_Hant_GB@currency=$$$" [alan ICU3.0] */ },
2191 
2192         /* test cases reflecting internal resource bundle usage */
2193         { "root@kw=foo", "root@kw=foo", "root@kw=foo" },
2194         { "@calendar=gregorian", "@calendar=gregorian", "@calendar=gregorian" },
2195         { "ja_JP@calendar=Japanese", "ja_JP@calendar=Japanese", "ja_JP@calendar=Japanese" }
2196     };
2197 
2198     static const char* label[] = { "createFromName", "createCanonical", "Locale" };
2199 
2200     int32_t i, j;
2201 
2202     for (i=0; i < (int)(sizeof(testCases)/sizeof(testCases[0])); i++) {
2203         for (j=0; j<3; ++j) {
2204             const char* expected = (j==1) ? testCases[i].canonicalID : testCases[i].getNameID;
2205             Locale loc = _canonicalize(j, testCases[i].localeID);
2206             const char* getName = loc.isBogus() ? "BOGUS" : loc.getName();
2207             if(uprv_strcmp(expected, getName) != 0) {
2208                 errln("FAIL: %s(%s).getName() => \"%s\", expected \"%s\"",
2209                       label[j], testCases[i].localeID, getName, expected);
2210             } else {
2211                 logln("Ok: %s(%s) => \"%s\"",
2212                       label[j], testCases[i].localeID, getName);
2213             }
2214         }
2215     }
2216 }
2217 
TestCurrencyByDate(void)2218 void LocaleTest::TestCurrencyByDate(void)
2219 {
2220 #if !UCONFIG_NO_FORMATTING
2221     UErrorCode status = U_ZERO_ERROR;
2222     UDate date = uprv_getUTCtime();
2223 	UChar TMP[4];
2224 	int32_t index = 0;
2225 	int32_t resLen = 0;
2226     UnicodeString tempStr, resultStr;
2227 
2228 	// Cycle through historical currencies
2229     date = (UDate)-630720000000.0; // pre 1961 - no currency defined
2230     index = ucurr_countCurrencies("eo_AM", date, &status);
2231     if (index != 0)
2232 	{
2233 		errcheckln(status, "FAIL: didn't return 0 for eo_AM - %s", u_errorName(status));
2234 	}
2235     resLen = ucurr_forLocaleAndDate("eo_AM", date, index, TMP, 4, &status);
2236     if (resLen != 0) {
2237 		errcheckln(status, "FAIL: eo_AM didn't return NULL - %s", u_errorName(status));
2238     }
2239     status = U_ZERO_ERROR;
2240 
2241     date = (UDate)0.0; // 1970 - one currency defined
2242     index = ucurr_countCurrencies("eo_AM", date, &status);
2243     if (index != 1)
2244 	{
2245 		errcheckln(status, "FAIL: didn't return 1 for eo_AM - %s", u_errorName(status));
2246 	}
2247     resLen = ucurr_forLocaleAndDate("eo_AM", date, index, TMP, 4, &status);
2248 	tempStr.setTo(TMP);
2249     resultStr.setTo("SUR");
2250     if (resultStr != tempStr) {
2251         errcheckln(status, "FAIL: didn't return SUR for eo_AM - %s", u_errorName(status));
2252     }
2253 
2254     date = (UDate)693792000000.0; // 1992 - one currency defined
2255 	index = ucurr_countCurrencies("eo_AM", date, &status);
2256     if (index != 1)
2257 	{
2258 		errcheckln(status, "FAIL: didn't return 1 for eo_AM - %s", u_errorName(status));
2259 	}
2260     resLen = ucurr_forLocaleAndDate("eo_AM", date, index, TMP, 4, &status);
2261 	tempStr.setTo(TMP);
2262     resultStr.setTo("RUR");
2263     if (resultStr != tempStr) {
2264         errcheckln(status, "FAIL: didn't return RUR for eo_AM - %s", u_errorName(status));
2265     }
2266 
2267 	date = (UDate)977616000000.0; // post 1993 - one currency defined
2268 	index = ucurr_countCurrencies("eo_AM", date, &status);
2269     if (index != 1)
2270 	{
2271 		errcheckln(status, "FAIL: didn't return 1 for eo_AM - %s", u_errorName(status));
2272 	}
2273     resLen = ucurr_forLocaleAndDate("eo_AM", date, index, TMP, 4, &status);
2274 	tempStr.setTo(TMP);
2275     resultStr.setTo("AMD");
2276     if (resultStr != tempStr) {
2277         errcheckln(status, "FAIL: didn't return AMD for eo_AM - %s", u_errorName(status));
2278     }
2279 
2280     // Locale AD has multiple currencies at once
2281 	date = (UDate)977616000000.0; // year 2001
2282 	index = ucurr_countCurrencies("eo_AD", date, &status);
2283     if (index != 4)
2284 	{
2285 		errcheckln(status, "FAIL: didn't return 4 for eo_AD - %s", u_errorName(status));
2286 	}
2287     resLen = ucurr_forLocaleAndDate("eo_AD", date, 1, TMP, 4, &status);
2288 	tempStr.setTo(TMP);
2289     resultStr.setTo("EUR");
2290     if (resultStr != tempStr) {
2291         errcheckln(status, "FAIL: didn't return EUR for eo_AD - %s", u_errorName(status));
2292     }
2293     resLen = ucurr_forLocaleAndDate("eo_AD", date, 2, TMP, 4, &status);
2294 	tempStr.setTo(TMP);
2295     resultStr.setTo("ESP");
2296     if (resultStr != tempStr) {
2297         errcheckln(status, "FAIL: didn't return ESP for eo_AD - %s", u_errorName(status));
2298     }
2299     resLen = ucurr_forLocaleAndDate("eo_AD", date, 3, TMP, 4, &status);
2300 	tempStr.setTo(TMP);
2301     resultStr.setTo("FRF");
2302     if (resultStr != tempStr) {
2303         errcheckln(status, "FAIL: didn't return FRF for eo_AD - %s", u_errorName(status));
2304     }
2305     resLen = ucurr_forLocaleAndDate("eo_AD", date, 4, TMP, 4, &status);
2306 	tempStr.setTo(TMP);
2307     resultStr.setTo("ADP");
2308     if (resultStr != tempStr) {
2309         errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status));
2310     }
2311 
2312 	date = (UDate)0.0; // year 1970
2313 	index = ucurr_countCurrencies("eo_AD", date, &status);
2314     if (index != 3)
2315 	{
2316 		errcheckln(status, "FAIL: didn't return 3 for eo_AD - %s", u_errorName(status));
2317 	}
2318     resLen = ucurr_forLocaleAndDate("eo_AD", date, 1, TMP, 4, &status);
2319 	tempStr.setTo(TMP);
2320     resultStr.setTo("ESP");
2321     if (resultStr != tempStr) {
2322         errcheckln(status, "FAIL: didn't return ESP for eo_AD - %s", u_errorName(status));
2323     }
2324     resLen = ucurr_forLocaleAndDate("eo_AD", date, 2, TMP, 4, &status);
2325 	tempStr.setTo(TMP);
2326     resultStr.setTo("FRF");
2327     if (resultStr != tempStr) {
2328         errcheckln(status, "FAIL: didn't return FRF for eo_AD - %s", u_errorName(status));
2329     }
2330     resLen = ucurr_forLocaleAndDate("eo_AD", date, 3, TMP, 4, &status);
2331 	tempStr.setTo(TMP);
2332     resultStr.setTo("ADP");
2333     if (resultStr != tempStr) {
2334         errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status));
2335     }
2336 
2337 	date = (UDate)-630720000000.0; // year 1950
2338 	index = ucurr_countCurrencies("eo_AD", date, &status);
2339     if (index != 2)
2340 	{
2341 		errcheckln(status, "FAIL: didn't return 2 for eo_AD - %s", u_errorName(status));
2342 	}
2343     resLen = ucurr_forLocaleAndDate("eo_AD", date, 1, TMP, 4, &status);
2344 	tempStr.setTo(TMP);
2345     resultStr.setTo("ESP");
2346     if (resultStr != tempStr) {
2347         errcheckln(status, "FAIL: didn't return ESP for eo_AD - %s", u_errorName(status));
2348     }
2349     resLen = ucurr_forLocaleAndDate("eo_AD", date, 2, TMP, 4, &status);
2350 	tempStr.setTo(TMP);
2351     resultStr.setTo("ADP");
2352     if (resultStr != tempStr) {
2353         errcheckln(status, "FAIL: didn't return ADP for eo_AD - %s", u_errorName(status));
2354     }
2355 
2356 	date = (UDate)-2207520000000.0; // year 1900
2357 	index = ucurr_countCurrencies("eo_AD", date, &status);
2358     if (index != 1)
2359 	{
2360 		errcheckln(status, "FAIL: didn't return 1 for eo_AD - %s", u_errorName(status));
2361 	}
2362     resLen = ucurr_forLocaleAndDate("eo_AD", date, 1, TMP, 4, &status);
2363 	tempStr.setTo(TMP);
2364     resultStr.setTo("ESP");
2365     if (resultStr != tempStr) {
2366         errcheckln(status, "FAIL: didn't return ESP for eo_AD - %s", u_errorName(status));
2367     }
2368 
2369 	// Locale UA has gap between years 1994 - 1996
2370 	date = (UDate)788400000000.0;
2371 	index = ucurr_countCurrencies("eo_UA", date, &status);
2372     if (index != 0)
2373 	{
2374 		errcheckln(status, "FAIL: didn't return 0 for eo_UA - %s", u_errorName(status));
2375 	}
2376     resLen = ucurr_forLocaleAndDate("eo_UA", date, index, TMP, 4, &status);
2377     if (resLen != 0) {
2378 		errcheckln(status, "FAIL: eo_UA didn't return NULL - %s", u_errorName(status));
2379     }
2380     status = U_ZERO_ERROR;
2381 
2382 	// Test index bounds
2383     resLen = ucurr_forLocaleAndDate("eo_UA", date, 100, TMP, 4, &status);
2384     if (resLen != 0) {
2385 		errcheckln(status, "FAIL: eo_UA didn't return NULL - %s", u_errorName(status));
2386     }
2387     status = U_ZERO_ERROR;
2388 
2389     resLen = ucurr_forLocaleAndDate("eo_UA", date, 0, TMP, 4, &status);
2390     if (resLen != 0) {
2391 		errcheckln(status, "FAIL: eo_UA didn't return NULL - %s", u_errorName(status));
2392     }
2393     status = U_ZERO_ERROR;
2394 
2395 	// Test for bogus locale
2396 	index = ucurr_countCurrencies("eo_QQ", date, &status);
2397     if (index != 0)
2398 	{
2399 		errcheckln(status, "FAIL: didn't return 0 for eo_QQ - %s", u_errorName(status));
2400 	}
2401     status = U_ZERO_ERROR;
2402     resLen = ucurr_forLocaleAndDate("eo_QQ", date, 1, TMP, 4, &status);
2403     if (resLen != 0) {
2404 		errcheckln(status, "FAIL: eo_QQ didn't return NULL - %s", u_errorName(status));
2405     }
2406     status = U_ZERO_ERROR;
2407     resLen = ucurr_forLocaleAndDate("eo_QQ", date, 0, TMP, 4, &status);
2408     if (resLen != 0) {
2409 		errcheckln(status, "FAIL: eo_QQ didn't return NULL - %s", u_errorName(status));
2410     }
2411     status = U_ZERO_ERROR;
2412 
2413     // Cycle through histrocial currencies
2414 	date = (UDate)977616000000.0; // 2001 - one currency
2415 	index = ucurr_countCurrencies("eo_AO", date, &status);
2416     if (index != 1)
2417 	{
2418 		errcheckln(status, "FAIL: didn't return 1 for eo_AO - %s", u_errorName(status));
2419 	}
2420     resLen = ucurr_forLocaleAndDate("eo_AO", date, 1, TMP, 4, &status);
2421 	tempStr.setTo(TMP);
2422     resultStr.setTo("AOA");
2423     if (resultStr != tempStr) {
2424         errcheckln(status, "FAIL: didn't return AOA for eo_AO - %s", u_errorName(status));
2425     }
2426 
2427 	date = (UDate)819936000000.0; // 1996 - 2 currencies
2428 	index = ucurr_countCurrencies("eo_AO", date, &status);
2429     if (index != 2)
2430 	{
2431 		errcheckln(status, "FAIL: didn't return 1 for eo_AO - %s", u_errorName(status));
2432 	}
2433     resLen = ucurr_forLocaleAndDate("eo_AO", date, 1, TMP, 4, &status);
2434 	tempStr.setTo(TMP);
2435     resultStr.setTo("AOR");
2436     if (resultStr != tempStr) {
2437         errcheckln(status, "FAIL: didn't return AOR for eo_AO - %s", u_errorName(status));
2438     }
2439     resLen = ucurr_forLocaleAndDate("eo_AO", date, 2, TMP, 4, &status);
2440 	tempStr.setTo(TMP);
2441     resultStr.setTo("AON");
2442     if (resultStr != tempStr) {
2443         errcheckln(status, "FAIL: didn't return AON for eo_AO - %s", u_errorName(status));
2444     }
2445 
2446 	date = (UDate)662256000000.0; // 1991 - 2 currencies
2447 	index = ucurr_countCurrencies("eo_AO", date, &status);
2448     if (index != 2)
2449 	{
2450 		errcheckln(status, "FAIL: didn't return 1 for eo_AO - %s", u_errorName(status));
2451 	}
2452     resLen = ucurr_forLocaleAndDate("eo_AO", date, 1, TMP, 4, &status);
2453 	tempStr.setTo(TMP);
2454     resultStr.setTo("AON");
2455     if (resultStr != tempStr) {
2456         errcheckln(status, "FAIL: didn't return AON for eo_AO - %s", u_errorName(status));
2457     }
2458     resLen = ucurr_forLocaleAndDate("eo_AO", date, 2, TMP, 4, &status);
2459 	tempStr.setTo(TMP);
2460     resultStr.setTo("AOK");
2461     if (resultStr != tempStr) {
2462         errcheckln(status, "FAIL: didn't return AOK for eo_AO - %s", u_errorName(status));
2463     }
2464 
2465 	date = (UDate)315360000000.0; // 1980 - one currency
2466 	index = ucurr_countCurrencies("eo_AO", date, &status);
2467     if (index != 1)
2468 	{
2469 		errcheckln(status, "FAIL: didn't return 1 for eo_AO - %s", u_errorName(status));
2470 	}
2471     resLen = ucurr_forLocaleAndDate("eo_AO", date, 1, TMP, 4, &status);
2472 	tempStr.setTo(TMP);
2473     resultStr.setTo("AOK");
2474     if (resultStr != tempStr) {
2475         errcheckln(status, "FAIL: didn't return AOK for eo_AO - %s", u_errorName(status));
2476     }
2477 
2478 	date = (UDate)0.0; // 1970 - no currencies
2479 	index = ucurr_countCurrencies("eo_AO", date, &status);
2480     if (index != 0)
2481 	{
2482 		errcheckln(status, "FAIL: didn't return 1 for eo_AO - %s", u_errorName(status));
2483 	}
2484     resLen = ucurr_forLocaleAndDate("eo_AO", date, 1, TMP, 4, &status);
2485     if (resLen != 0) {
2486 		errcheckln(status, "FAIL: eo_AO didn't return NULL - %s", u_errorName(status));
2487     }
2488     status = U_ZERO_ERROR;
2489 
2490     // Test with currency keyword override
2491 	date = (UDate)977616000000.0; // 2001 - two currencies
2492 	index = ucurr_countCurrencies("eo_DE@currency=DEM", date, &status);
2493     if (index != 2)
2494 	{
2495 		errcheckln(status, "FAIL: didn't return 2 for eo_DE@currency=DEM - %s", u_errorName(status));
2496 	}
2497     resLen = ucurr_forLocaleAndDate("eo_DE@currency=DEM", date, 1, TMP, 4, &status);
2498 	tempStr.setTo(TMP);
2499     resultStr.setTo("EUR");
2500     if (resultStr != tempStr) {
2501         errcheckln(status, "FAIL: didn't return EUR for eo_DE@currency=DEM - %s", u_errorName(status));
2502     }
2503     resLen = ucurr_forLocaleAndDate("eo_DE@currency=DEM", date, 2, TMP, 4, &status);
2504 	tempStr.setTo(TMP);
2505     resultStr.setTo("DEM");
2506     if (resultStr != tempStr) {
2507         errcheckln(status, "FAIL: didn't return DEM for eo_DE@currency=DEM - %s", u_errorName(status));
2508     }
2509 
2510     // Test Euro Support
2511 	status = U_ZERO_ERROR; // reset
2512     date = uprv_getUTCtime();
2513 
2514     UChar USD[4];
2515     ucurr_forLocaleAndDate("en_US", date, 1, USD, 4, &status);
2516 
2517 	UChar YEN[4];
2518     ucurr_forLocaleAndDate("ja_JP", date, 1, YEN, 4, &status);
2519 
2520     ucurr_forLocaleAndDate("en_US", date, 1, TMP, 4, &status);
2521     if (u_strcmp(USD, TMP) != 0) {
2522         errcheckln(status, "Fail: en_US didn't return USD - %s", u_errorName(status));
2523     }
2524     ucurr_forLocaleAndDate("en_US_PREEURO", date, 1, TMP, 4, &status);
2525     if (u_strcmp(USD, TMP) != 0) {
2526         errcheckln(status, "Fail: en_US_PREEURO didn't fallback to en_US - %s", u_errorName(status));
2527     }
2528     ucurr_forLocaleAndDate("en_US_Q", date, 1, TMP, 4, &status);
2529     if (u_strcmp(USD, TMP) != 0) {
2530         errcheckln(status, "Fail: en_US_Q didn't fallback to en_US - %s", u_errorName(status));
2531     }
2532     status = U_ZERO_ERROR; // reset
2533 #endif
2534 }
2535 
TestGetVariantWithKeywords(void)2536 void LocaleTest::TestGetVariantWithKeywords(void)
2537 {
2538   Locale l("en_US_VALLEY@foo=value");
2539   const char *variant = l.getVariant();
2540   logln(variant);
2541   test_assert(strcmp("VALLEY", variant) == 0);
2542 
2543   UErrorCode status = U_ZERO_ERROR;
2544   char buffer[50];
2545   int32_t len = l.getKeywordValue("foo", buffer, 50, status);
2546   buffer[len] = '\0';
2547   test_assert(strcmp("value", buffer) == 0);
2548 }
2549