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