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