void formatErrorMessage(UErrorCode &realStatus, const UnicodeString& pattern, const Locale& theLocale, UErrorCode inStatus0, /* statusString 1 */ const Locale &inCountry2, double currency3, // these numbers are the message arguments. UnicodeString &result) { if(U_FAILURE(realStatus)) return; // you messed up UnicodeString errString1(u_errorName(inStatus0)); UnicodeString countryName2; inCountry2.getDisplayCountry(theLocale,countryName2); Formattable myArgs[] = { Formattable((int32_t)inStatus0), // inStatus0 {0} Formattable(errString1), // statusString1 {1} Formattable(countryName2), // inCountry2 {2} Formattable(currency3)// currency3 {3,number,currency} }; MessageFormat *fmt = new MessageFormat("MessageFormat's API is broken!!!!!!!!!!!",realStatus); fmt->setLocale(theLocale); fmt->applyPattern(pattern, realStatus); if (U_FAILURE(realStatus)) { delete fmt; return; } FieldPosition ignore = 0; fmt->format(myArgs,4,result,ignore,realStatus); delete fmt; }
void TestMessageFormat::testStaticFormat() { UErrorCode err = U_ZERO_ERROR; Formattable arguments[] = { (int32_t)7, Formattable(UDate(8.71068e+011), Formattable::kIsDate), "a disturbance in the Force" }; UnicodeString result; result = MessageFormat::format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", arguments, 3, result, err); if (U_FAILURE(err)) { errln("TestMessageFormat::testStaticFormat #1"); logln(UnicodeString("TestMessageFormat::testStaticFormat failed test #1 with error code ")+(int32_t)err); return; } const UnicodeString expected( "At 12:20:00 PM on Aug 8, 1997, there was a disturbance in the Force on planet 7.", ""); if (result != expected) { errln("TestMessageFormat::testStaticFormat failed on test"); logln( UnicodeString(" Result: ") + result ); logln( UnicodeString(" Expected: ") + expected ); } }
/* When the default locale is tr, make sure that the pattern can still be parsed. */ void TestMessageFormat::TestTurkishCasing() { UErrorCode err = U_ZERO_ERROR; Locale saveDefaultLocale; Locale::setDefault( Locale("tr"), err ); Formattable arguments[] = { (int32_t)7, Formattable(UDate(8.71068e+011), Formattable::kIsDate), "a disturbance in the Force" }; UnicodeString result; result = MessageFormat::format( "At {1,TIME} on {1,DATE,SHORT}, there was {2} on planet {0,NUMBER,INTEGER}.", arguments, 3, result, err); if (U_FAILURE(err)) { errln("TestTurkishCasing #1 with error code %s", u_errorName(err)); return; } const UnicodeString expected( "At 12:20:00 on 08.08.1997, there was a disturbance in the Force on planet 7.", ""); if (result != expected) { errln("TestTurkishCasing failed on test"); errln( UnicodeString(" Result: ") + result ); errln( UnicodeString(" Expected: ") + expected ); } Locale::setDefault( saveDefaultLocale, err ); }
TimeUnitAmount::TimeUnitAmount(double amount, TimeUnit::UTimeUnitFields timeUnitField, UErrorCode& status) : Measure(Formattable(amount), TimeUnit::createInstance(timeUnitField, status), status) { }
UnicodeString& PluralFormat::format(double number, UnicodeString& appendTo, FieldPosition& pos, UErrorCode& status) const { return format(Formattable(number), (double)number, appendTo, pos, status); }
void TestMessageFormat::testFormat() { UErrorCode err = U_ZERO_ERROR; GregorianCalendar cal(err); const Formattable ftarray[] = { Formattable( UDate(8.71068e+011), Formattable::kIsDate ) }; const int32_t ft_cnt = sizeof(ftarray) / sizeof(Formattable); Formattable ft_arr( ftarray, ft_cnt ); Formattable* fmt = new Formattable(UDate(8.71068e+011), Formattable::kIsDate); UnicodeString result; //UnicodeString formatStr = "At {1,time} on {1,date}, you made a {2} of {0,number,currency}."; UnicodeString formatStr = "On {0,date}, it began."; UnicodeString compareStr = "On Aug 8, 1997, it began."; err = U_ZERO_ERROR; MessageFormat msg( formatStr, err); FieldPosition fp(0); result = ""; fp = 0; result = msg.format( *fmt, result, //FieldPosition(0), fp, err); if (err != U_ILLEGAL_ARGUMENT_ERROR) { errln("*** MSG format without expected error code."); } err = U_ZERO_ERROR; result = ""; fp = 0; result = msg.format( ft_arr, result, //FieldPosition(0), fp, err); logln("MSG format( Formattable&, ... ) expected:" + compareStr); logln("MSG format( Formattable&, ... ) result:" + result); if (result != compareStr) { errln("*** MSG format( Formattable&, .... ) err."); }else{ logln("MSG format( Formattable&, ... ) tested."); } delete fmt; }
void MessageFormatRegressionTest::Test4105380() { UnicodeString patternText1("The disk \"{1}\" contains {0}."); UnicodeString patternText2("There are {0} on the disk \"{1}\""); UErrorCode status = U_ZERO_ERROR; const UBool possibleDataError = TRUE; MessageFormat *form1 = new MessageFormat(patternText1, status); failure(status, "new MessageFormat"); MessageFormat *form2 = new MessageFormat(patternText2, status); failure(status, "new MessageFormat"); double filelimits [] = {0,1,2}; UnicodeString filepart [] = { (UnicodeString)"no files", (UnicodeString)"one file", (UnicodeString)"{0,number} files" }; ChoiceFormat *fileform = new ChoiceFormat(filelimits, filepart, 3); form1->setFormat(1, *fileform); form2->setFormat(0, *fileform); //Object[] testArgs = {new Long(12373), "MyDisk"}; Formattable testArgs [] = { Formattable((int32_t)12373), Formattable((UnicodeString)"MyDisk") }; FieldPosition bogus(FieldPosition::DONT_CARE); UnicodeString result; logln(form1->format(testArgs, 2, result, bogus, status)); failure(status, "form1->format", possibleDataError); result.remove(); logln(form2->format(testArgs, 2, result, bogus, status)); failure(status, "form1->format", possibleDataError); delete form1; delete form2; delete fileform; }
void MessageFormatRegressionTest::Test4118594() { UErrorCode status = U_ZERO_ERROR; const UBool possibleDataError = TRUE; MessageFormat *mf = new MessageFormat("{0}, {0}, {0}", status); failure(status, "new MessageFormat"); UnicodeString forParsing("x, y, z"); //Object[] objs = mf.parse(forParsing, new ParsePosition(0)); int32_t count = 0; ParsePosition pp(0); Formattable *objs = mf->parse(forParsing, pp, count); UnicodeString pat; logln("pattern: \"" + mf->toPattern(pat) + "\""); logln("text for parsing: \"" + forParsing + "\""); UnicodeString str; if (objs[0].getString(str) != "z") errln("argument0: \"" + objs[0].getString(str) + "\""); mf->applyPattern("{0,number,#.##}, {0,number,#.#}", status); failure(status, "mf->applyPattern", possibleDataError); //Object[] oldobjs = {new Double(3.1415)}; Formattable oldobjs [] = {Formattable(3.1415)}; UnicodeString result; FieldPosition pos(FieldPosition::DONT_CARE); result = mf->format( oldobjs, 1, result, pos, status ); failure(status, "mf->format", possibleDataError); pat.remove(); logln("pattern: \"" + mf->toPattern(pat) + "\""); logln("text for parsing: \"" + result + "\""); // result now equals "3.14, 3.1" if (result != "3.14, 3.1") dataerrln("result = " + result + " - " + u_errorName(status)); //Object[] newobjs = mf.parse(result, new ParsePosition(0)); int32_t count1 = 0; pp.setIndex(0); Formattable *newobjs = mf->parse(result, pp, count1); // newobjs now equals {new Double(3.1)} if (newobjs == NULL) { dataerrln("Error calling MessageFormat::parse"); } else { if (newobjs[0].getDouble() != 3.1) errln( UnicodeString("newobjs[0] = ") + newobjs[0].getDouble()); } delete [] objs; delete [] newobjs; delete mf; }
UnicodeString format(UnicodeString FormatString, UErrorCode &Status, Ts... Arguments) { UnicodeString Result; Formattable FmtArguments[] = { Formattable(Arguments)... }; Result = MessageFormat::format(FormatString, FmtArguments, sizeof...(Ts), Result, Status); return Result; }
void MessageFormatRegressionTest::Test4142938() { UnicodeString pat = CharsToUnicodeString("''Vous'' {0,choice,0#n''|1#}avez s\\u00E9lectionn\\u00E9 " "{0,choice,0#aucun|1#{0}} client{0,choice,0#s|1#|2#s} " "personnel{0,choice,0#s|1#|2#s}."); UErrorCode status = U_ZERO_ERROR; MessageFormat *mf = new MessageFormat(pat, status); failure(status, "new MessageFormat"); UnicodeString PREFIX [] = { CharsToUnicodeString("'Vous' n'avez s\\u00E9lectionn\\u00E9 aucun clients personnels."), CharsToUnicodeString("'Vous' avez s\\u00E9lectionn\\u00E9 "), CharsToUnicodeString("'Vous' avez s\\u00E9lectionn\\u00E9 ") }; UnicodeString SUFFIX [] = { UnicodeString(), UNICODE_STRING(" client personnel.", 18), UNICODE_STRING(" clients personnels.", 20) }; for (int i=0; i<3; i++) { UnicodeString out; //out = mf->format(new Object[]{new Integer(i)}); Formattable objs [] = { Formattable((int32_t)i) }; FieldPosition pos(FieldPosition::DONT_CARE); out = mf->format(objs, 1, out, pos, status); if (!failure(status, "mf->format", TRUE)) { if (SUFFIX[i] == "") { if (out != PREFIX[i]) errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\""); } else { if (!out.startsWith(PREFIX[i]) || !out.endsWith(SUFFIX[i])) errln((UnicodeString)"" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"...\"" + SUFFIX[i] + "\""); } } } delete mf; }
/* * This method updates the cache and must be called with a lock */ const UChar* TZGNCore::getGenericLocationName(const UnicodeString& tzCanonicalID) { U_ASSERT(!tzCanonicalID.isEmpty()); if (tzCanonicalID.length() > ZID_KEY_MAX) { return NULL; } UErrorCode status = U_ZERO_ERROR; UChar tzIDKey[ZID_KEY_MAX + 1]; int32_t tzIDKeyLen = tzCanonicalID.extract(tzIDKey, ZID_KEY_MAX + 1, status); U_ASSERT(status == U_ZERO_ERROR); // already checked length above tzIDKey[tzIDKeyLen] = 0; const UChar *locname = (const UChar *)uhash_get(fLocationNamesMap, tzIDKey); if (locname != NULL) { // gEmpty indicate the name is not available if (locname == gEmpty) { return NULL; } return locname; } // Construct location name UnicodeString name; UnicodeString usCountryCode; UBool isPrimary = FALSE; ZoneMeta::getCanonicalCountry(tzCanonicalID, usCountryCode, &isPrimary); if (!usCountryCode.isEmpty()) { FieldPosition fpos; if (isPrimary) { // If this is the primary zone in the country, use the country name. char countryCode[ULOC_COUNTRY_CAPACITY]; U_ASSERT(usCountryCode.length() < ULOC_COUNTRY_CAPACITY); int32_t ccLen = usCountryCode.extract(0, usCountryCode.length(), countryCode, sizeof(countryCode), US_INV); countryCode[ccLen] = 0; UnicodeString country; fLocaleDisplayNames->regionDisplayName(countryCode, country); Formattable param[] = { Formattable(country) }; fRegionFormat->format(param, 1, name, fpos, status); } else { // If this is not the primary zone in the country, // use the exemplar city name. // getExemplarLocationName should retur non-empty string // if the time zone is associated with a region UnicodeString city; fTimeZoneNames->getExemplarLocationName(tzCanonicalID, city); Formattable param[] = { Formattable(city), }; fRegionFormat->format(param, 1, name, fpos, status); } if (U_FAILURE(status)) { return NULL; } } locname = name.isEmpty() ? NULL : fStringPool.get(name, status); if (U_SUCCESS(status)) { // Cache the result const UChar* cacheID = ZoneMeta::findTimeZoneID(tzCanonicalID); U_ASSERT(cacheID != NULL); if (locname == NULL) { // gEmpty to indicate - no location name available uhash_put(fLocationNamesMap, (void *)cacheID, (void *)gEmpty, &status); } else { uhash_put(fLocationNamesMap, (void *)cacheID, (void *)locname, &status); if (U_FAILURE(status)) { locname = NULL; } else { // put the name info into the trie GNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(GNameInfo)); if (nameinfo != NULL) { nameinfo->type = UTZGNM_LOCATION; nameinfo->tzID = cacheID; fGNamesTrie.put(locname, nameinfo, status); } } } } return locname; }
UnicodeString PluralFormat::format(double number, UErrorCode& status) const { FieldPosition fpos(0); UnicodeString result; return format(Formattable(number), number, result, fpos, status); }
void MessageFormatRegressionTest::Test4031438() { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern1("Impossible {1} has occurred -- status code is {0} and message is {2}."); UnicodeString pattern2("Double '' Quotes {0} test and quoted '{1}' test plus 'other {2} stuff'."); MessageFormat *messageFormatter = new MessageFormat("", status); failure(status, "new MessageFormat"); const UBool possibleDataError = TRUE; //try { logln("Apply with pattern : " + pattern1); messageFormatter->applyPattern(pattern1, status); failure(status, "messageFormat->applyPattern"); //Object[] params = {new Integer(7)}; Formattable params []= { Formattable((int32_t)7) }; UnicodeString tempBuffer; FieldPosition pos(FieldPosition::DONT_CARE); tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status); if(tempBuffer != "Impossible {1} has occurred -- status code is 7 and message is {2}." || failure(status, "MessageFormat::format")) dataerrln("Tests arguments < substitution failed"); logln("Formatted with 7 : " + tempBuffer); ParsePosition pp(0); int32_t count = 0; Formattable *objs = messageFormatter->parse(tempBuffer, pp, count); //if(objs[7/*params.length*/] != NULL) // errln("Parse failed with more than expected arguments"); NumberFormat *fmt = 0; UnicodeString temp, temp1; for (int i = 0; i < count; i++) { // convert to string if not already Formattable obj = objs[i]; temp.remove(); if(obj.getType() == Formattable::kString) temp = obj.getString(temp); else { fmt = NumberFormat::createInstance(status); switch (obj.getType()) { case Formattable::kLong: fmt->format(obj.getLong(), temp); break; case Formattable::kInt64: fmt->format(obj.getInt64(), temp); break; case Formattable::kDouble: fmt->format(obj.getDouble(), temp); break; default: break; } } // convert to string if not already Formattable obj1 = params[i]; temp1.remove(); if(obj1.getType() == Formattable::kString) temp1 = obj1.getString(temp1); else { fmt = NumberFormat::createInstance(status); switch (obj1.getType()) { case Formattable::kLong: fmt->format(obj1.getLong(), temp1); break; case Formattable::kInt64: fmt->format(obj1.getInt64(), temp1); break; case Formattable::kDouble: fmt->format(obj1.getDouble(), temp1); break; default: break; } } //if (objs[i] != NULL && objs[i].getString(temp1) != params[i].getString(temp2)) { if (temp != temp1) { errln("Parse failed on object " + objs[i].getString(temp1) + " at index : " + i); } } delete fmt; delete [] objs; // {sfb} does this apply? no way to really pass a null Formattable, // only a null array /*tempBuffer = messageFormatter->format(null, tempBuffer, FieldPosition(FieldPosition::DONT_CARE), status); if (tempBuffer != "Impossible {1} has occurred -- status code is {0} and message is {2}." || failure(status, "messageFormat->format")) errln("Tests with no arguments failed"); logln("Formatted with null : " + tempBuffer);*/ logln("Apply with pattern : " + pattern2); messageFormatter->applyPattern(pattern2, status); failure(status, "messageFormatter->applyPattern", possibleDataError); tempBuffer.remove(); tempBuffer = messageFormatter->format(params, 1, tempBuffer, pos, status); if (tempBuffer != "Double ' Quotes 7 test and quoted {1} test plus other {2} stuff.") dataerrln("quote format test (w/ params) failed. - %s", u_errorName(status)); logln("Formatted with params : " + tempBuffer); /*tempBuffer = messageFormatter->format(null); if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff.")) errln("quote format test (w/ null) failed."); logln("Formatted with null : " + tempBuffer); logln("toPattern : " + messageFormatter.toPattern());*/ /*} catch (Exception foo) { errln("Exception when formatting in bug 4031438. "+foo.getMessage()); }*/ delete messageFormatter; }
void TestChoiceFormat::TestComplexExample( void ) { UErrorCode status = U_ZERO_ERROR; const double filelimits[] = {-1, 0,1,2}; const UnicodeString filepart[] = {"are corrupted files", "are no files","is one file","are {2} files"}; ChoiceFormat* fileform = new ChoiceFormat( filelimits, filepart, 4); if (!fileform) { it_errln("*** test_complex_example fileform"); return; } Format* filenumform = NumberFormat::createInstance( status ); if (!filenumform) { dataerrln((UnicodeString)"*** test_complex_example filenumform - " + u_errorName(status)); delete fileform; return; } if (!chkstatus( status, "*** test_simple_example filenumform" )) { delete fileform; delete filenumform; return; } //const Format* testFormats[] = { fileform, NULL, filenumform }; //pattform->setFormats( testFormats, 3 ); MessageFormat* pattform = new MessageFormat("There {0} on {1}", status ); if (!pattform) { it_errln("*** test_complex_example pattform"); delete fileform; delete filenumform; return; } if (!chkstatus( status, "*** test_complex_example pattform" )) { delete fileform; delete filenumform; delete pattform; return; } pattform->setFormat( 0, *fileform ); pattform->setFormat( 2, *filenumform ); Formattable testArgs[] = {(int32_t)0, "Disk_A", (int32_t)0}; UnicodeString str; UnicodeString res1, res2; pattform->toPattern( res1 ); it_logln("MessageFormat toPattern: " + res1); fileform->toPattern( res1 ); it_logln("ChoiceFormat toPattern: " + res1); if (res1 == "-1#are corrupted files|0#are no files|1#is one file|2#are {2} files") { it_logln("toPattern tested!"); }else{ it_errln("*** ChoiceFormat to Pattern result!"); } FieldPosition fpos(FieldPosition::DONT_CARE); UnicodeString checkstr[] = { "There are corrupted files on Disk_A", "There are no files on Disk_A", "There is one file on Disk_A", "There are 2 files on Disk_A", "There are 3 files on Disk_A" }; // if (status != U_ZERO_ERROR) return; // TODO: analyze why we have such a bad bail out here! if (U_FAILURE(status)) { delete fileform; delete filenumform; delete pattform; return; } int32_t i; int32_t start = -1; for (i = start; i < 4; ++i) { str = ""; status = U_ZERO_ERROR; testArgs[0] = Formattable((int32_t)i); testArgs[2] = testArgs[0]; res2 = pattform->format(testArgs, 3, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format" )) { delete fileform; delete filenumform; delete pattform; return; } it_logln(i + UnicodeString(" -> ") + res2); if (res2 != checkstr[i - start]) { it_errln("*** test_complex_example res string"); it_errln(UnicodeString("*** ") + i + UnicodeString(" -> '") + res2 + UnicodeString("' unlike '") + checkstr[i] + UnicodeString("' ! ")); } } it_logln(); it_logln("------ additional testing in complex test ------"); it_logln(); // #if 0 // ICU 4.8 deprecates and disables the ChoiceFormat getters. int32_t retCount; const double* retLimits = fileform->getLimits( retCount ); if ((retCount == 4) && (retLimits) && (retLimits[0] == -1.0) && (retLimits[1] == 0.0) && (retLimits[2] == 1.0) && (retLimits[3] == 2.0)) { it_logln("getLimits tested!"); }else{ it_errln("*** getLimits unexpected result!"); } const UnicodeString* retFormats = fileform->getFormats( retCount ); if ((retCount == 4) && (retFormats) && (retFormats[0] == "are corrupted files") && (retFormats[1] == "are no files") && (retFormats[2] == "is one file") && (retFormats[3] == "are {2} files")) { it_logln("getFormats tested!"); }else{ it_errln("*** getFormats unexpected result!"); } #endif UnicodeString checkstr2[] = { "There is no folder on Disk_A", "There is one folder on Disk_A", "There are many folders on Disk_A", "There are many folders on Disk_A" }; fileform->applyPattern("0#is no folder|1#is one folder|2#are many folders", status ); if (status == U_ZERO_ERROR) it_logln("status applyPattern OK!"); if (!chkstatus( status, "*** test_complex_example pattform" )) { delete fileform; delete filenumform; delete pattform; return; } pattform->setFormat( 0, *fileform ); fpos = 0; for (i = 0; i < 4; ++i) { str = ""; status = U_ZERO_ERROR; testArgs[0] = Formattable((int32_t)i); testArgs[2] = testArgs[0]; res2 = pattform->format(testArgs, 3, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format 2" )) { delete fileform; delete filenumform; delete pattform; return; } it_logln(UnicodeString() + i + UnicodeString(" -> ") + res2); if (res2 != checkstr2[i]) { it_errln("*** test_complex_example res string"); it_errln(UnicodeString("*** ") + i + UnicodeString(" -> '") + res2 + UnicodeString("' unlike '") + checkstr2[i] + UnicodeString("' ! ")); } } const double limits_A[] = {1,2,3,4,5,6,7}; const UnicodeString monthNames_A[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; ChoiceFormat* form_A = new ChoiceFormat(limits_A, monthNames_A, 7); ChoiceFormat* form_A2 = new ChoiceFormat(limits_A, monthNames_A, 7); const double limits_B[] = {1,2,3,4,5,6,7}; const UnicodeString monthNames_B[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat_BBB"}; ChoiceFormat* form_B = new ChoiceFormat(limits_B, monthNames_B, 7); if (!form_A || !form_B || !form_A2) { it_errln("*** test-choiceFormat not allocatable!"); }else{ if (*form_A == *form_A2) { it_logln("operator== tested."); }else{ it_errln("*** operator=="); } if (*form_A != *form_B) { it_logln("operator!= tested."); }else{ it_errln("*** operator!="); } ChoiceFormat* form_A3 = (ChoiceFormat*) form_A->clone(); if (!form_A3) { it_errln("*** ChoiceFormat->clone is nil."); }else{ if ((*form_A3 == *form_A) && (*form_A3 != *form_B)) { it_logln("method clone tested."); }else{ it_errln("*** ChoiceFormat clone or operator==, or operator!= ."); } } ChoiceFormat form_Assigned( *form_A ); UBool ok = (form_Assigned == *form_A) && (form_Assigned != *form_B); form_Assigned = *form_B; ok = ok && (form_Assigned != *form_A) && (form_Assigned == *form_B); if (ok) { it_logln("copy constructor and operator= tested."); }else{ it_errln("*** copy constructor or operator= or operator == or operator != ."); } delete form_A3; } delete form_A; delete form_A2; delete form_B; const char* testPattern = "0#none|1#one|2#many"; ChoiceFormat form_pat( testPattern, status ); if (!chkstatus( status, "*** ChoiceFormat contructor( newPattern, status)" )) { delete fileform; delete filenumform; delete pattform; return; } form_pat.toPattern( res1 ); if (res1 == "0#none|1#one|2#many") { it_logln("ChoiceFormat contructor( newPattern, status) tested"); }else{ it_errln("*** ChoiceFormat contructor( newPattern, status) or toPattern result!"); } double d_a2[] = { 3.0, 4.0 }; UnicodeString s_a2[] = { "third", "forth" }; form_pat.setChoices( d_a2, s_a2, 2 ); form_pat.toPattern( res1 ); it_logln(UnicodeString("ChoiceFormat adoptChoices toPattern: ") + res1); if (res1 == "3#third|4#forth") { it_logln("ChoiceFormat adoptChoices tested"); }else{ it_errln("*** ChoiceFormat adoptChoices result!"); } str = ""; fpos = 0; status = U_ZERO_ERROR; double arg_double = 3.0; res1 = form_pat.format( arg_double, str, fpos ); it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (double, ...) result!"); str = ""; fpos = 0; status = U_ZERO_ERROR; int64_t arg_64 = 3; res1 = form_pat.format( arg_64, str, fpos ); it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (int64_t, ...) result!"); str = ""; fpos = 0; status = U_ZERO_ERROR; int32_t arg_long = 3; res1 = form_pat.format( arg_long, str, fpos ); it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (int32_t, ...) result!"); Formattable ft( (int32_t)3 ); str = ""; fpos = 0; status = U_ZERO_ERROR; res1 = form_pat.format( ft, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format (int32_t, ...)" )) { delete fileform; delete filenumform; delete pattform; return; } it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (Formattable, ...) result!"); Formattable fta[] = { (int32_t)3 }; str = ""; fpos = 0; status = U_ZERO_ERROR; res1 = form_pat.format( fta, 1, str, fpos, status ); if (!chkstatus( status, "*** test_complex_example format (int32_t, ...)" )) { delete fileform; delete filenumform; delete pattform; return; } it_logln(UnicodeString("ChoiceFormat format:") + res1); if (res1 != "third") it_errln("*** ChoiceFormat format (Formattable[], cnt, ...) result!"); ParsePosition parse_pos = 0; Formattable result; UnicodeString parsetext("third"); form_pat.parse( parsetext, result, parse_pos ); double rd = (result.getType() == Formattable::kLong) ? result.getLong() : result.getDouble(); if (rd == 3.0) { it_logln("parse( ..., ParsePos ) tested."); }else{ it_errln("*** ChoiceFormat parse( ..., ParsePos )!"); } form_pat.parse( parsetext, result, status ); rd = (result.getType() == Formattable::kLong) ? result.getLong() : result.getDouble(); if (rd == 3.0) { it_logln("parse( ..., UErrorCode ) tested."); }else{ it_errln("*** ChoiceFormat parse( ..., UErrorCode )!"); } /* UClassID classID = ChoiceFormat::getStaticClassID(); if (classID == form_pat.getDynamicClassID()) { it_out << "getStaticClassID and getDynamicClassID tested." << endl; }else{ it_errln("*** getStaticClassID and getDynamicClassID!"); } */ it_logln(); delete fileform; delete filenumform; delete pattform; }
void test_Formattable( void ) { UErrorCode status = U_ZERO_ERROR; Formattable* ftp = new Formattable(); if (!ftp || !(ftp->getType() == Formattable::kLong) || !(ftp->getLong() == 0)) { it_errln("*** Formattable constructor or getType or getLong"); } delete ftp; Formattable fta, ftb; fta.setLong(1); ftb.setLong(2); if ((fta != ftb) || !(fta == ftb)) { it_logln("FT setLong, operator== and operator!= tested."); status = U_ZERO_ERROR; fta.getLong(&status); if ( status == U_INVALID_FORMAT_ERROR){ it_errln("*** FT getLong(UErrorCode* status) failed on real Long"); } else { it_logln("FT getLong(UErrorCode* status) tested."); } }else{ it_errln("*** Formattable setLong or operator== or !="); } fta = ftb; if ((fta == ftb) || !(fta != ftb)) { it_logln("FT operator= tested."); }else{ it_errln("*** FT operator= or operator== or operator!="); } fta.setDouble( 3.0 ); if ((fta.getType() == Formattable::kDouble) && (fta.getDouble() == 3.0)) { it_logln("FT set- and getDouble tested."); }else{ it_errln("*** FT set- or getDouble"); } fta.getDate(status = U_ZERO_ERROR); if (status != U_INVALID_FORMAT_ERROR){ it_errln("*** FT getDate with status should fail on non-Date"); } fta.setDate( 4.0 ); if ((fta.getType() == Formattable::kDate) && (fta.getDate() == 4.0)) { it_logln("FT set- and getDate tested."); status = U_ZERO_ERROR; fta.getDate(status); if ( status == U_INVALID_FORMAT_ERROR){ it_errln("*** FT getDate with status failed on real Date"); } else { it_logln("FT getDate with status tested."); } }else{ it_errln("*** FT set- or getDate"); } status = U_ZERO_ERROR; fta.getLong(&status); if (status != U_INVALID_FORMAT_ERROR){ it_errln("*** FT getLong(UErrorCode* status) should fail on non-Long"); } fta.setString("abc"); const Formattable ftc(fta); UnicodeString res; { UBool t; t = (fta.getType() == Formattable::kString) && (fta.getString(res) == "abc") && (fta.getString() == "abc"); res = fta.getString(status = U_ZERO_ERROR); t = t && (status != U_INVALID_FORMAT_ERROR && res == "abc"); res = ftc.getString(status = U_ZERO_ERROR); t = t && (status != U_INVALID_FORMAT_ERROR && res == "abc"); ftc.getString(res,status = U_ZERO_ERROR); t = t && (status != U_INVALID_FORMAT_ERROR && res == "abc"); if (t) { it_logln("FT set- and getString tested."); }else{ it_errln("*** FT set- or getString"); } } UnicodeString ucs = "unicode-string"; UnicodeString* ucs_ptr = new UnicodeString("pointed-to-unicode-string"); const Formattable ftarray[] = { Formattable( 1.0, Formattable::kIsDate ), 2.0, (int32_t)3, ucs, ucs_ptr }; const int32_t ft_cnt = UPRV_LENGTHOF(ftarray); Formattable ft_arr( ftarray, ft_cnt ); UnicodeString temp; if ((ft_arr[0].getType() == Formattable::kDate) && (ft_arr[0].getDate() == 1.0) && (ft_arr[1].getType() == Formattable::kDouble) && (ft_arr[1].getDouble() == 2.0) && (ft_arr[2].getType() == Formattable::kLong) && (ft_arr[2].getLong() == (int32_t)3) && (ft_arr[3].getType() == Formattable::kString) && (ft_arr[3].getString(temp) == ucs) && (ft_arr[4].getType() == Formattable::kString) && (ft_arr[4].getString(temp) == *ucs_ptr) ) { it_logln("FT constr. for date, double, long, ustring, ustring* and array tested"); }else{ it_errln("*** FT constr. for date, double, long, ustring, ustring* or array"); } int32_t i, res_cnt; const Formattable* res_array = ft_arr.getArray( res_cnt ); if (res_cnt == ft_cnt) { UBool same = TRUE; for (i = 0; i < res_cnt; i++ ) { if (res_array[i] != ftarray[i]) { same = FALSE; } } if (same) { it_logln("FT getArray tested"); res_array = ft_arr.getArray( res_cnt, status = U_ZERO_ERROR); if (status == U_INVALID_FORMAT_ERROR){ it_errln("*** FT getArray with status failed on real array"); } else { it_logln("FT getArray with status tested on real array"); } }else{ it_errln("*** FT getArray comparison"); } }else{ it_errln(UnicodeString("*** FT getArray count res_cnt=") + res_cnt + UnicodeString("ft_cnt=") + ft_cnt); } res_array = fta.getArray(res_cnt, status = U_ZERO_ERROR); if (status == U_INVALID_FORMAT_ERROR){ if (res_cnt == 0 && res_array == NULL){ it_logln("FT getArray with status tested on non array"); } else { it_errln("*** FT getArray with status return values are not consistent"); } } else { it_errln("*** FT getArray with status should fail on non-array"); } Formattable *pf; for(i = 0; i < ft_cnt; ++i) { pf = ftarray[i].clone(); if(pf == (ftarray + i) || *pf != ftarray[i]) { it_errln(UnicodeString("Formattable.clone() failed for item ") + i); } delete pf; } const Formattable ftarr1[] = { Formattable( (int32_t)1 ), Formattable( (int32_t)2 ) }; const Formattable ftarr2[] = { Formattable( (int32_t)3 ), Formattable( (int32_t)4 ) }; const int32_t ftarr1_cnt = (int32_t)(sizeof(ftarr1) / sizeof(Formattable)); const int32_t ftarr2_cnt = (int32_t)(sizeof(ftarr2) / sizeof(Formattable)); ft_arr.setArray( ftarr1, ftarr1_cnt ); if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == (int32_t)1)) { it_logln("FT setArray tested"); }else{ it_errln("*** FT setArray"); } Formattable* ft_dynarr = new Formattable[ftarr2_cnt]; for (i = 0; i < ftarr2_cnt; i++ ) { ft_dynarr[i] = ftarr2[i]; } if ((ft_dynarr[0].getType() == Formattable::kLong) && (ft_dynarr[0].getLong() == (int32_t)3) && (ft_dynarr[1].getType() == Formattable::kLong) && (ft_dynarr[1].getLong() == (int32_t)4)) { it_logln("FT operator= and array operations tested"); }else{ it_errln("*** FT operator= or array operations"); } ft_arr.adoptArray( ft_dynarr, ftarr2_cnt ); if ((ft_arr[0].getType() == Formattable::kLong) && (ft_arr[0].getLong() == (int32_t)3) && (ft_arr[1].getType() == Formattable::kLong) && (ft_arr[1].getLong() == (int32_t)4)) { it_logln("FT adoptArray tested"); }else{ it_errln("*** FT adoptArray or operator[]"); } ft_arr.setLong(0); // calls 'dispose' and deletes adopted array ! UnicodeString* ucs_dyn = new UnicodeString("ttt"); UnicodeString tmp2; fta.adoptString( ucs_dyn ); if ((fta.getType() == Formattable::kString) && (fta.getString(tmp2) == "ttt")) { it_logln("FT adoptString tested"); }else{ it_errln("*** FT adoptString or getString"); } fta.setLong(0); // calls 'dispose' and deletes adopted string ! it_logln(); }
void MessageFormatRegressionTest::Test4106661() { UErrorCode status = U_ZERO_ERROR; ChoiceFormat *fmt = new ChoiceFormat( "-1#are negative| 0#are no or fraction | 1#is one |1.0<is 1+ |2#are two |2<are more than 2.", status); failure(status, "new ChoiceFormat"); UnicodeString pat; logln("Formatter Pattern : " + fmt->toPattern(pat)); FieldPosition bogus(FieldPosition::DONT_CARE); UnicodeString str; // Will this work for -inf? logln("Format with -INF : " + fmt->format(Formattable(-uprv_getInfinity()), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 1.0 : " + fmt->format(Formattable(1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with NaN : " + fmt->format(Formattable(uprv_getNaN()), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with +INF : " + fmt->format(Formattable(uprv_getInfinity()), str, bogus, status)); failure(status, "fmt->format"); delete fmt; }
void TestMessageFormat::testSetLocale() { UErrorCode err = U_ZERO_ERROR; GregorianCalendar cal(err); Formattable arguments[] = { 456.83, Formattable(UDate(8.71068e+011), Formattable::kIsDate), "deposit" }; UnicodeString result; //UnicodeString formatStr = "At {1,time} on {1,date}, you made a {2} of {0,number,currency}."; UnicodeString formatStr = "At <time> on {1,date}, you made a {2} of {0,number,currency}."; // {sfb} to get $, would need Locale::US, not Locale::ENGLISH // Just use unlocalized currency symbol. //UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of $456.83."; UnicodeString compareStrEng = "At <time> on Aug 8, 1997, you made a deposit of "; compareStrEng += (UChar) 0x00a4; compareStrEng += "456.83."; // {sfb} to get DM, would need Locale::GERMANY, not Locale::GERMAN // Just use unlocalized currency symbol. //UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of 456,83 DM."; UnicodeString compareStrGer = "At <time> on 08.08.1997, you made a deposit of "; compareStrGer += "456,83 "; compareStrGer += (UChar) 0x00a4; compareStrGer += "."; MessageFormat msg( formatStr, err); result = ""; FieldPosition pos(0); result = msg.format( arguments, 3, result, pos, err); logln(result); if (result != compareStrEng) { errln("*** MSG format err."); } msg.setLocale(Locale::getEnglish()); UBool getLocale_ok = TRUE; if (msg.getLocale() != Locale::getEnglish()) { errln("*** MSG getLocal err."); getLocale_ok = FALSE; } msg.setLocale(Locale::getGerman()); if (msg.getLocale() != Locale::getGerman()) { errln("*** MSG getLocal err."); getLocale_ok = FALSE; } msg.applyPattern( formatStr, err); pos.setField(0); result = ""; result = msg.format( arguments, 3, result, pos, err); logln(result); if (result == compareStrGer) { logln("MSG setLocale tested."); }else{ errln( "*** MSG setLocale err."); } if (getLocale_ok) { logln("MSG getLocale tested."); } }
void MessageFormatRegressionTest::Test4094906() { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern("-"); pattern += (UChar) 0x221E; pattern += "<are negative|0<are no or fraction|1#is one|1<is 1+|"; pattern += (UChar) 0x221E; pattern += "<are many."; ChoiceFormat *fmt = new ChoiceFormat(pattern, status); failure(status, "new ChoiceFormat"); UnicodeString pat; if (fmt->toPattern(pat) != pattern) { errln( (UnicodeString) "Formatter Pattern : " + pat); errln( (UnicodeString) "Expected Pattern : " + pattern); } FieldPosition bogus(FieldPosition::DONT_CARE); UnicodeString str; // Will this work for -inf? logln("Format with -INF : " + fmt->format(Formattable(-uprv_getInfinity()), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with -1.0 : " + fmt->format(Formattable(-1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0 : " + fmt->format(Formattable((int32_t)0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 0.9 : " + fmt->format(Formattable(0.9), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 1.0 : " + fmt->format(Formattable(1.0), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 1.5 : " + fmt->format(Formattable(1.5), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2 : " + fmt->format(Formattable((int32_t)2), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with 2.1 : " + fmt->format(Formattable(2.1), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with NaN : " + fmt->format(Formattable(uprv_getNaN()), str, bogus, status)); failure(status, "fmt->format"); str.remove(); logln("Format with +INF : " + fmt->format(Formattable(uprv_getInfinity()), str, bogus, status)); failure(status, "fmt->format"); delete fmt; }
void MessageFormatRegressionTest::Test4074764() { UnicodeString pattern [] = { "Message without param", "Message with param:{0}", "Longer Message with param {0}" }; //difference between the two param strings are that //in the first one, the param position is within the //length of the string without param while it is not so //in the other case. UErrorCode status = U_ZERO_ERROR; MessageFormat *messageFormatter = new MessageFormat("", status); failure(status, "couldn't create MessageFormat"); //try { //Apply pattern with param and print the result messageFormatter->applyPattern(pattern[1], status); failure(status, "messageFormat->applyPattern"); //Object[] params = {new UnicodeString("BUG"), new Date()}; Formattable params [] = { Formattable(UnicodeString("BUG")), Formattable(0, Formattable::kIsDate) }; UnicodeString tempBuffer; FieldPosition pos(FieldPosition::DONT_CARE); tempBuffer = messageFormatter->format(params, 2, tempBuffer, pos, status); if( tempBuffer != "Message with param:BUG" || failure(status, "messageFormat->format")) errln("MessageFormat with one param test failed."); logln("Formatted with one extra param : " + tempBuffer); //Apply pattern without param and print the result messageFormatter->applyPattern(pattern[0], status); failure(status, "messageFormatter->applyPattern"); // {sfb} how much does this apply in C++? // do we want to verify that the Formattable* array is not NULL, // or is that the user's responsibility? // additionally, what should be the item count? // for bug testing purposes, assume that something was set to // NULL by mistake, and that the length should be non-zero //tempBuffer = messageFormatter->format(NULL, 1, tempBuffer, FieldPosition(FieldPosition::DONT_CARE), status); tempBuffer.remove(); tempBuffer = messageFormatter->format(NULL, 0, tempBuffer, pos, status); if( tempBuffer != "Message without param" || failure(status, "messageFormat->format")) errln("MessageFormat with no param test failed."); logln("Formatted with no params : " + tempBuffer); tempBuffer.remove(); tempBuffer = messageFormatter->format(params, 2, tempBuffer, pos, status); if (tempBuffer != "Message without param" || failure(status, "messageFormat->format")) errln("Formatted with arguments > subsitution failed. result = " + tempBuffer); logln("Formatted with extra params : " + tempBuffer); //This statement gives an exception while formatting... //If we use pattern[1] for the message with param, //we get an NullPointerException in MessageFormat.java(617) //If we use pattern[2] for the message with param, //we get an StringArrayIndexOutOfBoundsException in MessageFormat.java(614) //Both are due to maxOffset not being reset to -1 //in applyPattern() when the pattern does not //contain any param. /*} catch (Exception foo) { errln("Exception when formatting with no params."); }*/ delete messageFormatter; }
void TestMessageFormat::PatternTest() { Formattable testArgs[] = { Formattable(double(1)), Formattable(double(3456)), Formattable("Disk"), Formattable(UDate((int32_t)1000000000L), Formattable::kIsDate) }; UnicodeString testCases[] = { "Quotes '', '{', 'a' {0} '{0}'", "Quotes '', '{', 'a' {0,number} '{0}'", "'{'1,number,'#',##} {1,number,'#',##}", "There are {1} files on {2} at {3}.", "On {2}, there are {1} files, with {0,number,currency}.", "'{1,number,percent}', {1,number,percent},", "'{1,date,full}', {1,date,full},", "'{3,date,full}', {3,date,full},", "'{1,number,#,##}' {1,number,#,##}", }; UnicodeString testResultPatterns[] = { "Quotes '', '{', a {0} '{'0}", "Quotes '', '{', a {0,number} '{'0}", "'{'1,number,#,##} {1,number,'#'#,##}", "There are {1} files on {2} at {3}.", "On {2}, there are {1} files, with {0,number,currency}.", "'{'1,number,percent}, {1,number,percent},", "'{'1,date,full}, {1,date,full},", "'{'3,date,full}, {3,date,full},", "'{'1,number,#,##} {1,number,#,##}" }; UnicodeString testResultStrings[] = { "Quotes ', {, a 1 {0}", "Quotes ', {, a 1 {0}", "{1,number,#,##} #34,56", "There are 3,456 files on Disk at 1/12/70 5:46 AM.", "On Disk, there are 3,456 files, with $1.00.", "{1,number,percent}, 345,600%,", "{1,date,full}, Wednesday, December 31, 1969,", "{3,date,full}, Monday, January 12, 1970,", "{1,number,#,##} 34,56" }; for (int32_t i = 0; i < 9; ++i) { //it_out << "\nPat in: " << testCases[i]); MessageFormat *form = 0; UErrorCode success = U_ZERO_ERROR; UnicodeString buffer; form = new MessageFormat(testCases[i], Locale::getUS(), success); if (U_FAILURE(success)) { errln("MessageFormat creation failed.#1"); logln(((UnicodeString)"MessageFormat for ") + testCases[i] + " creation failed.\n"); continue; } if (form->toPattern(buffer) != testResultPatterns[i]) { errln(UnicodeString("TestMessageFormat::PatternTest failed test #2, i = ") + i); //form->toPattern(buffer); errln(((UnicodeString)" Orig: ") + testCases[i]); errln(((UnicodeString)" Exp: ") + testResultPatterns[i]); errln(((UnicodeString)" Got: ") + buffer); } //it_out << "Pat out: " << form->toPattern(buffer)); UnicodeString result; int32_t count = 4; FieldPosition fieldpos(0); form->format(testArgs, count, result, fieldpos, success); if (U_FAILURE(success)) { errln("MessageFormat failed test #3"); logln("TestMessageFormat::PatternTest failed test #3"); continue; } if (result != testResultStrings[i]) { errln("TestMessageFormat::PatternTest failed test #4"); logln("TestMessageFormat::PatternTest failed #4."); logln(UnicodeString(" Result: ") + result ); logln(UnicodeString(" Expected: ") + testResultStrings[i] ); } //it_out << "Result: " << result); #if 0 /* TODO: Look at this test and see if this is still a valid test */ logln("---------------- test parse ----------------"); form->toPattern(buffer); logln("MSG pattern for parse: " + buffer); int32_t parseCount = 0; Formattable* values = form->parse(result, parseCount, success); if (U_FAILURE(success)) { errln("MessageFormat failed test #5"); logln(UnicodeString("MessageFormat failed test #5 with error code ")+(int32_t)success); } else if (parseCount != count) { errln("MSG count not %d as expected. Got %d", count, parseCount); } UBool failed = FALSE; for (int32_t j = 0; j < parseCount; ++j) { if (values == 0 || testArgs[j] != values[j]) { errln(((UnicodeString)"MSG testargs[") + j + "]: " + toString(testArgs[j])); errln(((UnicodeString)"MSG values[") + j + "] : " + toString(values[j])); failed = TRUE; } } if (failed) errln("MessageFormat failed test #6"); #endif delete form; } }
/** * Verify that MessageFormat accomodates more than 10 arguments and * more than 10 subformats. */ void TestMessageFormat::TestUnlimitedArgsAndSubformats() { UErrorCode ec = U_ZERO_ERROR; const UnicodeString pattern = "On {0,date} (aka {0,date,short}, aka {0,date,long}) " "at {0,time} (aka {0,time,short}, aka {0,time,long}) " "there were {1,number} werjes " "(a {3,number,percent} increase over {2,number}) " "despite the {4}''s efforts " "and to delight of {5}, {6}, {7}, {8}, {9}, and {10} {11}."; MessageFormat msg(pattern, ec); if (U_FAILURE(ec)) { errln("FAIL: constructor failed"); return; } const Formattable ARGS[] = { Formattable(UDate(1e13), Formattable::kIsDate), Formattable((int32_t)1303), Formattable((int32_t)1202), Formattable(1303.0/1202 - 1), Formattable("Glimmung"), Formattable("the printers"), Formattable("Nick"), Formattable("his father"), Formattable("his mother"), Formattable("the spiddles"), Formattable("of course"), Formattable("Horace"), }; const int32_t ARGS_LENGTH = sizeof(ARGS) / sizeof(ARGS[0]); Formattable ARGS_OBJ(ARGS, ARGS_LENGTH); UnicodeString expected = "On Nov 20, 2286 (aka 11/20/86, aka November 20, 2286) " "at 9:46:40 AM (aka 9:46 AM, aka 9:46:40 AM PST) " "there were 1,303 werjes " "(a 8% increase over 1,202) " "despite the Glimmung's efforts " "and to delight of the printers, Nick, his father, " "his mother, the spiddles, and of course Horace."; UnicodeString result; msg.format(ARGS_OBJ, result, ec); if (result == expected) { logln(result); } else { errln((UnicodeString)"FAIL: Got " + result + ", expected " + expected); } }
/** * Test various generic API methods of SelectFormat for Basic API usage. * This is to make sure the API test coverage is 100% . */ void SelectFormatTest::selectFormatAPITest(/*char *par*/) { const UnicodeString SIMPLE_PATTERN(SIMPLE_PATTERN_STRING); /* Don't static init this! */ int numOfConstructors =3; UErrorCode status[3]; SelectFormat* selFmt[3] = { NULL, NULL, NULL }; // ========= Test constructors logln("SelectFormat API test: Testing SelectFormat constructors ..."); for (int32_t i=0; i< numOfConstructors; ++i) { status[i] = U_ZERO_ERROR; } selFmt[0]= new SelectFormat(SIMPLE_PATTERN, status[0]); if ( U_FAILURE(status[0]) ) { errln("ERROR: SelectFormat API test constructor with pattern and status failed! with %s\n", u_errorName(status[0])); return; } // =========== Test copy constructor logln("SelectFormat API test: Testing copy constructor and == operator ..."); SelectFormat fmt = *selFmt[0]; SelectFormat* dupPFmt = new SelectFormat(fmt); if ((*selFmt[0]) != (*dupPFmt)) { errln("ERROR: SelectFormat API test Failed in copy constructor or == operator!"); } delete dupPFmt; // ======= Test clone && == operator. logln("SelectFormat API test: Testing clone and == operator ..."); if ( U_SUCCESS(status[0]) ) { selFmt[1] = (SelectFormat*)selFmt[0]->clone(); if (selFmt[1]!=NULL) { if ( *selFmt[1] != *selFmt[0] ) { errln("ERROR: SelectFormat API test clone test failed!"); } } else { errln("ERROR: SelectFormat API test clone test failed with NULL!"); return; } } else { errln("ERROR: could not create [0]: %s\n", u_errorName(status[0])); return; } // ======= Test assignment operator && == operator. logln("SelectFormat API test: Testing assignment operator and == operator ..."); selFmt[2]= new SelectFormat(SIMPLE_PATTERN, status[2]); if ( U_SUCCESS(status[2]) ) { *selFmt[1] = *selFmt[2]; if (selFmt[1]!=NULL) { if ( (*selFmt[1] != *selFmt[2]) ) { errln("ERROR: SelectFormat API test assignment operator test failed!"); } } delete selFmt[1]; } else { errln("ERROR: SelectFormat constructor failed in assignment operator!"); } delete selFmt[0]; delete selFmt[2]; // ======= Test getStaticClassID() and getStaticClassID() logln("SelectFormat API test: Testing getStaticClassID() and getStaticClassID() ..."); UErrorCode status1 = U_ZERO_ERROR; SelectFormat* selFmt1 = new SelectFormat( SIMPLE_PATTERN , status1); if( U_FAILURE(status1)) { errln("ERROR: SelectFormat constructor failed in staticClassID test! Exitting"); return; } logln("Testing getStaticClassID()"); if(selFmt1->getDynamicClassID() !=SelectFormat::getStaticClassID()) { errln("ERROR: SelectFormat API test getDynamicClassID() didn't return the expected value"); } // ======= Test applyPattern() and toPattern() logln("SelectFormat API test: Testing applyPattern() and toPattern() ..."); UnicodeString pattern = UnicodeString("masculine{masculineVerbValue} other{otherVerbValue}"); status1 = U_ZERO_ERROR; selFmt1->applyPattern( pattern, status1); if (U_FAILURE(status1)) { errln("ERROR: SelectFormat API test failed in applyPattern() with pattern: "+ pattern); }else{ UnicodeString checkPattern; selFmt1->toPattern( checkPattern); if( checkPattern != pattern ){ errln("ERROR: SelectFormat API test failed in toPattern() with unexpected result with pattern: "+ pattern); } } // ======= Test different format() methods logln("SelectFormat API test: Testing format() with keyword method ..."); status1 = U_ZERO_ERROR; UnicodeString result; FieldPosition ignore(FieldPosition::DONT_CARE); UnicodeString keyWord = UnicodeString("masculine"); selFmt1->format( keyWord, result , ignore , status1); if (U_FAILURE(status1)) { errln("ERROR: SelectFormat API test failed in format() with keyWord: "+ keyWord); }else{ UnicodeString expected=UnicodeString("masculineVerbValue"); if( result != expected ){ errln("ERROR: SelectFormat API test failed in format() with unexpected result with keyWord: "+ keyWord); } } logln("SelectFormat API test: Testing format() with Formattable obj method ..."); status1 = U_ZERO_ERROR; result.remove(); UnicodeString result1; Formattable testArgs = Formattable("other"); selFmt1->format( testArgs, result1 , ignore , status1); if (U_FAILURE(status1)) { errln("ERROR: SelectFormat API test failed in format() with Formattable"); }else{ UnicodeString expected=UnicodeString("otherVerbValue"); if( result1 != expected ){ errln("ERROR: SelectFormat API test failed in format() with unexpected result with Formattable"); } } delete selFmt1; }
void NumberFormatRoundTripTest::test(NumberFormat *fmt, int32_t value) { test(fmt, Formattable(value)); }
void NumberFormatRoundTripTest::test(NumberFormat *fmt, double value) { test(fmt, Formattable(value)); }
void TimeUnitFormat::parseObject(const UnicodeString& source, Formattable& result, ParsePosition& pos) const { Formattable resultNumber(0.0); UBool withNumberFormat = false; TimeUnit::UTimeUnitFields resultTimeUnit = TimeUnit::UTIMEUNIT_FIELD_COUNT; int32_t oldPos = pos.getIndex(); int32_t newPos = -1; int32_t longestParseDistance = 0; UnicodeString* countOfLongestMatch = NULL; #ifdef TMUTFMT_DEBUG char res[1000]; source.extract(0, source.length(), res, "UTF-8"); std::cout << "parse source: " << res << "\n"; #endif // parse by iterating through all available patterns // and looking for the longest match. for (TimeUnit::UTimeUnitFields i = TimeUnit::UTIMEUNIT_YEAR; i < TimeUnit::UTIMEUNIT_FIELD_COUNT; i = (TimeUnit::UTimeUnitFields)(i+1)) { Hashtable* countToPatterns = fTimeUnitToCountToPatterns[i]; int32_t elemPos = UHASH_FIRST; const UHashElement* elem = NULL; while ((elem = countToPatterns->nextElement(elemPos)) != NULL){ const UHashTok keyTok = elem->key; UnicodeString* count = (UnicodeString*)keyTok.pointer; #ifdef TMUTFMT_DEBUG count->extract(0, count->length(), res, "UTF-8"); std::cout << "parse plural count: " << res << "\n"; #endif const UHashTok valueTok = elem->value; // the value is a pair of MessageFormat* MessageFormat** patterns = (MessageFormat**)valueTok.pointer; for (UTimeUnitFormatStyle style = UTMUTFMT_FULL_STYLE; style < UTMUTFMT_FORMAT_STYLE_COUNT; style = (UTimeUnitFormatStyle)(style + 1)) { MessageFormat* pattern = patterns[style]; pos.setErrorIndex(-1); pos.setIndex(oldPos); // see if we can parse Formattable parsed; pattern->parseObject(source, parsed, pos); if (pos.getErrorIndex() != -1 || pos.getIndex() == oldPos) { continue; } #ifdef TMUTFMT_DEBUG std::cout << "parsed.getType: " << parsed.getType() << "\n"; #endif Formattable tmpNumber(0.0); if (pattern->getArgTypeCount() != 0) { Formattable& temp = parsed[0]; if (temp.getType() == Formattable::kString) { UnicodeString tmpString; UErrorCode pStatus = U_ZERO_ERROR; getNumberFormat().parse(temp.getString(tmpString), tmpNumber, pStatus); if (U_FAILURE(pStatus)) { continue; } } else if (temp.isNumeric()) { tmpNumber = temp; } else { continue; } } int32_t parseDistance = pos.getIndex() - oldPos; if (parseDistance > longestParseDistance) { if (pattern->getArgTypeCount() != 0) { resultNumber = tmpNumber; withNumberFormat = true; } else { withNumberFormat = false; } resultTimeUnit = i; newPos = pos.getIndex(); longestParseDistance = parseDistance; countOfLongestMatch = count; } } } } /* After find the longest match, parse the number. * Result number could be null for the pattern without number pattern. * such as unit pattern in Arabic. * When result number is null, use plural rule to set the number. */ if (withNumberFormat == false && longestParseDistance != 0) { // set the number using plurrual count if (0 == countOfLongestMatch->compare(PLURAL_COUNT_ZERO, 4)) { resultNumber = Formattable(0.0); } else if (0 == countOfLongestMatch->compare(PLURAL_COUNT_ONE, 3)) { resultNumber = Formattable(1.0); } else if (0 == countOfLongestMatch->compare(PLURAL_COUNT_TWO, 3)) { resultNumber = Formattable(2.0); } else { // should not happen. // TODO: how to handle? resultNumber = Formattable(3.0); } } if (longestParseDistance == 0) { pos.setIndex(oldPos); pos.setErrorIndex(0); } else { UErrorCode status = U_ZERO_ERROR; TimeUnitAmount* tmutamt = new TimeUnitAmount(resultNumber, resultTimeUnit, status); if (U_SUCCESS(status)) { result.adoptObject(tmutamt); pos.setIndex(newPos); pos.setErrorIndex(-1); } else { pos.setIndex(oldPos); pos.setErrorIndex(0); } } }
CurrencyAmount::CurrencyAmount(double amount, const UChar* isoCode, UErrorCode& ec) : Measure(Formattable(amount), new CurrencyUnit(isoCode, ec), ec) { }
/* * This method updates the cache and must be called with a lock */ const UChar* TZGNCore::getPartialLocationName(const UnicodeString& tzCanonicalID, const UnicodeString& mzID, UBool isLong, const UnicodeString& mzDisplayName) { U_ASSERT(!tzCanonicalID.isEmpty()); U_ASSERT(!mzID.isEmpty()); U_ASSERT(!mzDisplayName.isEmpty()); PartialLocationKey key; key.tzID = ZoneMeta::findTimeZoneID(tzCanonicalID); key.mzID = ZoneMeta::findMetaZoneID(mzID); key.isLong = isLong; U_ASSERT(key.tzID != NULL && key.mzID != NULL); const UChar* uplname = (const UChar*)uhash_get(fPartialLocationNamesMap, (void *)&key); if (uplname != NULL) { return uplname; } UnicodeString location; UnicodeString usCountryCode; ZoneMeta::getCanonicalCountry(tzCanonicalID, usCountryCode); if (!usCountryCode.isEmpty()) { char countryCode[ULOC_COUNTRY_CAPACITY]; U_ASSERT(usCountryCode.length() < ULOC_COUNTRY_CAPACITY); int32_t ccLen = usCountryCode.extract(0, usCountryCode.length(), countryCode, sizeof(countryCode), US_INV); countryCode[ccLen] = 0; UnicodeString regionalGolden; fTimeZoneNames->getReferenceZoneID(mzID, countryCode, regionalGolden); if (tzCanonicalID == regionalGolden) { // Use country name fLocaleDisplayNames->regionDisplayName(countryCode, location); } else { // Otherwise, use exemplar city name fTimeZoneNames->getExemplarLocationName(tzCanonicalID, location); } } else { fTimeZoneNames->getExemplarLocationName(tzCanonicalID, location); if (location.isEmpty()) { // This could happen when the time zone is not associated with a country, // and its ID is not hierarchical, for example, CST6CDT. // We use the canonical ID itself as the location for this case. location.setTo(tzCanonicalID); } } UErrorCode status = U_ZERO_ERROR; UnicodeString name; FieldPosition fpos; Formattable param[] = { Formattable(location), Formattable(mzDisplayName) }; fFallbackFormat->format(param, 2, name, fpos, status); if (U_FAILURE(status)) { return NULL; } uplname = fStringPool.get(name, status); if (U_SUCCESS(status)) { // Add the name to cache PartialLocationKey* cacheKey = (PartialLocationKey *)uprv_malloc(sizeof(PartialLocationKey)); if (cacheKey != NULL) { cacheKey->tzID = key.tzID; cacheKey->mzID = key.mzID; cacheKey->isLong = key.isLong; uhash_put(fPartialLocationNamesMap, (void *)cacheKey, (void *)uplname, &status); if (U_FAILURE(status)) { uprv_free(cacheKey); } else { // put the name to the local trie as well GNameInfo *nameinfo = (ZNameInfo *)uprv_malloc(sizeof(GNameInfo)); if (nameinfo != NULL) { nameinfo->type = isLong ? UTZGNM_LONG : UTZGNM_SHORT; nameinfo->tzID = key.tzID; fGNamesTrie.put(uplname, nameinfo, status); } } } } return uplname; }