diff --git a/.gitattributes b/.gitattributes index 883f6102810..41a0c9ad4d9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -187,6 +187,7 @@ icu4j/main/tests/core/src/com/ibm/icu/dev/test/calendar/CalendarTestFmwk.java -t icu4j/main/tests/core/src/com/ibm/icu/dev/test/duration/LanguageTestFmwk.java -text icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DataDrivenNumberFormatTestUtility.java -text icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/NumberFormatTestData.java -text +icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/AbstractBreakIteratorTests.java -text icu4j/main/tests/core/src/com/ibm/icu/dev/test/serializable/CalendarHandler.java -text icu4j/main/tests/core/src/com/ibm/icu/dev/test/serializable/ExceptionHandler.java -text icu4j/main/tests/core/src/com/ibm/icu/dev/test/serializable/FormatHandler.java -text diff --git a/icu4j/main/classes/collate/src/com/ibm/icu/text/CollationElementIterator.java b/icu4j/main/classes/collate/src/com/ibm/icu/text/CollationElementIterator.java index 9822ced91ba..1940fe34230 100644 --- a/icu4j/main/classes/collate/src/com/ibm/icu/text/CollationElementIterator.java +++ b/icu4j/main/classes/collate/src/com/ibm/icu/text/CollationElementIterator.java @@ -584,37 +584,16 @@ public final class CollationElementIterator dir_ = 0; } - // Java porting note: This method is @stable ICU 2.0 in ICU4C, but not available - // in ICU4J. For now, keep it package local. - /** - * Gets the comparison order in the desired strength. Ignore the other - * differences. - * @param order The order value - */ - int strengthOrder(int order) { - int s = rbc_.settings.readOnly().getStrength(); - // Mask off the unwanted differences. - if (s == Collator.PRIMARY) { - order &= 0xffff0000; - } - else if (s == Collator.SECONDARY) { - order &= 0xffffff00; - } - - return order; - } - - private static final class MaxExpSink implements ContractionsAndExpansions.CESink { MaxExpSink(Map h) { maxExpansions = h; } - // Java 6: @Override + @Override public void handleCE(long ce) { } - // Java 6: @Override + @Override public void handleExpansion(long ces[], int start, int length) { if (length <= 1) { // We do not need to add single CEs into the map. @@ -694,6 +673,7 @@ public final class CollationElementIterator * CollationElementIterator * @stable ICU 2.8 */ + @Override public boolean equals(Object that) { if (that == this) { return true; @@ -715,6 +695,7 @@ public final class CollationElementIterator * @internal * @deprecated This API is ICU internal only. */ + @Override @Deprecated public int hashCode() { assert false : "hashCode not designed"; diff --git a/icu4j/main/classes/core/src/com/ibm/icu/impl/CurrencyData.java b/icu4j/main/classes/core/src/com/ibm/icu/impl/CurrencyData.java index 3ab318255d0..e39645ac495 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/impl/CurrencyData.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/impl/CurrencyData.java @@ -17,6 +17,8 @@ import com.ibm.icu.util.ULocale; public class CurrencyData { public static final CurrencyDisplayInfoProvider provider; + private CurrencyData() {} + public static interface CurrencyDisplayInfoProvider { CurrencyDisplayInfo getInstance(ULocale locale, boolean withFallback); boolean hasData(); diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/CompactDecimalDataCache.java b/icu4j/main/classes/core/src/com/ibm/icu/text/CompactDecimalDataCache.java index 7e2edec1fa2..8d302a559c9 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/text/CompactDecimalDataCache.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/text/CompactDecimalDataCache.java @@ -393,8 +393,11 @@ class CompactDecimalDataCache { /** - * Returns locale and style. Used to form useful messages in thrown - * exceptions. + * Returns locale and style. Used to form useful messages in thrown exceptions. + * + * Note: This is not covered by unit tests since no exceptions are thrown on the default CLDR data. It is too + * cumbersome to cover via reflection. + * * @param locale the locale * @param style the style */ diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/RBBIDataWrapper.java b/icu4j/main/classes/core/src/com/ibm/icu/text/RBBIDataWrapper.java index 82097c8905a..6147cd04a1d 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/text/RBBIDataWrapper.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/text/RBBIDataWrapper.java @@ -21,7 +21,7 @@ import com.ibm.icu.impl.Trie; /** *

Internal class used for Rule Based Break Iterators

*

This class provides access to the compiled break rule data, as -* it is stored in a .brk file. +* it is stored in a .brk file. */ final class RBBIDataWrapper { // @@ -44,6 +44,7 @@ final class RBBIDataWrapper { private static final class IsAcceptable implements Authenticate { // @Override when we switch to Java 6 + @Override public boolean isDataVersionAcceptable(byte version[]) { return version[0] == (FORMAT_VERSION >>> 24); } @@ -73,17 +74,17 @@ final class RBBIDataWrapper { final static int DH_RULESOURCELEN = 15; final static int DH_STATUSTABLE = 16; final static int DH_STATUSTABLELEN = 17; - - + + // Index offsets to the fields in a state table row. // Corresponds to struct RBBIStateTableRow in the C version. - // + // final static int ACCEPTING = 0; final static int LOOKAHEAD = 1; final static int TAGIDX = 2; final static int RESERVED = 3; final static int NEXTSTATES = 4; - + // Index offsets to header fields of a state table // struct RBBIStateTable {... in the C version. // @@ -97,37 +98,37 @@ final class RBBIDataWrapper { // enum RBBIStateTableFlags in the C version. // final static int RBBI_LOOKAHEAD_HARD_BREAK = 1; - final static int RBBI_BOF_REQUIRED = 2; - + final static int RBBI_BOF_REQUIRED = 2; + /** * Data Header. A struct-like class with the fields from the RBBI data file header. */ final static class RBBIDataHeader { - int fMagic; // == 0xbla0 - int fVersion; // == 1 (for ICU 3.2 and earlier. + int fMagic; // == 0xbla0 + int fVersion; // == 1 (for ICU 3.2 and earlier. byte[] fFormatVersion; // For ICU 3.4 and later. - int fLength; // Total length in bytes of this RBBI Data, - // including all sections, not just the header. - int fCatCount; // Number of character categories. + int fLength; // Total length in bytes of this RBBI Data, + // including all sections, not just the header. + int fCatCount; // Number of character categories. - // - // Offsets and sizes of each of the subsections within the RBBI data. - // All offsets are bytes from the start of the RBBIDataHeader. - // All sizes are in bytes. - // - int fFTable; // forward state transition table. + // + // Offsets and sizes of each of the subsections within the RBBI data. + // All offsets are bytes from the start of the RBBIDataHeader. + // All sizes are in bytes. + // + int fFTable; // forward state transition table. int fFTableLen; - int fRTable; // Offset to the reverse state transition table. + int fRTable; // Offset to the reverse state transition table. int fRTableLen; - int fSFTable; // safe point forward transition table + int fSFTable; // safe point forward transition table int fSFTableLen; - int fSRTable; // safe point reverse transition table + int fSRTable; // safe point reverse transition table int fSRTableLen; - int fTrie; // Offset to Trie data for character categories + int fTrie; // Offset to Trie data for character categories int fTrieLen; - int fRuleSource; // Offset to the source for for the break - int fRuleSourceLen; // rules. Stored UChar *. - int fStatusTable; // Offset to the table of rule status values + int fRuleSource; // Offset to the source for for the break + int fRuleSourceLen; // rules. Stored UChar *. + int fStatusTable; // Offset to the table of rule status values int fStatusTableLen; public RBBIDataHeader() { @@ -135,18 +136,19 @@ final class RBBIDataWrapper { fFormatVersion = new byte[4]; } } - - + + /** * RBBI State Table Indexing Function. Given a state number, return the * array index of the start of the state table row for that state. - * + * */ int getRowIndex(int state){ return ROW_DATA + state * (fHeader.fCatCount + 4); } - + static class TrieFoldingFunc implements Trie.DataManipulate { + @Override public int getFoldingOffset(int data) { if ((data & 0x8000) != 0) { return data & 0x7fff; @@ -156,8 +158,8 @@ final class RBBIDataWrapper { } } static TrieFoldingFunc fTrieFoldingFunc = new TrieFoldingFunc(); - - + + RBBIDataWrapper() { } @@ -317,7 +319,7 @@ final class RBBIDataWrapper { bytes, This.fHeader.fRuleSourceLen / 2, This.fHeader.fRuleSourceLen & 1); if (RuleBasedBreakIterator.fDebugEnv!=null && RuleBasedBreakIterator.fDebugEnv.indexOf("data")>=0) { - This.dump(); + This.dump(System.out); } return This; } @@ -341,35 +343,35 @@ final class RBBIDataWrapper { ///CLOVER:OFF /* Debug function to display the break iterator data. */ - void dump() { + void dump(java.io.PrintStream out) { if (fFTable.length == 0) { // There is no table. Fail early for testing purposes. throw new NullPointerException(); } - System.out.println("RBBI Data Wrapper dump ..."); - System.out.println(); - System.out.println("Forward State Table"); - dumpTable(fFTable); - System.out.println("Reverse State Table"); - dumpTable(fRTable); - System.out.println("Forward Safe Points Table"); - dumpTable(fSFTable); - System.out.println("Reverse Safe Points Table"); - dumpTable(fSRTable); - - dumpCharCategories(); - System.out.println("Source Rules: " + fRuleSource); - + out.println("RBBI Data Wrapper dump ..."); + out.println(); + out.println("Forward State Table"); + dumpTable(out, fFTable); + out.println("Reverse State Table"); + dumpTable(out, fRTable); + out.println("Forward Safe Points Table"); + dumpTable(out, fSFTable); + out.println("Reverse Safe Points Table"); + dumpTable(out, fSRTable); + + dumpCharCategories(out); + out.println("Source Rules: " + fRuleSource); + } ///CLOVER:ON ///CLOVER:OFF /* Fixed width int-to-string conversion. */ static public String intToString(int n, int width) { - StringBuilder dest = new StringBuilder(width); + StringBuilder dest = new StringBuilder(width); dest.append(n); while (dest.length() < width) { - dest.insert(0, ' '); + dest.insert(0, ' '); } return dest.toString(); } @@ -378,10 +380,10 @@ final class RBBIDataWrapper { ///CLOVER:OFF /* Fixed width int-to-string conversion. */ static public String intToHexString(int n, int width) { - StringBuilder dest = new StringBuilder(width); + StringBuilder dest = new StringBuilder(width); dest.append(Integer.toHexString(n)); while (dest.length() < width) { - dest.insert(0, ' '); + dest.insert(0, ' '); } return dest.toString(); } @@ -389,9 +391,9 @@ final class RBBIDataWrapper { ///CLOVER:OFF /** Dump a state table. (A full set of RBBI rules has 4 state tables.) */ - private void dumpTable(short table[]) { + private void dumpTable(java.io.PrintStream out, short table[]) { if (table == null) { - System.out.println(" -- null -- "); + out.println(" -- null -- "); } else { int n; int state; @@ -399,15 +401,15 @@ final class RBBIDataWrapper { for (n=0; n fHeader.fCatCount) { - System.out.println("Error, bad category " + Integer.toHexString(category) + - " for char " + Integer.toHexString(char32)); + out.println("Error, bad category " + Integer.toHexString(category) + + " for char " + Integer.toHexString(char32)); break; } if (category == lastCat ) { - rangeEnd = char32; + rangeEnd = char32; } else { if (lastCat >= 0) { if (catStrings[lastCat].length() > lastNewline[lastCat] + 70) { lastNewline[lastCat] = catStrings[lastCat].length() + 10; catStrings[lastCat] += "\n "; } - + catStrings[lastCat] += " " + Integer.toHexString(rangeStart); if (rangeEnd != rangeStart) { - catStrings[lastCat] += "-" + Integer.toHexString(rangeEnd); + catStrings[lastCat] += "-" + Integer.toHexString(rangeEnd); } } lastCat = category; @@ -486,13 +488,13 @@ final class RBBIDataWrapper { } catStrings[lastCat] += " " + Integer.toHexString(rangeStart); if (rangeEnd != rangeStart) { - catStrings[lastCat] += "-" + Integer.toHexString(rangeEnd); + catStrings[lastCat] += "-" + Integer.toHexString(rangeEnd); } - + for (category = 0; category <= fHeader.fCatCount; category ++) { - System.out.println (intToString(category, 5) + " " + catStrings[category]); + out.println (intToString(category, 5) + " " + catStrings[category]); } - System.out.println(); + out.println(); } ///CLOVER:ON @@ -510,9 +512,9 @@ final class RBBIDataWrapper { s = args[0]; } System.out.println("RBBIDataWrapper.main(" + s + ") "); - + String versionedName = ICUResourceBundle.ICU_BUNDLE+"/"+ s + ".brk"; - + try { RBBIDataWrapper This = RBBIDataWrapper.get(versionedName); This.dump(); @@ -520,6 +522,6 @@ final class RBBIDataWrapper { catch (Exception e) { System.out.println("Exception: " + e.toString()); } - + }*/ } diff --git a/icu4j/main/classes/core/src/com/ibm/icu/text/RuleBasedBreakIterator.java b/icu4j/main/classes/core/src/com/ibm/icu/text/RuleBasedBreakIterator.java index c2c247d2726..51f17bd99e5 100644 --- a/icu4j/main/classes/core/src/com/ibm/icu/text/RuleBasedBreakIterator.java +++ b/icu4j/main/classes/core/src/com/ibm/icu/text/RuleBasedBreakIterator.java @@ -127,6 +127,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * behavior as this one. * @stable ICU 2.0 */ + @Override public Object clone() { RuleBasedBreakIterator result = (RuleBasedBreakIterator)super.clone(); @@ -141,6 +142,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * rules, and iterate over the same text. * @stable ICU 2.0 */ + @Override public boolean equals(Object that) { if (that == null) { return false; @@ -175,6 +177,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * (In ICU4C, the same function is RuleBasedBreakIterator::getRules()) * @stable ICU 2.0 */ + @Override public String toString() { String retStr = ""; if (fRData != null) { @@ -188,6 +191,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return A hash code * @stable ICU 2.0 */ + @Override public int hashCode() { return fRData.fRuleSource.hashCode(); @@ -294,8 +298,11 @@ public class RuleBasedBreakIterator extends BreakIterator { * @deprecated This API is ICU internal only. */ @Deprecated - public void dump() { - this.fRData.dump(); + public void dump(java.io.PrintStream out) { + if (out == null) { + out = System.out; + } + this.fRData.dump(out); } /** @@ -327,6 +334,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The offset of the beginning of the text. * @stable ICU 2.0 */ + @Override public int first() { fCachedBreakPositions = null; fDictionaryCharCount = 0; @@ -346,6 +354,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The text's past-the-end offset. * @stable ICU 2.0 */ + @Override public int last() { fCachedBreakPositions = null; fDictionaryCharCount = 0; @@ -377,6 +386,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * the current one. * @stable ICU 2.0 */ + @Override public int next(int n) { int result = current(); while (n > 0) { @@ -395,6 +405,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The position of the first boundary after this one. * @stable ICU 2.0 */ + @Override public int next() { // if we have cached break positions and we're still in the range // covered by them, just move one step forward in the cache @@ -584,6 +595,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The position of the last boundary position preceding this one. * @stable ICU 2.0 */ + @Override public int previous() { int result; int startPos; @@ -682,6 +694,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The position of the first break after the current position. * @stable ICU 2.0 */ + @Override public int following(int offset) { CharacterIterator text = getText(); @@ -796,6 +809,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The position of the last boundary before the starting position. * @stable ICU 2.0 */ + @Override public int preceding(int offset) { CharacterIterator text = getText(); @@ -905,6 +919,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return True if "offset" is a boundary position. * @stable ICU 2.0 */ + @Override public boolean isBoundary(int offset) { checkOffset(offset, fText); @@ -938,6 +953,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return The current iteration position. * @stable ICU 2.0 */ + @Override public int current() { return (fText != null) ? fText.getIndex() : BreakIterator.DONE; } @@ -988,6 +1004,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @provisional This is a draft API and might change in a future release of ICU. */ + @Override public int getRuleStatus() { makeRuleStatusValid(); // Status records have this form: @@ -1025,6 +1042,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @draft ICU 3.0 (retain) * @provisional This is a draft API and might change in a future release of ICU. */ + @Override public int getRuleStatusVec(int[] fillInArray) { makeRuleStatusValid(); int numStatusVals = fRData.fStatusTable[fLastRuleStatusIndex]; @@ -1045,6 +1063,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @return An iterator over the text being analyzed. * @stable ICU 2.0 */ + @Override public CharacterIterator getText() { return fText; } @@ -1055,6 +1074,7 @@ public class RuleBasedBreakIterator extends BreakIterator { * @param newText An iterator over the text to analyze. * @stable ICU 2.0 */ + @Override public void setText(CharacterIterator newText) { fText = newText; // first() resets the caches @@ -1308,7 +1328,7 @@ public class RuleBasedBreakIterator extends BreakIterator { // Advance to the next character. // If this is a beginning-of-input loop iteration, don't advance. // The next iteration will be processing the first real input character. - c = (int)text.next(); + c = text.next(); if (c >= UTF16.LEAD_SURROGATE_MIN_VALUE) { c = nextTrail32(text, c); } diff --git a/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/AlphabeticIndexTest.java b/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/AlphabeticIndexTest.java index bdd2f0f4a01..06bd1ccfcdb 100644 --- a/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/AlphabeticIndexTest.java +++ b/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/AlphabeticIndexTest.java @@ -45,17 +45,17 @@ import com.ibm.icu.util.ULocale; */ public class AlphabeticIndexTest extends TestFmwk { /** - * + * */ private static final String ARROW = "\u2192"; private static final boolean DEBUG = ICUDebug.enabled("alphabeticindex"); public static Set KEY_LOCALES = new LinkedHashSet(Arrays.asList( - "en", "es", "de", "fr", "ja", "it", "tr", "pt", "zh", "nl", - "pl", "ar", "ru", "zh_Hant", "ko", "th", "sv", "fi", "da", - "he", "nb", "el", "hr", "bg", "sk", "lt", "vi", "lv", "sr", - "pt_PT", "ro", "hu", "cs", "id", "sl", "fil", "fa", "uk", - "ca", "hi", "et", "eu", "is", "sw", "ms", "bn", "am", "ta", + "en", "es", "de", "fr", "ja", "it", "tr", "pt", "zh", "nl", + "pl", "ar", "ru", "zh_Hant", "ko", "th", "sv", "fi", "da", + "he", "nb", "el", "hr", "bg", "sk", "lt", "vi", "lv", "sr", + "pt_PT", "ro", "hu", "cs", "id", "sl", "fil", "fa", "uk", + "ca", "hi", "et", "eu", "is", "sw", "ms", "bn", "am", "ta", "te", "mr", "ur", "ml", "kn", "gu", "or")); private String[][] localeAndIndexCharactersLists = new String[][] { /* Arabic*/ {"ar", "\u0627:\u0628:\u062A:\u062B:\u062C:\u062D:\u062E:\u062F:\u0630:\u0631:\u0632:\u0633:\u0634:\u0635:\u0636:\u0637:\u0638:\u0639:\u063A:\u0641:\u0642:\u0643:\u0644:\u0645:\u0646:\u0647:\u0648:\u064A"}, @@ -165,7 +165,7 @@ public class AlphabeticIndexTest extends TestFmwk { // /* Yoruba*/ {"yo", "A:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z"}, }; - + // public void TestAAKeyword() { // ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance( // ICUResourceBundle.ICU_COLLATION_BASE_NAME, "zh"); @@ -197,7 +197,7 @@ public class AlphabeticIndexTest extends TestFmwk { // int comp = foo.compare("a", "ā"); // assertEquals("should fall back to default for zh", -1, comp); // } -// +// // /** // * @param rb // * @param i @@ -210,12 +210,12 @@ public class AlphabeticIndexTest extends TestFmwk { // } // } - + @Test public void TestA() { String[][] tests = {{"zh_Hant", "渡辺", "12劃"}, {"zh", "渡辺", "D"} - /*, "zh@collation=unihan", "ja@collation=unihan", "ko@collation=unihan"*/ + /*, "zh@collation=unihan", "ja@collation=unihan", "ko@collation=unihan"*/ }; for (String[] test : tests) { AlphabeticIndex alphabeticIndex = new AlphabeticIndex(new ULocale(test[0])); @@ -327,6 +327,22 @@ public class AlphabeticIndexTest extends TestFmwk { } } + @Test + public void TestSetGetSpecialLabels() { + AlphabeticIndex index = new AlphabeticIndex(Locale.GERMAN).addLabels(new Locale("ru")); + index.setUnderflowLabel("__"); + index.setInflowLabel("--"); + index.setOverflowLabel("^^"); + assertEquals("underflow label", "__", index.getUnderflowLabel()); + assertEquals("inflow label", "--", index.getInflowLabel()); + assertEquals("overflow label", "^^", index.getOverflowLabel()); + + ImmutableIndex ii = index.buildImmutableIndex(); + assertEquals("0 -> underflow", "__", ii.getBucket(ii.getBucketIndex("0")).getLabel()); + assertEquals("Ω -> inflow", "--", ii.getBucket(ii.getBucketIndex("Ω")).getLabel()); + assertEquals("字 -> overflow", "^^", ii.getBucket(ii.getBucketIndex("字")).getLabel()); + } + @Test public void TestInflow() { Object[][] tests = { @@ -381,9 +397,10 @@ public class AlphabeticIndexTest extends TestFmwk { int counter = 0; Counter itemCount = new Counter(); for (String item : test) { - index.addRecord(item, counter++); + index.addRecord(item, counter++); itemCount.add(item, 1); } + assertEquals("getRecordCount()", (int)itemCount.getTotal(), index.getRecordCount()); // code coverage List labels = index.getBucketLabels(); ImmutableIndex immIndex = index.buildImmutableIndex(); @@ -589,7 +606,7 @@ public class AlphabeticIndexTest extends TestFmwk { public void TestClientSupport() { for (String localeString : new String[] {"zh"}) { // KEY_LOCALES, new String[] {"zh"} ULocale ulocale = new ULocale(localeString); - AlphabeticIndex alphabeticIndex = new AlphabeticIndex(ulocale).addLabels(ULocale.ENGLISH); + AlphabeticIndex alphabeticIndex = new AlphabeticIndex(ulocale).addLabels(Locale.ENGLISH); RuleBasedCollator collator = alphabeticIndex.getCollator(); String [][] tests; @@ -643,7 +660,7 @@ public class AlphabeticIndexTest extends TestFmwk { String myName = null; if (myBucketIterator.hasNext()) { R4 myRecord = myBucketIterator.next(); - myName = (String) myRecord.get1(); + myName = myRecord.get1(); } if (!record.getName().equals(myName)) { gotError |= !assertEquals(ulocale + "\t" + bucketLabel + "\t" + "Record Names (" + index + "." + recordIndex++ + ")", record.getName(), myName); @@ -651,7 +668,7 @@ public class AlphabeticIndexTest extends TestFmwk { } while (myBucketIterator.hasNext()) { R4 myRecord = myBucketIterator.next(); - String myName = (String) myRecord.get1(); + String myName = myRecord.get1(); gotError |= !assertEquals(ulocale + "\t" + bucketLabel + "\t" + "Record Names (" + index + "." + recordIndex++ + ")", null, myName); } index++; @@ -763,20 +780,20 @@ public class AlphabeticIndexTest extends TestFmwk { checkBuckets("zh_Hant", traditionalNames, ULocale.ENGLISH, "\u4e9f", "\u5357\u9580"); } - static final String[] SimpleTests = { + static final String[] SimpleTests = { "斎藤", - "\u1f2d\u03c1\u03b1", - "$", "\u00a3", "12", "2", + "\u1f2d\u03c1\u03b1", + "$", "\u00a3", "12", "2", "Davis", "Davis", "Abbot", "\u1D05avis", "Zach", "\u1D05avis", "\u01b5", "\u0130stanbul", "Istanbul", "istanbul", "\u0131stanbul", "\u00deor", "\u00c5berg", "\u00d6stlund", - "\u1f2d\u03c1\u03b1", "\u1f08\u03b8\u03b7\u03bd\u1fb6", - "\u0396\u03b5\u03cd\u03c2", "\u03a0\u03bf\u03c3\u03b5\u03b9\u03b4\u1f63\u03bd", "\u1f0d\u03b9\u03b4\u03b7\u03c2", "\u0394\u03b7\u03bc\u03ae\u03c4\u03b7\u03c1", "\u1f19\u03c3\u03c4\u03b9\u03ac", + "\u1f2d\u03c1\u03b1", "\u1f08\u03b8\u03b7\u03bd\u1fb6", + "\u0396\u03b5\u03cd\u03c2", "\u03a0\u03bf\u03c3\u03b5\u03b9\u03b4\u1f63\u03bd", "\u1f0d\u03b9\u03b4\u03b7\u03c2", "\u0394\u03b7\u03bc\u03ae\u03c4\u03b7\u03c1", "\u1f19\u03c3\u03c4\u03b9\u03ac", //"\u1f08\u03c0\u03cc\u03bb\u03bb\u03c9\u03bd", "\u1f0c\u03c1\u03c4\u03b5\u03bc\u03b9\u03c2", "\u1f19\u03c1\u03bc\u1f23\u03c2", "\u1f0c\u03c1\u03b7\u03c2", "\u1f08\u03c6\u03c1\u03bf\u03b4\u03af\u03c4\u03b7", "\u1f2d\u03c6\u03b1\u03b9\u03c3\u03c4\u03bf\u03c2", "\u0394\u03b9\u03cc\u03bd\u03c5\u03c3\u03bf\u03c2", "\u6589\u85e4", "\u4f50\u85e4", "\u9234\u6728", "\u9ad8\u6a4b", "\u7530\u4e2d", "\u6e21\u8fba", "\u4f0a\u85e4", "\u5c71\u672c", "\u4e2d\u6751", "\u5c0f\u6797", "\u658e\u85e4", "\u52a0\u85e4", //"\u5409\u7530", "\u5c71\u7530", "\u4f50\u3005\u6728", "\u5c71\u53e3", "\u677e\u672c", "\u4e95\u4e0a", "\u6728\u6751", "\u6797", "\u6e05\u6c34" }; - static final String[] hackPinyin = { + static final String[] hackPinyin = { "a", "\u5416", "\u58ba", // "b", "\u516b", "\u62d4", "\u8500", // "c", "\u5693", "\u7938", "\u9e7e", // @@ -802,7 +819,7 @@ public class AlphabeticIndexTest extends TestFmwk { "z", "\u5e00", "\u707d", "\u5c0a" }; - static final String[] simplifiedNames = { + static final String[] simplifiedNames = { "Abbot", "Morton", "Zachary", "Williams", "\u8d75", "\u94b1", "\u5b59", "\u674e", "\u5468", "\u5434", "\u90d1", "\u738b", "\u51af", "\u9648", "\u696e", "\u536b", "\u848b", "\u6c88", "\u97e9", "\u6768", "\u6731", "\u79e6", "\u5c24", "\u8bb8", "\u4f55", "\u5415", "\u65bd", "\u5f20", "\u5b54", "\u66f9", "\u4e25", "\u534e", "\u91d1", "\u9b4f", "\u9676", "\u59dc", "\u621a", "\u8c22", "\u90b9", "\u55bb", "\u67cf", "\u6c34", "\u7aa6", "\u7ae0", "\u4e91", "\u82cf", "\u6f58", "\u845b", "\u595a", "\u8303", "\u5f6d", "\u90ce", "\u9c81", "\u97e6", "\u660c", "\u9a6c", "\u82d7", "\u51e4", "\u82b1", "\u65b9", @@ -905,7 +922,7 @@ public class AlphabeticIndexTest extends TestFmwk { coll.setReorderCodes(UScript.HAN); AlphabeticIndex index = new AlphabeticIndex(coll); assertEquals("getBucketCount()", 1, index.getBucketCount()); // ... (underflow only) - index.addLabels(ULocale.ENGLISH); + index.addLabels(Locale.ENGLISH); assertEquals("getBucketCount()", 28, index.getBucketCount()); // ... A-Z ... int bucketIndex = index.getBucketIndex("\u897f"); assertEquals("getBucketIndex(U+897F)", 0, bucketIndex); // underflow bucket @@ -929,7 +946,7 @@ public class AlphabeticIndexTest extends TestFmwk { coll.setReorderCodes(UScript.HAN); AlphabeticIndex index = new AlphabeticIndex(coll); assertEquals("getBucketCount()", 28, index.getBucketCount()); // ... A-Z ... - index.addLabels(ULocale.CHINESE); + index.addLabels(Locale.CHINESE); assertEquals("getBucketCount()", 28, index.getBucketCount()); // ... A-Z ... int bucketIndex = index.getBucketIndex("\u897f"); assertEquals("getBucketIndex(U+897F)", 'X' - 'A' + 1, bucketIndex); @@ -996,6 +1013,7 @@ public class AlphabeticIndexTest extends TestFmwk { index.addRecord("\u897f", 0); index.addRecord("i", 0); index.addRecord("\u03B1", 0); + assertEquals("getRecordCount()", 3, index.getRecordCount()); // code coverage assertEquals("getBucketCount()", 1, index.getBucketCount()); // ... Bucket bucket = index.iterator().next(); assertEquals("underflow label type", LabelType.UNDERFLOW, bucket.getLabelType()); @@ -1049,6 +1067,7 @@ public class AlphabeticIndexTest extends TestFmwk { public void TestChineseUnihan() { AlphabeticIndex index = new AlphabeticIndex(new ULocale("zh-u-co-unihan")); index.setMaxLabelCount(500); // ICU 54 default is 99. + assertEquals("getMaxLabelCount()", 500, index.getMaxLabelCount()); // code coverage AlphabeticIndex.ImmutableIndex immIndex = index.buildImmutableIndex(); int bucketCount = immIndex.getBucketCount(); if(bucketCount < 216) { diff --git a/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/CollationAPITest.java b/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/CollationAPITest.java index 12a05048ac3..085298d85f6 100644 --- a/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/CollationAPITest.java +++ b/icu4j/main/tests/collate/src/com/ibm/icu/dev/test/collator/CollationAPITest.java @@ -7,11 +7,11 @@ ******************************************************************************* */ -/** +/** * Port From: ICU4C v2.1 : collate/CollationAPITest * Source File: $ICU4CRoot/source/test/intltest/apicoll.cpp **/ - + package com.ibm.icu.dev.test.collator; import java.text.CharacterIterator; @@ -52,16 +52,16 @@ public class CollationAPITest extends TestFmwk { logln("testing CollationKey begins..."); Collator col = Collator.getInstance(); col.setStrength(Collator.TERTIARY); - + String test1 = "Abcda"; String test2 = "abcda"; - + logln("Testing weird arguments"); CollationKey sortk1 = col.getCollationKey(""); // key gets reset here byte[] bytes = sortk1.toByteArray(); - doAssert(bytes.length == 3 && bytes[0] == 1 && bytes[1] == 1 - && bytes[2] == 0, + doAssert(bytes.length == 3 && bytes[0] == 1 && bytes[1] == 1 + && bytes[2] == 0, "Empty string should return a collation key with empty levels"); // Most control codes and CGJ are completely ignorable. @@ -104,38 +104,38 @@ public class CollationAPITest extends TestFmwk { CollationKey key1 = col.getCollationKey(test1); CollationKey key2 = col.getCollationKey(test2); CollationKey key3 = col.getCollationKey(test2); - - doAssert(key1.compareTo(key2) > 0, + + doAssert(key1.compareTo(key2) > 0, "Result should be \"Abcda\" > \"abcda\""); doAssert(key2.compareTo(key1) < 0, "Result should be \"abcda\" < \"Abcda\""); doAssert(key2.compareTo(key3) == 0, "Result should be \"abcda\" == \"abcda\""); - + byte key2identical[] = key2.toByteArray(); - + logln("Use secondary comparision level testing ..."); col.setStrength(Collator.SECONDARY); - + key1 = col.getCollationKey(test1); key2 = col.getCollationKey(test2); key3 = col.getCollationKey(test2); - - doAssert(key1.compareTo(key2) == 0, + + doAssert(key1.compareTo(key2) == 0, "Result should be \"Abcda\" == \"abcda\""); doAssert(key2.compareTo(key3) == 0, "Result should be \"abcda\" == \"abcda\""); - + byte tempkey[] = key2.toByteArray(); byte subkey2compat[] = new byte[tempkey.length]; System.arraycopy(key2identical, 0, subkey2compat, 0, tempkey.length); subkey2compat[subkey2compat.length - 1] = 0; doAssert(Arrays.equals(tempkey, subkey2compat), "Binary format for 'abcda' sortkey different for secondary strength!"); - + logln("testing sortkey ends..."); } - + @Test public void TestRawCollationKey() { @@ -143,47 +143,47 @@ public class CollationAPITest extends TestFmwk { RawCollationKey key = new RawCollationKey(); if (key.bytes != null || key.size != 0) { errln("Empty default constructor expected to leave the bytes null " - + "and size 0"); + + "and size 0"); } byte array[] = new byte[128]; key = new RawCollationKey(array); if (key.bytes != array || key.size != 0) { errln("Constructor taking an array expected to adopt it and " - + "retaining its size 0"); + + "retaining its size 0"); } try { key = new RawCollationKey(array, 129); errln("Constructor taking an array and a size > array.length " - + "expected to throw an exception"); + + "expected to throw an exception"); } catch (IndexOutOfBoundsException e) { logln("PASS: Constructor failed as expected"); } try { key = new RawCollationKey(array, -1); errln("Constructor taking an array and a size < 0 " - + "expected to throw an exception"); + + "expected to throw an exception"); } catch (IndexOutOfBoundsException e) { logln("PASS: Constructor failed as expected"); } key = new RawCollationKey(array, array.length >> 1); if (key.bytes != array || key.size != (array.length >> 1)) { errln("Constructor taking an array and a size, " - + "expected to adopt it and take the size specified"); + + "expected to adopt it and take the size specified"); } key = new RawCollationKey(10); if (key.bytes == null || key.bytes.length != 10 || key.size != 0) { errln("Constructor taking a specified capacity expected to " + "create a new internal byte array with length 10 and " - + "retain size 0"); + + "retain size 0"); } } - + void doAssert(boolean conditions, String message) { if (!conditions) { errln(message); } } - + /** * This tests the comparison convenience methods of a collator object. * - greater than @@ -198,24 +198,24 @@ public class CollationAPITest extends TestFmwk { String test1 = "Abcda"; String test2 = "abcda"; logln("Use tertiary comparison level testing ...."); - + doAssert((!col.equals(test1, test2) ), "Result should be \"Abcda\" != \"abcda\""); doAssert((col.compare(test1, test2) > 0 ), "Result should be \"Abcda\" >>> \"abcda\""); col.setStrength(Collator.SECONDARY); logln("Use secondary comparison level testing ...."); - + doAssert((col.equals(test1, test2) ), "Result should be \"Abcda\" == \"abcda\""); doAssert((col.compare(test1, test2) == 0), "Result should be \"Abcda\" == \"abcda\""); col.setStrength(Collator.PRIMARY); logln("Use primary comparison level testing ...."); - + doAssert((col.equals(test1, test2) ), "Result should be \"Abcda\" == \"abcda\""); doAssert((col.compare(test1, test2) == 0 ), "Result should be \"Abcda\" == \"abcda\""); logln("The compare tests end."); } - + /** * Tests decomposition setting */ @@ -227,7 +227,7 @@ public class CollationAPITest extends TestFmwk { el_GR = Collator.getInstance(new Locale("el", "GR")); vi_VN = Collator.getInstance(new Locale("vi", "VN")); - + // there is no reason to have canonical decomposition in en_US OR default locale */ if (vi_VN.getDecomposition() != Collator.CANONICAL_DECOMPOSITION) { @@ -244,15 +244,15 @@ public class CollationAPITest extends TestFmwk { errln("en_US collation had cannonical decomposition for normalization!"); } } - + /** * This tests the duplication of a collator object. */ @Test public void TestDuplicate() { - //Clone does not be implemented + //Clone does not be implemented Collator col1 = Collator.getInstance(Locale.ENGLISH); - + // Collator col2 = (Collator)col1.clone(); // doAssert(col1.equals(col2), "Cloned object is not equal to the orginal"); String ruleset = "&9 < a, A < b, B < c, C < d, D, e, E"; @@ -266,9 +266,9 @@ public class CollationAPITest extends TestFmwk { doAssert(!col1.equals(col3), "Cloned object is equal to some dummy"); col3 = (RuleBasedCollator)col1; doAssert(col1.equals(col3), "Copied object is not equal to the orginal"); - + } - + /** * This tests the CollationElementIterator related APIs. * - creation of a CollationElementIterator object @@ -282,18 +282,18 @@ public class CollationAPITest extends TestFmwk { // logln("testing sortkey begins..."); Collator col = Collator.getInstance(Locale.ENGLISH); - + String testString1 = "XFILE What subset of all possible test cases has the highest probability of detecting the most errors?"; String testString2 = "Xf_ile What subset of all possible test cases has the lowest probability of detecting the least errors?"; // logln("Constructors and comparison testing...."); CollationElementIterator iterator1 = ((RuleBasedCollator)col).getCollationElementIterator(testString1); - + CharacterIterator chariter=new StringCharacterIterator(testString1); // copy ctor CollationElementIterator iterator2 = ((RuleBasedCollator)col).getCollationElementIterator(chariter); UCharacterIterator uchariter=UCharacterIterator.getInstance(testString2); CollationElementIterator iterator3 = ((RuleBasedCollator)col).getCollationElementIterator(uchariter); - + int offset = 0; offset = iterator1.getOffset(); if (offset != 0) { @@ -303,48 +303,55 @@ public class CollationAPITest extends TestFmwk { iterator1.setOffset(6); iterator1.setOffset(0); int order1, order2, order3; - + order1 = iterator1.next(); doAssert(!(iterator1.equals(iterator2)), "The first iterator advance failed"); order2 = iterator2.next(); + // Code coverage for dummy "not designed" hashCode() which does "assert false". + try { + iterator1.hashCode(); // We don't expect any particular value. + } catch (AssertionError ignored) { + // Expected to be thrown if assertions are enabled. + } + // In ICU 52 and earlier we had iterator1.equals(iterator2) // but in ICU 53 this fails because the iterators differ (String vs. CharacterIterator). // doAssert((iterator1.equals(iterator2)), "The second iterator advance failed"); doAssert(iterator1.getOffset() == iterator2.getOffset(), "The second iterator advance failed"); doAssert((order1 == order2), "The order result should be the same"); order3 = iterator3.next(); - - doAssert((CollationElementIterator.primaryOrder(order1) == + + doAssert((CollationElementIterator.primaryOrder(order1) == CollationElementIterator.primaryOrder(order3)), "The primary orders should be the same"); - doAssert((CollationElementIterator.secondaryOrder(order1) == + doAssert((CollationElementIterator.secondaryOrder(order1) == CollationElementIterator.secondaryOrder(order3)), "The secondary orders should be the same"); - doAssert((CollationElementIterator.tertiaryOrder(order1) == + doAssert((CollationElementIterator.tertiaryOrder(order1) == CollationElementIterator.tertiaryOrder(order3)), "The tertiary orders should be the same"); - - order1 = iterator1.next(); + + order1 = iterator1.next(); order3 = iterator3.next(); - - doAssert((CollationElementIterator.primaryOrder(order1) == + + doAssert((CollationElementIterator.primaryOrder(order1) == CollationElementIterator.primaryOrder(order3)), "The primary orders should be identical"); - doAssert((CollationElementIterator.tertiaryOrder(order1) != + doAssert((CollationElementIterator.tertiaryOrder(order1) != CollationElementIterator.tertiaryOrder(order3)), "The tertiary orders should be different"); - - order1 = iterator1.next(); + + order1 = iterator1.next(); order3 = iterator3.next(); // invalid test wrong in UCA - // doAssert((CollationElementIterator.secondaryOrder(order1) != + // doAssert((CollationElementIterator.secondaryOrder(order1) != // CollationElementIterator.secondaryOrder(order3)), "The secondary orders should not be the same"); - + doAssert((order1 != CollationElementIterator.NULLORDER), "Unexpected end of iterator reached"); - - iterator1.reset(); - iterator2.reset(); + + iterator1.reset(); + iterator2.reset(); iterator3.reset(); order1 = iterator1.next(); - + doAssert(!(iterator1.equals(iterator2)), "The first iterator advance failed"); - + order2 = iterator2.next(); // In ICU 52 and earlier we had iterator1.equals(iterator2) @@ -352,36 +359,36 @@ public class CollationAPITest extends TestFmwk { // doAssert((iterator1.equals(iterator2)), "The second iterator advance failed"); doAssert(iterator1.getOffset() == iterator2.getOffset(), "The second iterator advance failed"); doAssert((order1 == order2), "The order result should be the same"); - + order3 = iterator3.next(); - - doAssert((CollationElementIterator.primaryOrder(order1) == + + doAssert((CollationElementIterator.primaryOrder(order1) == CollationElementIterator.primaryOrder(order3)), "The primary orders should be the same"); - doAssert((CollationElementIterator.secondaryOrder(order1) == + doAssert((CollationElementIterator.secondaryOrder(order1) == CollationElementIterator.secondaryOrder(order3)), "The secondary orders should be the same"); - doAssert((CollationElementIterator.tertiaryOrder(order1) == + doAssert((CollationElementIterator.tertiaryOrder(order1) == CollationElementIterator.tertiaryOrder(order3)), "The tertiary orders should be the same"); - - order1 = iterator1.next(); - order2 = iterator2.next(); + + order1 = iterator1.next(); + order2 = iterator2.next(); order3 = iterator3.next(); - - doAssert((CollationElementIterator.primaryOrder(order1) == + + doAssert((CollationElementIterator.primaryOrder(order1) == CollationElementIterator.primaryOrder(order3)), "The primary orders should be identical"); - doAssert((CollationElementIterator.tertiaryOrder(order1) != + doAssert((CollationElementIterator.tertiaryOrder(order1) != CollationElementIterator.tertiaryOrder(order3)), "The tertiary orders should be different"); - - order1 = iterator1.next(); + + order1 = iterator1.next(); order3 = iterator3.next(); - + // obsolete invalid test, removed - // doAssert((CollationElementIterator.secondaryOrder(order1) != + // doAssert((CollationElementIterator.secondaryOrder(order1) != // CollationElementIterator.secondaryOrder(order3)), "The secondary orders should not be the same"); doAssert((order1 != CollationElementIterator.NULLORDER), "Unexpected end of iterator reached"); doAssert(!(iterator2.equals(iterator3)), "The iterators should be different"); logln("testing CollationElementIterator ends..."); } - + /** * This tests the hashCode method of a collator object. */ @@ -389,7 +396,7 @@ public class CollationAPITest extends TestFmwk { public void TestHashCode() { logln("hashCode tests begin."); Collator col1 = Collator.getInstance(Locale.ENGLISH); - + Collator col2 = null; Locale dk = new Locale("da", "DK", ""); try { @@ -398,7 +405,7 @@ public class CollationAPITest extends TestFmwk { errln("Danish collation creation failed."); return; } - + Collator col3 = null; try { col3 = Collator.getInstance(Locale.ENGLISH); @@ -406,28 +413,28 @@ public class CollationAPITest extends TestFmwk { errln("2nd default collation creation failed."); return; } - + logln("Collator.hashCode() testing ..."); - - doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect" ); - doAssert(!(col1.hashCode() == col2.hashCode()), "Hash test2 result incorrect" ); - doAssert(col1.hashCode() == col3.hashCode(), "Hash result not equal" ); - + + doAssert(col1.hashCode() != col2.hashCode(), "Hash test1 result incorrect" ); + doAssert(!(col1.hashCode() == col2.hashCode()), "Hash test2 result incorrect" ); + doAssert(col1.hashCode() == col3.hashCode(), "Hash result not equal" ); + logln("hashCode tests end."); - + String test1 = "Abcda"; String test2 = "abcda"; - + CollationKey sortk1, sortk2, sortk3; - + sortk1 = col3.getCollationKey(test1); - sortk2 = col3.getCollationKey(test2); - sortk3 = col3.getCollationKey(test2); - - doAssert(sortk1.hashCode() != sortk2.hashCode(), "Hash test1 result incorrect"); + sortk2 = col3.getCollationKey(test2); + sortk3 = col3.getCollationKey(test2); + + doAssert(sortk1.hashCode() != sortk2.hashCode(), "Hash test1 result incorrect"); doAssert(sortk2.hashCode() == sortk3.hashCode(), "Hash result not equal" ); } - + /** * This tests the properties of a collator object. * - constructor @@ -437,13 +444,13 @@ public class CollationAPITest extends TestFmwk { */ @Test public void TestProperty() { - /* + /* All the collations have the same version in an ICU version. ICU 2.0 currVersionArray = {0x18, 0xC0, 0x02, 0x02}; ICU 2.1 currVersionArray = {0x19, 0x00, 0x03, 0x03}; - ICU 2.8 currVersionArray = {0x29, 0x80, 0x00, 0x04}; - */ + ICU 2.8 currVersionArray = {0x29, 0x80, 0x00, 0x04}; + */ logln("The property tests begin : "); logln("Test ctors : "); Collator col = Collator.getInstance(Locale.ENGLISH); @@ -467,60 +474,60 @@ public class CollationAPITest extends TestFmwk { doAssert((col.compare("blackbird", "black-bird") > 0), "black-bird > blackbird comparison failed"); doAssert((col.compare("black bird", "black-bird") < 0), "black bird > black-bird comparison failed"); doAssert((col.compare("Hello", "hello") > 0), "Hello > hello comparison failed"); - + logln("Test ctors ends."); - + logln("testing Collator.getStrength() method ..."); doAssert((col.getStrength() == Collator.TERTIARY), "collation object has the wrong strength"); doAssert((col.getStrength() != Collator.PRIMARY), "collation object's strength is primary difference"); - + logln("testing Collator.setStrength() method ..."); col.setStrength(Collator.SECONDARY); doAssert((col.getStrength() != Collator.TERTIARY), "collation object's strength is secondary difference"); doAssert((col.getStrength() != Collator.PRIMARY), "collation object's strength is primary difference"); doAssert((col.getStrength() == Collator.SECONDARY), "collation object has the wrong strength"); - + logln("testing Collator.setDecomposition() method ..."); col.setDecomposition(Collator.NO_DECOMPOSITION); doAssert((col.getDecomposition() != Collator.CANONICAL_DECOMPOSITION), "Decomposition mode != Collator.CANONICAL_DECOMPOSITION"); doAssert((col.getDecomposition() == Collator.NO_DECOMPOSITION), "Decomposition mode = Collator.NO_DECOMPOSITION"); - - + + RuleBasedCollator rcol = (RuleBasedCollator)Collator.getInstance(new Locale("da", "DK")); doAssert(rcol.getRules().length() != 0, "da_DK rules does not have length 0"); - + try { col = Collator.getInstance(Locale.FRENCH); } catch (Exception e) { errln("Creating French collation failed."); return; } - + col.setStrength(Collator.PRIMARY); logln("testing Collator.getStrength() method again ..."); doAssert((col.getStrength() != Collator.TERTIARY), "collation object has the wrong strength"); doAssert((col.getStrength() == Collator.PRIMARY), "collation object's strength is not primary difference"); - + logln("testing French Collator.setStrength() method ..."); col.setStrength(Collator.TERTIARY); doAssert((col.getStrength() == Collator.TERTIARY), "collation object's strength is not tertiary difference"); doAssert((col.getStrength() != Collator.PRIMARY), "collation object's strength is primary difference"); doAssert((col.getStrength() != Collator.SECONDARY), "collation object's strength is secondary difference"); - + } @Test public void TestJunkCollator(){ logln("Create junk collation: "); Locale abcd = new Locale("ab", "CD", ""); - + Collator junk = Collator.getInstance(abcd); Collator col = Collator.getInstance(); - + String colrules = ((RuleBasedCollator)col).getRules(); String junkrules = ((RuleBasedCollator)junk).getRules(); - doAssert(colrules == junkrules || colrules.equals(junkrules), + doAssert(colrules == junkrules || colrules.equals(junkrules), "The default collation should be returned."); Collator frCol = null; try { @@ -529,10 +536,10 @@ public class CollationAPITest extends TestFmwk { errln("Creating fr_CA collator failed."); return; } - + doAssert(!(frCol.equals(junk)), "The junk is the same as the fr_CA collator."); logln("Collator property test ended."); - + } /** @@ -543,26 +550,26 @@ public class CollationAPITest extends TestFmwk { @Test public void TestRuleBasedColl() { RuleBasedCollator col1 = null, col2 = null, col3 = null, col4 = null; - - String ruleset1 = "&9 < a, A < b, B < c, C; ch, cH, Ch, CH < d, D, e, E"; + + String ruleset1 = "&9 < a, A < b, B < c, C; ch, cH, Ch, CH < d, D, e, E"; String ruleset2 = "&9 < a, A < b, B < c, C < d, D, e, E"; String ruleset3 = "&"; - + try { col1 = new RuleBasedCollator(ruleset1); } catch (Exception e) { - // only first error needs to be a warning since we exit function + // only first error needs to be a warning since we exit function warnln("RuleBased Collator creation failed."); return; } - + try { col2 = new RuleBasedCollator(ruleset2); } catch (Exception e) { errln("RuleBased Collator creation failed."); return; } - + try { // empty rules fail col3 = new RuleBasedCollator(ruleset3); @@ -573,7 +580,7 @@ public class CollationAPITest extends TestFmwk { } catch (Exception e) { logln("PASS: Empty rules for the collator failed as expected"); } - + Locale locale = new Locale("aa", "AA"); try { col3 = (RuleBasedCollator)Collator.getInstance(locale); @@ -581,29 +588,29 @@ public class CollationAPITest extends TestFmwk { errln("Fallback Collator creation failed.: %s"); return; } - + try { col3 = (RuleBasedCollator)Collator.getInstance(); } catch (Exception e) { errln("Default Collator creation failed.: %s"); return; } - - String rule1 = col1.getRules(); + + String rule1 = col1.getRules(); String rule2 = col2.getRules(); String rule3 = col3.getRules(); - + doAssert(!rule1.equals(rule2), "Default collator getRules failed"); doAssert(!rule2.equals(rule3), "Default collator getRules failed"); doAssert(!rule1.equals(rule3), "Default collator getRules failed"); - + try { col4 = new RuleBasedCollator(rule2); } catch (Exception e) { errln("RuleBased Collator creation failed."); return; } - + String rule4 = col4.getRules(); doAssert(rule2.equals(rule4), "Default collator getRules failed"); // tests that modifier ! is always ignored @@ -614,9 +621,9 @@ public class CollationAPITest extends TestFmwk { RuleBasedCollator col5 = new RuleBasedCollator(exclamationrules); RuleBasedCollator encol = (RuleBasedCollator) Collator.getInstance(Locale.ENGLISH); - CollationElementIterator col5iter + CollationElementIterator col5iter = col5.getCollationElementIterator(thaistr); - CollationElementIterator encoliter + CollationElementIterator encoliter = encol.getCollationElementIterator( thaistr); while (true) { @@ -635,7 +642,7 @@ public class CollationAPITest extends TestFmwk { return; } } - + /** * This tests the RuleBasedCollator * - getRules @@ -645,67 +652,67 @@ public class CollationAPITest extends TestFmwk { RuleBasedCollator coll = (RuleBasedCollator)Collator.getInstance(new Locale("","","")); //root // logln("PASS: RuleBased Collator creation passed"); - + String rules = coll.getRules(); if (rules != null && rules.length() != 0) { errln("Root tailored rules failed"); } } - + @Test public void TestSafeClone() { String test1 = "abCda"; String test2 = "abcda"; - - // one default collator & two complex ones + + // one default collator & two complex ones RuleBasedCollator someCollators[] = { (RuleBasedCollator)Collator.getInstance(Locale.ENGLISH), (RuleBasedCollator)Collator.getInstance(Locale.KOREA), (RuleBasedCollator)Collator.getInstance(Locale.JAPAN) }; RuleBasedCollator someClonedCollators[] = new RuleBasedCollator[3]; - - // change orig & clone & make sure they are independent - + + // change orig & clone & make sure they are independent + for (int index = 0; index < someCollators.length; index ++) { try { - someClonedCollators[index] + someClonedCollators[index] = (RuleBasedCollator)someCollators[index].clone(); } catch (CloneNotSupportedException e) { errln("Error cloning collator"); } - + someClonedCollators[index].setStrength(Collator.TERTIARY); someCollators[index].setStrength(Collator.PRIMARY); someClonedCollators[index].setCaseLevel(false); someCollators[index].setCaseLevel(false); - - doAssert(someClonedCollators[index].compare(test1, test2) > 0, + + doAssert(someClonedCollators[index].compare(test1, test2) > 0, "Result should be \"abCda\" >>> \"abcda\" "); - doAssert(someCollators[index].compare(test1, test2) == 0, + doAssert(someCollators[index].compare(test1, test2) == 0, "Result should be \"abCda\" == \"abcda\" "); } } @Test - public void TestGetTailoredSet() + public void TestGetTailoredSet() { logln("testing getTailoredSet..."); String rules[] = { - "&a < \u212b", + "&a < \u212b", "& S < \u0161 <<< \u0160", }; String data[][] = { - { "\u212b", "A\u030a", "\u00c5" }, - { "\u0161", "s\u030C", "\u0160", "S\u030C" } + { "\u212b", "A\u030a", "\u00c5" }, + { "\u0161", "s\u030C", "\u0160", "S\u030C" } }; - + int i = 0, j = 0; - + RuleBasedCollator coll; UnicodeSet set; - + for(i = 0; i < rules.length; i++) { try { logln("Instantiating a collator from "+rules[i]); @@ -727,11 +734,12 @@ public class CollationAPITest extends TestFmwk { } } - /** - * Simple test to see if Collator is subclassable + /** + * Simple test to see if Collator is subclassable. + * Also test coverage of base class methods that are overridden by RuleBasedCollator. */ @Test - public void TestSubClass() + public void TestSubClass() { class TestCollator extends Collator { @@ -739,25 +747,25 @@ public class CollationAPITest extends TestFmwk { public boolean equals(Object that) { return this == that; } - + @Override public int hashCode() { return 0; } - + @Override public int compare(String source, String target) { return source.compareTo(target); } - + @Override public CollationKey getCollationKey(String source) - { return new CollationKey(source, + { return new CollationKey(source, getRawCollationKey(source, new RawCollationKey())); } - + @Override - public RawCollationKey getRawCollationKey(String source, + public RawCollationKey getRawCollationKey(String source, RawCollationKey key) { byte temp1[] = source.getBytes(); @@ -767,11 +775,11 @@ public class CollationAPITest extends TestFmwk { if (key == null) { key = new RawCollationKey(); } - key.bytes = temp2; + key.bytes = temp2; key.size = temp2.length; return key; } - + @Override public void setVariableTop(int ce) { @@ -779,9 +787,9 @@ public class CollationAPITest extends TestFmwk { throw new UnsupportedOperationException("Attempt to modify frozen object"); } } - + @Override - public int setVariableTop(String str) + public int setVariableTop(String str) { if (isFrozen()) { throw new UnsupportedOperationException("Attempt to modify frozen object"); @@ -789,7 +797,7 @@ public class CollationAPITest extends TestFmwk { return 0; } - + @Override public int getVariableTop() { @@ -804,9 +812,9 @@ public class CollationAPITest extends TestFmwk { public VersionInfo getUCAVersion() { return VersionInfo.getInstance(0); - } + } } - + Collator col1 = new TestCollator(); Collator col2 = new TestCollator(); if (col1.equals(col2)) { @@ -826,22 +834,91 @@ public class CollationAPITest extends TestFmwk { byte temp2[] = new byte[temp1.length + 1]; System.arraycopy(temp1, 0, temp2, 0, temp1.length); temp2[temp1.length] = 0; - if (!java.util.Arrays.equals(key.toByteArray(), temp2) - || !key.getSourceString().equals(abc)) { + if (!java.util.Arrays.equals(key.toByteArray(), temp2) + || !key.getSourceString().equals(abc)) { errln("TestCollator collationkey API is returning wrong values"); } UnicodeSet set = col1.getTailoredSet(); if (!set.equals(new UnicodeSet(0, 0x10FFFF))) { errln("Error getting default tailored set"); } + + // Base class code coverage. + // Most of these methods are dummies; + // they are overridden by any subclass that supports their features. + + assertEquals("compare(strings as Object)", 0, + col1.compare(new StringBuilder("abc"), new StringBuffer("abc"))); + + col1.setStrength(Collator.SECONDARY); + assertNotEquals("getStrength()", Collator.PRIMARY, col1.getStrength()); + + // setStrength2() is @internal and returns this. + // The base class getStrength() always returns the same value, + // since the base class does not have a field to store the strength. + assertNotEquals("setStrength2().getStrength()", Collator.PRIMARY, + col1.setStrength2(Collator.IDENTICAL).getStrength()); + + // (base class).setDecomposition() may or may not be implemented. + try { + col1.setDecomposition(Collator.CANONICAL_DECOMPOSITION); + } catch (UnsupportedOperationException expected) { + } + assertNotEquals("getDecomposition()", -1, col1.getDecomposition()); // don't care about the value + + // (base class).setMaxVariable() may or may not be implemented. + try { + col1.setMaxVariable(Collator.ReorderCodes.CURRENCY); + } catch (UnsupportedOperationException expected) { + } + assertNotEquals("getMaxVariable()", -1, col1.getMaxVariable()); // don't care about the value + + // (base class).setReorderCodes() may or may not be implemented. + try { + col1.setReorderCodes(0, 1, 2); + } catch (UnsupportedOperationException expected) { + } + try { + col1.getReorderCodes(); + } catch (UnsupportedOperationException expected) { + } + + assertFalse("getDisplayName()", Collator.getDisplayName(Locale.GERMAN).isEmpty()); + assertFalse("getDisplayName()", Collator.getDisplayName(Locale.GERMAN, Locale.ITALIAN).isEmpty()); + + assertNotEquals("getLocale()", ULocale.GERMAN, col1.getLocale(ULocale.ACTUAL_LOCALE)); + + // Cover Collator.setLocale() which is only package-visible. + Object token = Collator.registerInstance(new TestCollator(), new ULocale("de-Japn-419")); + Collator.unregister(token); + + // Freezable default implementations. freeze() may or may not be implemented. + assertFalse("not yet frozen", col2.isFrozen()); + try { + col2.freeze(); + assertTrue("now frozen", col2.isFrozen()); + } catch (UnsupportedOperationException expected) { + } + try { + col2.setStrength(Collator.PRIMARY); + if (col2.isFrozen()) { + fail("(frozen Collator).setStrength() should throw an exception"); + } + } catch (UnsupportedOperationException expected) { + } + try { + Collator col3 = col2.cloneAsThawed(); + assertFalse("!cloneAsThawed().isFrozen()", col3.isFrozen()); + } catch (UnsupportedOperationException expected) { + } } - /** + /** * Simple test the collator setter and getters. * Similar to C++ apicoll.cpp TestAttribute(). */ @Test - public void TestSetGet() + public void TestSetGet() { RuleBasedCollator collator = (RuleBasedCollator)Collator.getInstance(); int decomp = collator.getDecomposition(); @@ -852,7 +929,7 @@ public class CollationAPITest extends TestFmwk { boolean hquart = collator.isHiraganaQuaternary(); boolean lowercase = collator.isLowerCaseFirst(); boolean uppercase = collator.isUpperCaseFirst(); - + collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION); if (collator.getDecomposition() != Collator.CANONICAL_DECOMPOSITION) { errln("Setting decomposition failed"); @@ -884,7 +961,7 @@ public class CollationAPITest extends TestFmwk { collator.setUpperCaseFirst(!uppercase); if (collator.isUpperCaseFirst() == uppercase) { errln("Setting upper case first failed"); - } + } collator.setDecompositionDefault(); if (collator.getDecomposition() != decomp) { errln("Setting decomposition default failed"); @@ -910,7 +987,7 @@ public class CollationAPITest extends TestFmwk { errln("Setting Hiragana Quartenary default failed"); } collator.setCaseFirstDefault(); - if (collator.isLowerCaseFirst() != lowercase + if (collator.isLowerCaseFirst() != lowercase || collator.isUpperCaseFirst() != uppercase) { errln("Setting case first handling default failed"); } @@ -1101,32 +1178,32 @@ public class CollationAPITest extends TestFmwk { } @Test - public void TestBounds() + public void TestBounds() { Collator coll = Collator.getInstance(new Locale("sh", "")); - - String test[] = { "John Smith", "JOHN SMITH", + + String test[] = { "John Smith", "JOHN SMITH", "john SMITH", "j\u00F6hn sm\u00EFth", "J\u00F6hn Sm\u00EFth", "J\u00D6HN SM\u00CFTH", "john smithsonian", "John Smithsonian", }; - + String testStr[] = { - "\u010CAKI MIHALJ", "\u010CAKI MIHALJ", - "\u010CAKI PIRO\u0160KA", + "\u010CAKI MIHALJ", + "\u010CAKI PIRO\u0160KA", "\u010CABAI ANDRIJA", - "\u010CABAI LAJO\u0160", + "\u010CABAI LAJO\u0160", "\u010CABAI MARIJA", - "\u010CABAI STEVAN", "\u010CABAI STEVAN", - "\u010CABARKAPA BRANKO", + "\u010CABAI STEVAN", + "\u010CABARKAPA BRANKO", "\u010CABARKAPA MILENKO", - "\u010CABARKAPA MIROSLAV", + "\u010CABARKAPA MIROSLAV", "\u010CABARKAPA SIMO", - "\u010CABARKAPA STANKO", + "\u010CABARKAPA STANKO", "\u010CABARKAPA TAMARA", - "\u010CABARKAPA TOMA\u0160", + "\u010CABARKAPA TOMA\u0160", "\u010CABDARI\u0106 NIKOLA", "\u010CABDARI\u0106 ZORICA", "\u010CABI NANDOR", @@ -1169,20 +1246,20 @@ public class CollationAPITest extends TestFmwk { "\u010CAKI ANDRA\u0160", "\u010CAKI LADISLAV", "\u010CAKI LAJO\u0160", - "\u010CAKI LASLO" }; - + "\u010CAKI LASLO" }; + CollationKey testKey[] = new CollationKey[testStr.length]; for (int i = 0; i < testStr.length; i ++) { testKey[i] = coll.getCollationKey(testStr[i]); } - + Arrays.sort(testKey); for(int i = 0; i < testKey.length - 1; i ++) { - CollationKey lower + CollationKey lower = testKey[i].getBound(CollationKey.BoundMode.LOWER, Collator.SECONDARY); for (int j = i + 1; j < testKey.length; j ++) { - CollationKey upper + CollationKey upper = testKey[j].getBound(CollationKey.BoundMode.UPPER, Collator.SECONDARY); for (int k = i; k <= j; k ++) { @@ -1197,8 +1274,8 @@ public class CollationAPITest extends TestFmwk { } } } - - for (int i = 0; i < test.length; i ++) + + for (int i = 0; i < test.length; i ++) { CollationKey key = coll.getCollationKey(test[i]); CollationKey lower = key.getBound(CollationKey.BoundMode.LOWER, @@ -1216,7 +1293,7 @@ public class CollationAPITest extends TestFmwk { } } } - + public final void TestGetAll() { Locale[] list = Collator.getAvailableLocales(); int errorCount = 0; @@ -1227,24 +1304,24 @@ public class CollationAPITest extends TestFmwk { logln(list[i].getDisplayName()); try{ logln(" ...... Or display as: " + Collator.getDisplayName(list[i])); - logln(" ...... and display in Chinese: " + - Collator.getDisplayName(list[i],Locale.CHINA)); + logln(" ...... and display in Chinese: " + + Collator.getDisplayName(list[i],Locale.CHINA)); }catch(MissingResourceException ex){ errorCount++; logln("could not get displayName for " + list[i]); - } + } } if(errorCount>0){ warnln("Could not load the locale data."); } - } + } private boolean doSetsTest(UnicodeSet ref, UnicodeSet set, String inSet, String outSet) { boolean ok = true; set.clear(); set.applyPattern(inSet); - + if(!ref.containsAll(set)) { err("Some stuff from "+inSet+" is not present in the set.\nMissing:"+ set.removeAll(ref).toPattern(true)+"\n"); @@ -1275,7 +1352,7 @@ public class CollationAPITest extends TestFmwk { } */ String tests[][] = { - { "ru", + { "ru", "[{\u0418\u0306}{\u0438\u0306}]", "[\u0439\u0457]", "[\u00e6]", @@ -1326,7 +1403,7 @@ public class CollationAPITest extends TestFmwk { UnicodeSet conts = new UnicodeSet(); UnicodeSet exp = new UnicodeSet(); UnicodeSet set = new UnicodeSet(); - + for(i = 0; i < tests.length; i++) { logln("Testing locale: "+ tests[i][0]); coll = (RuleBasedCollator)Collator.getInstance(new ULocale(tests[i][0])); @@ -1352,7 +1429,7 @@ public class CollationAPITest extends TestFmwk { } private static final String bigone = "One"; private static final String littleone = "one"; - + @Test public void TestClone() { logln("\ninit c0"); @@ -1441,7 +1518,7 @@ public class CollationAPITest extends TestFmwk { } } } - + /* * Tests the class CollatorFactory */ @@ -1449,6 +1526,7 @@ public class CollationAPITest extends TestFmwk { public void TestCreateCollator() { // The following class override public Collator createCollator(Locale loc) class TestCreateCollator extends CollatorFactory { + @Override public Set getSupportedLocaleIDs() { return new HashSet(); } @@ -1457,12 +1535,14 @@ public class CollationAPITest extends TestFmwk { super(); } + @Override public Collator createCollator(ULocale c) { return null; } } // The following class override public Collator createCollator(ULocale loc) class TestCreateCollator1 extends CollatorFactory { + @Override public Set getSupportedLocaleIDs() { return new HashSet(); } @@ -1471,9 +1551,11 @@ public class CollationAPITest extends TestFmwk { super(); } + @Override public Collator createCollator(Locale c) { return null; } + @Override public boolean visible(){ return false; } @@ -1498,7 +1580,7 @@ public class CollationAPITest extends TestFmwk { } catch (Exception e) { errln("Collator.createCollator(ULocale) was not suppose to " + "return an exception."); } - + /* * Tests the method public String getDisplayName(Locale objectLocale, Locale displayLocale) using TestCreateCollator1 class */ @@ -1508,7 +1590,7 @@ public class CollationAPITest extends TestFmwk { } catch (Exception e) { errln("Collator.getDisplayName(Locale,Locale) was not suppose to return an exception."); } - + /* * Tests the method public String getDisplayName(ULocale objectLocale, ULocale displayLocale) using TestCreateCollator1 class */ diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateIntervalFormatTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateIntervalFormatTest.java index dee86416df4..859bc1bdaed 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateIntervalFormatTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateIntervalFormatTest.java @@ -1,3 +1,4 @@ + // © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* @@ -16,6 +17,7 @@ package com.ibm.icu.dev.test.format; import java.text.FieldPosition; import java.text.ParseException; +import java.text.ParsePosition; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -33,6 +35,7 @@ import com.ibm.icu.text.DateIntervalInfo.PatternInfo; import com.ibm.icu.text.SimpleDateFormat; import com.ibm.icu.util.Calendar; import com.ibm.icu.util.DateInterval; +import com.ibm.icu.util.Output; import com.ibm.icu.util.TimeZone; import com.ibm.icu.util.ULocale; @@ -1390,6 +1393,43 @@ public class DateIntervalFormatTest extends com.ibm.icu.dev.test.TestFmwk { DateIntervalFormat.getInstance(DateFormat.YEAR_MONTH).parseObject(""); } + @Test + public void TestDateIntervalFormatCoverage() throws Exception{ + long date1 = 1299090600000L; + long date2 = 1299115800000L; + DateInterval dtitv = new DateInterval(date1, date2); + DateIntervalFormat dtitvfmt = DateIntervalFormat.getInstance("MMMd", Locale.ENGLISH); + DateIntervalInfo dtintinf = new DateIntervalInfo(ULocale.ENGLISH); + + // Check the default private constructor + checkDefaultPrivateConstructor(DateIntervalFormat.class); + + // Check clone + DateIntervalFormat dtitvfmtClone = (DateIntervalFormat) dtitvfmt.clone(); + assertEquals("DateIntervalFormat.clone() failed", dtitvfmt.format(dtitv), dtitvfmtClone.format(dtitv)); + + // Coverage for getInstance + assertNotNull("Expected DateIntervalFormat object", DateIntervalFormat.getInstance("MMMd", dtintinf)); + assertNotNull("Expected DateIntervalFormat object", + DateIntervalFormat.getInstance("MMMdHHmm", Locale.ENGLISH, dtintinf)); + + // Coverage for parseObject. Exception expected. + try { + dtitvfmt.parseObject("", new ParsePosition(0)); + errln("Exception was expected when calling DateIntervalFormat.parseObject()"); + } catch (Exception e) { /* No op */ } + + // Check getPatterns() + Output secondPart = new Output(); + Calendar fromCalendar = Calendar.getInstance(Locale.ENGLISH); + fromCalendar.set(2016, 5, 22); + Calendar toCalendar= Calendar.getInstance(Locale.ENGLISH); + toCalendar.set(2016, 5, 23); + assertEquals("Date interval pattern mismatch.", + dtitvfmt.getPatterns(fromCalendar, toCalendar, secondPart), "MMM d – "); + assertEquals("Date interval pattern mismatch.", secondPart.value, "d"); + } + @Test public void TestTicket9919GetInstance() { // Creating a DateIntervalFormat with a custom DateIntervalInfo diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateTimeGeneratorTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateTimeGeneratorTest.java index 5a3a2c6499d..272f5a02559 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateTimeGeneratorTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/DateTimeGeneratorTest.java @@ -1480,6 +1480,66 @@ public class DateTimeGeneratorTest extends TestFmwk { assertEquals("DateTimePatternGenerator.getAppendFormatNumber for Timezone", 15, fieldNum); } + /* + * Coverage for methods otherwise not covered by other tests. + */ + @Test + public void TestCoverage() { + DateTimePatternGenerator dtpg; + + // DateTimePatternGenerator#getDefaultHourFormatChar + // DateTimePatternGenerator#setDefaultHourFormatChar + { + dtpg = DateTimePatternGenerator.getEmptyInstance(); + assertEquals("Default hour char on empty instance", 'H', dtpg.getDefaultHourFormatChar()); + dtpg.setDefaultHourFormatChar('e'); + assertEquals("Default hour char after explicit set", 'e', dtpg.getDefaultHourFormatChar()); + dtpg = DateTimePatternGenerator.getInstance(ULocale.ENGLISH); + assertEquals("Default hour char on populated English instance", 'h', dtpg.getDefaultHourFormatChar()); + } + + // DateTimePatternGenerator#getSkeletonAllowingDuplicates + // DateTimePatternGenerator#getCanonicalSkeletonAllowingDuplicates + // DateTimePatternGenerator#getCanonicalChar + { + dtpg = DateTimePatternGenerator.getInstance(ULocale.ENGLISH); + assertEquals("Example skeleton with no duplicate fields", "MMMdd", dtpg.getSkeleton("dd/MMM")); + assertEquals("Should return same result as getSkeleton with no duplicate fields", + dtpg.getSkeleton("dd/MMM"), dtpg.getSkeletonAllowingDuplicates("dd/MMM")); + + try { + dtpg.getSkeleton("dd/MMM Zz"); + fail("getSkeleton should throw upon duplicate fields"); + } catch(IllegalArgumentException e) { + assertEquals("getSkeleton should throw upon duplicate fields", + "Conflicting fields:\tZ, z\t in dd/MMM Zz", e.getMessage()); + } + + assertEquals("Should not throw upon duplicate fields", + "MMMddZ", dtpg.getSkeletonAllowingDuplicates("dd/MMM Zz")); + assertEquals("Should not throw upon duplicate fields and should return Canonical fields", + "MMMddv", dtpg.getCanonicalSkeletonAllowingDuplicates("dd/MMM Zz")); + } + + // DistanceInfo#toString + // DateTimePatternGenerator#showMask + try { + String actual = invokeToString("com.ibm.icu.text.DateTimePatternGenerator$DistanceInfo"); + assertEquals("DistanceInfo toString", "missingFieldMask: , extraFieldMask: ", actual); + } catch(Exception e) { + errln("Couldn't call DistanceInfo.toString(): " + e.toString()); + } + + // DateTimePatternGenerator#skeletonsAreSimilar + // DateTimePatternGenerator#getSet + { + dtpg = DateTimePatternGenerator.getInstance(ULocale.ENGLISH); + assertTrue("Trivial skeletonsAreSimilar", dtpg.skeletonsAreSimilar("MMMdd", "MMMdd")); + assertTrue("Different number of chars in skeletonsAreSimilar", dtpg.skeletonsAreSimilar("Mddd", "MMMdd")); + assertFalse("Failure case for skeletonsAreSimilar", dtpg.skeletonsAreSimilar("mmDD", "MMMdd")); + } + } + @Test public void TestEmptyInstance() { DateTimePatternGenerator dtpg = DateTimePatternGenerator.getEmptyInstance(); diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/MeasureUnitTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/MeasureUnitTest.java index c5498ad2927..ea8945d63af 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/MeasureUnitTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/MeasureUnitTest.java @@ -1401,6 +1401,10 @@ public class MeasureUnitTest extends TestFmwk { assertEquals("Wide currency", "-1.00\u7C73\u30C9\u30EB", mf.format(USD_NEG_1)); assertEquals("Wide currency", "1.00\u7C73\u30C9\u30EB", mf.format(USD_1)); assertEquals("Wide currency", "2.00\u7C73\u30C9\u30EB", mf.format(USD_2)); + + Measure CAD_1 = new Measure(1.0, Currency.getInstance("CAD")); + mf = MeasureFormat.getInstance(ULocale.CANADA, FormatWidth.SHORT); + assertEquals("short currency", "CAD1.00", mf.format(CAD_1)); } @Test diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/RelativeDateTimeFormatterTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/RelativeDateTimeFormatterTest.java index 05130a6ba14..95863977275 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/RelativeDateTimeFormatterTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/RelativeDateTimeFormatterTest.java @@ -904,6 +904,14 @@ public class RelativeDateTimeFormatterTest extends TestFmwk { "", DisplayContext.CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, fmt.getCapitalizationContext()); + + // test the no-arguments getInstance(); + RelativeDateTimeFormatter fmt_default = RelativeDateTimeFormatter.getInstance(); + assertEquals("", RelativeDateTimeFormatter.Style.LONG, fmt_default.getFormatStyle()); + assertEquals( + "", + DisplayContext.CAPITALIZATION_NONE, + fmt_default.getCapitalizationContext()); } @Test diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TestMessageFormat.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TestMessageFormat.java index f6dab6299cb..9160b960dba 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TestMessageFormat.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TestMessageFormat.java @@ -523,7 +523,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { result, fp); assertEquals("format", compareStr, result.toString()); - + Map map = new HashMap(); try{ msg.format("", map); @@ -989,15 +989,15 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { assertEquals("[" + (i/2) + "] \"" + patterns[i] + "\"", patterns[i+1], MessageFormat.autoQuoteApostrophe(patterns[i])); } } - - // This tests passing named arguments instead of numbers to format(). + + // This tests passing named arguments instead of numbers to format(). @Test public void testFormatNamedArguments() { Map arguments = new HashMap(); arguments.put("startDate", new Date(871068000000L)); StringBuffer result = new StringBuffer(); - + String formatStr = "On {startDate,date}, it began."; String compareStr = "On Aug 8, 1997, it began."; @@ -1017,9 +1017,9 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { fp); assertEquals("format", compareStr, result.toString()); } - + // This tests parsing formatted messages with named arguments instead of - // numbers. + // numbers. @Test public void testParseNamedArguments() { String msgFormatString = "{foo} =sep= {bar}"; @@ -1039,7 +1039,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } ParsePosition pp = new ParsePosition(0); - Map fmt_map = msg.parseToMap(source, pp); + Map fmt_map = msg.parseToMap(source, pp); if (pp.getIndex()==0 || fmt_map==null) { errln("*** MSG parse (ustring, parsepos., count) error."); } else { @@ -1052,7 +1052,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } pp.setIndex(0); - + Map fmta = (Map) msg.parseObject( source, pp ); if (pp.getIndex() == 0) { errln("*** MSG parse (ustring, Object, parsepos ) error."); @@ -1065,7 +1065,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } } } - + // Ensure that methods designed for numeric arguments only, will throw // an exception when called on MessageFormat objects created with // named arguments. @@ -1081,10 +1081,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } if (!gotException) { errln("MessageFormat.setFormatsByArgumentIndex() should throw an " + - "IllegalArgumentException when called on formats with " + + "IllegalArgumentException when called on formats with " + "named arguments but did not!"); } - + gotException = false; try { msg.setFormatByArgumentIndex(0, new DecimalFormat()); @@ -1093,10 +1093,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } if (!gotException) { errln("MessageFormat.setFormatByArgumentIndex() should throw an " + - "IllegalArgumentException when called on formats with " + + "IllegalArgumentException when called on formats with " + "named arguments but did not!"); } - + gotException = false; try { msg.getFormatsByArgumentIndex(); @@ -1105,10 +1105,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } if (!gotException) { errln("MessageFormat.getFormatsByArgumentIndex() should throw an " + - "IllegalArgumentException when called on formats with " + + "IllegalArgumentException when called on formats with " + "named arguments but did not!"); } - + gotException = false; try { Object args[] = {new Long(42)}; @@ -1118,10 +1118,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } if (!gotException) { errln("MessageFormat.format(Object[], StringBuffer, FieldPosition) " + - "should throw an IllegalArgumentException when called on " + + "should throw an IllegalArgumentException when called on " + "formats with named arguments but did not!"); } - + gotException = false; try { Object args[] = {new Long(42)}; @@ -1132,10 +1132,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { if (!gotException) { errln("MessageFormat.format(Object, StringBuffer, FieldPosition) " + "should throw an IllegalArgumentException when called with " + - "non-Map object as argument on formats with named " + + "non-Map object as argument on formats with named " + "arguments but did not!"); } - + gotException = false; try { msg.parse("Number of files: 5", new ParsePosition(0)); @@ -1145,10 +1145,10 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { if (!gotException) { errln("MessageFormat.parse(String, ParsePosition) " + "should throw an IllegalArgumentException when called with " + - "non-Map object as argument on formats with named " + + "non-Map object as argument on formats with named " + "arguments but did not!"); } - + gotException = false; try { msg.parse("Number of files: 5"); @@ -1160,11 +1160,11 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { if (!gotException) { errln("MessageFormat.parse(String) " + "should throw an IllegalArgumentException when called with " + - "non-Map object as argument on formats with named " + + "non-Map object as argument on formats with named " + "arguments but did not!"); } } - + @Test public void testNamedArguments() { // ICU 4.8 allows mixing named and numbered arguments. @@ -1184,34 +1184,34 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { if (!mf.usesNamedArguments()) { errln("message format 2 should have used named arguments"); } - + // Test argument names with invalid start characters. // Modified: ICU 4.8 allows all characters except for Pattern_White_Space and Pattern_Syntax. try { new MessageFormat("Wavelength: {^\u028EValue\uFF14}"); - errln("Creating a MessageFormat with invalid argument names " + + errln("Creating a MessageFormat with invalid argument names " + "should throw an IllegalArgumentException but did not!"); } catch (IllegalArgumentException e) {} - + try { new MessageFormat("Wavelength: {\uFE45\u028EValue}"); - errln("Creating a MessageFormat with invalid argument names " + + errln("Creating a MessageFormat with invalid argument names " + "should throw an IllegalArgumentException but did not!"); } catch (IllegalArgumentException e) {} - + // Test argument names with invalid continue characters. // Modified: ICU 4.8 allows all characters except for Pattern_White_Space and Pattern_Syntax. try { new MessageFormat("Wavelength: {Value@\uFF14}"); - errln("Creating a MessageFormat with invalid argument names " + + errln("Creating a MessageFormat with invalid argument names " + "should throw an IllegalArgumentException but did not!"); } catch (IllegalArgumentException e) {} - + try { new MessageFormat("Wavelength: {Value(\uFF14)}"); - errln("Creating a MessageFormat with invalid argument names " + + errln("Creating a MessageFormat with invalid argument names " + "should throw an IllegalArgumentException but did not!"); - } catch (IllegalArgumentException e) {} + } catch (IllegalArgumentException e) {} } @Test @@ -1300,7 +1300,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { public void testPluralFormat() { { MessageFormat mfNum = new MessageFormat( - "{0, plural, one{C''est # fichier} other " + + "{0, plural, one{C''est # fichier} other " + "{Ce sont # fichiers}} dans la liste.", new ULocale("fr")); MessageFormat mfAlpha = new MessageFormat( @@ -1312,7 +1312,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { objMap.put("argument", objArray[0]); String result = mfNum.format(objArray); if (!result.equals(mfAlpha.format(objMap))) { - errln("PluralFormat's output differs when using named " + + errln("PluralFormat's output differs when using named " + "arguments instead of numbers!"); } if (!result.equals("C'est 0 fichier dans la liste.")) { @@ -1327,7 +1327,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { new ULocale("uk")); MessageFormat mfAlpha = new MessageFormat ( "There {argument, plural, one{is # zavod}few{" + - "are {argument, number,###.0} zavoda} other{are # " + + "are {argument, number,###.0} zavoda} other{are # " + "zavodov}} in the directory.", new ULocale("uk")); Object objArray[] = {new Long(4)}; @@ -1335,7 +1335,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { objMap.put("argument", objArray[0]); String result = mfNum.format(objArray); if (!result.equals(mfAlpha.format(objMap))) { - errln("PluralFormat's output differs when using named " + + errln("PluralFormat's output differs when using named " + "arguments instead of numbers!"); } if (!result.equals("There are 4,0 zavoda in the directory.")) { @@ -1383,16 +1383,16 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { */ @Test public void testSelectFormat() { - String pattern = null; + String pattern = null; MessageFormat msgFmt = null ; - //Create the MessageFormat with simple French pattern - pattern = "{0} est {1, select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris."; + //Create the MessageFormat with simple French pattern + pattern = "{0} est {1, select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris."; msgFmt = new MessageFormat(pattern); assertNotNull( "ERROR:Failure in constructing with simple French pattern", msgFmt); - //Format - Object testArgs[][] ={ + //Format + Object testArgs[][] ={ {"Kirti","female"} , {"Victor","other"} , {"Ash","unknown"} , @@ -1404,7 +1404,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { }; for ( int i=0; i< 3; i++){ assertEquals("ERROR:Failure in format with simple French Pattern" , - exp[i] , msgFmt.format(testArgs[i]) ); + exp[i] , msgFmt.format(testArgs[i]) ); } //Create the MessageFormat with Quoted French Pattern @@ -1412,8 +1412,8 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { msgFmt = new MessageFormat(pattern); assertNotNull( "ERROR:Failure in constructing with quoted French pattern", msgFmt); - //Format - Object testArgs1[][] ={ + //Format + Object testArgs1[][] ={ {"Kirti","female"} , {"Victor","other"} , {"Ash","male"} , @@ -1425,7 +1425,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { }; for ( int i=0; i< 3; i++){ assertEquals("ERROR:Failure in format with quoted French Pattern" , - exp1[i] , msgFmt.format(testArgs1[i]) ); + exp1[i] , msgFmt.format(testArgs1[i]) ); } //Nested patterns with plural, number ,choice ,select format etc. @@ -1434,11 +1434,11 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { msgFmt = new MessageFormat(pattern); assertNotNull( "ERROR:Failure in constructing with nested pattern 1", msgFmt); - //Format - Object testArgs3[][] ={ + //Format + Object testArgs3[][] ={ {"Kirti", "female", 6} , {"Kirti", "female", 100.100} , - {"Kirti", "other", 6} , + {"Kirti", "other", 6} , }; String exp3[] = { "Kirti est 6 all\\u00E9e \\u00E0 Paris." , @@ -1448,7 +1448,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { for ( int i=0; i< 3; i++){ assertEquals("ERROR:Failure in format with nested Pattern 1" , - exp3[i] , msgFmt.format(testArgs3[i]) ); + exp3[i] , msgFmt.format(testArgs3[i]) ); } //Plural format with embedded select format @@ -1456,8 +1456,8 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { msgFmt = new MessageFormat(pattern); assertNotNull( "ERROR:Failure in constructing with nested pattern 2", msgFmt); - //Format - Object testArgs4[][] ={ + //Format + Object testArgs4[][] ={ {"Kirti",6,"female"}, {"Kirti",1,"female"}, {"Ash",1,"other"}, @@ -1471,16 +1471,16 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { }; for ( int i=0; i< 4; i++){ assertEquals("ERROR:Failure in format with nested Pattern 2" , - exp4[i] , msgFmt.format(testArgs4[i]) ); + exp4[i] , msgFmt.format(testArgs4[i]) ); } - //Select, plural, and number formats heavily nested + //Select, plural, and number formats heavily nested pattern = "{0} und {1, select, female {{2, plural, one {{3, select, female {ihre Freundin} other {ihr Freund}} } other {ihre {2, number, integer} {3, select, female {Freundinnen} other {Freunde}} } }} other{{2, plural, one {{3, select, female {seine Freundin} other {sein Freund}}} other {seine {2, number, integer} {3, select, female {Freundinnen} other {Freunde}}}}} } gingen nach Paris."; msgFmt = new MessageFormat(pattern); assertNotNull( "ERROR:Failure in constructing with nested pattern 3", msgFmt); - //Format - Object testArgs5[][] ={ + //Format + Object testArgs5[][] ={ {"Kirti","other",1,"other"}, {"Kirti","other",6,"other"}, {"Kirti","other",1,"female"}, @@ -1515,7 +1515,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { //Format for ( int i=0; i< 14; i++){ assertEquals("ERROR:Failure in format with nested Pattern 3" , - exp5[i] , msgFmt.format(testArgs5[i]) ); + exp5[i] , msgFmt.format(testArgs5[i]) ); } } @@ -1527,7 +1527,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { String[] patterns = { //Pattern with some text at start and at end "{0} est {1,select, female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris.", - //Pattern with some text at start + //Pattern with some text at start "{0} est {1,select, female {all\\u00E9e} other {all\\u00E9}}", //Pattern with some text at end "{1, select,female {all\\u00E9e} other {all\\u00E9}} \\u00E0 Paris.", @@ -1542,7 +1542,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { MessageFormat mf = new MessageFormat(pattern); MessageFormat mf2 = new MessageFormat(mf.toPattern()); if (!mf.equals(mf2)) { - errln("message formats not equal for pattern:\n*** '" + errln("message formats not equal for pattern:\n*** '" + pattern + "'\n*** '" + mf.toPattern() + "'"); } } @@ -1569,7 +1569,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } } } - + @Test public void TestSetFormat() { MessageFormat ms = new MessageFormat("{number} {date}", ULocale.ENGLISH); @@ -1734,7 +1734,7 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { } catch (Exception e) { } } - + /* * Tests the method public Format getFormatByArgumentName(String argumentName) */ @@ -2069,4 +2069,14 @@ public class TestMessageFormat extends com.ibm.icu.dev.test.TestFmwk { // Only simple API coverage. The parser implementation is tested via MessageFormat. assertTrue("many parts", pattern.countParts() > 10); } + + public void TestDateFormatHashCode() { + DateFormat testDF = DateFormat.getDateInstance(DateFormat.DEFAULT, ULocale.GERMAN); + NumberFormat testNF = testDF.getNumberFormat(); + + int expectedResult = + testNF.getMaximumIntegerDigits() * 37 + testNF.getMaximumFractionDigits(); + int actualHashResult = testDF.hashCode(); + assertEquals("DateFormat hashCode", expectedResult, actualHashResult); + } } diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TimeZoneFormatTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TimeZoneFormatTest.java index 23805ce2d5f..ba198d1de82 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TimeZoneFormatTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/format/TimeZoneFormatTest.java @@ -14,10 +14,12 @@ import java.text.ParseException; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Locale; +import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; @@ -37,6 +39,7 @@ import com.ibm.icu.text.TimeZoneFormat.ParseOption; import com.ibm.icu.text.TimeZoneFormat.Style; import com.ibm.icu.text.TimeZoneFormat.TimeType; import com.ibm.icu.text.TimeZoneNames; +import com.ibm.icu.text.TimeZoneNames.Factory; import com.ibm.icu.text.TimeZoneNames.NameType; import com.ibm.icu.util.BasicTimeZone; import com.ibm.icu.util.Calendar; @@ -1119,12 +1122,137 @@ public class TimeZoneFormatTest extends com.ibm.icu.dev.test.TestFmwk { } } + @Test + public void TestGetDisplayNames() { + long date = System.currentTimeMillis(); + NameType[] types = new NameType[]{ + NameType.LONG_STANDARD, NameType.LONG_DAYLIGHT, + NameType.SHORT_STANDARD, NameType.SHORT_DAYLIGHT + }; + Set zones = ZoneMeta.getAvailableIDs(SystemTimeZoneType.ANY, null, null); + + int casesTested = 0; + Random rnd = new Random(2016); + for (ULocale uloc : ULocale.getAvailableLocales()) { + if (rnd.nextDouble() > 0.01) { continue; } + for (String zone : zones) { + if (rnd.nextDouble() > 0.01) { continue; } + casesTested++; + + // Test default TimeZoneNames (uses an overridden getDisplayNames) + { + TimeZoneNames tznames = TimeZoneNames.getInstance(uloc); + tznames.loadAllDisplayNames(); + String[] result = new String[types.length]; + tznames.getDisplayNames(zone, types, date, result, 0); + for (int i=0; i 0); + } + + class TimeZoneNamesInheriter extends TimeZoneNames { + @Override + public Set getAvailableMetaZoneIDs() { + return null; + } + + @Override + public Set getAvailableMetaZoneIDs(String tzID) { + return null; + } + + @Override + public String getMetaZoneID(String tzID, long date) { + return null; + } + + @Override + public String getReferenceZoneID(String mzID, String region) { + return null; + } + + @Override + public String getMetaZoneDisplayName(String mzID, NameType type) { + return null; + } + + @Override + public String getTimeZoneDisplayName(String tzID, NameType type) { + return null; + } + } + + // Coverage for default implementation and abstract methods in base class. + @Test + public void TestDefaultTimeZoneNames() { + long date = System.currentTimeMillis(); + TimeZoneNames.Factory factory; + try { + Class cls = Class.forName("com.ibm.icu.text.TimeZoneNames$DefaultTimeZoneNames$FactoryImpl"); + factory = (Factory) cls.newInstance(); + } catch (Exception e) { + errln("Could not create class DefaultTimeZoneNames.FactoryImpl: " + e.getClass() + ": " + e.getMessage()); + return; + } + TimeZoneNames tzn = factory.getTimeZoneNames(ULocale.ENGLISH); + assertEquals("Abstract: getAvailableMetaZoneIDs()", + tzn.getAvailableMetaZoneIDs(), Collections.emptySet()); + assertEquals("Abstract: getAvailableMetaZoneIDs(String tzID)", + tzn.getAvailableMetaZoneIDs("America/Chicago"), Collections.emptySet()); + assertEquals("Abstract: getMetaZoneID(String tzID, long date)", + tzn.getMetaZoneID("America/Chicago", date), null); + assertEquals("Abstract: getReferenceZoneID(String mzID, String region)", + tzn.getReferenceZoneID("America_Central", "IT"), null); + assertEquals("Abstract: getMetaZoneDisplayName(String mzID, NameType type)", + tzn.getMetaZoneDisplayName("America_Central", NameType.LONG_DAYLIGHT), null); + assertEquals("Abstract: getTimeZoneDisplayName(String mzID, NameType type)", + tzn.getTimeZoneDisplayName("America/Chicago", NameType.LONG_DAYLIGHT), null); + assertEquals("Abstract: find(CharSequence text, int start, EnumSet nameTypes)", + tzn.find("foo", 0, EnumSet.noneOf(NameType.class)), Collections.emptyList()); + + // Other abstract-class methods that aren't covered + tzn = new TimeZoneNamesInheriter(); + try { + tzn.find(null, 0, null); + } catch (UnsupportedOperationException e) { + assertEquals("find() exception", "The method is not implemented in TimeZoneNames base class.", e.getMessage()); + } + } + // Basic get/set test for methods not being called otherwise. @Test public void TestAPI() { TimeZoneFormat tzfmtEn = TimeZoneFormat.getInstance(ULocale.ENGLISH); TimeZoneFormat tzfmtAr = TimeZoneFormat.getInstance(new ULocale("ar")).cloneAsThawed(); - TimeZoneNames tzn = TimeZoneNames.getInstance(ULocale.ENGLISH); + TimeZoneNames tzn = TimeZoneNames.getInstance(Locale.ENGLISH); String digits = tzfmtEn.getGMTOffsetDigits(); tzfmtAr.setGMTOffsetDigits(digits); @@ -1153,5 +1281,26 @@ public class TimeZoneFormatTest extends com.ibm.icu.dev.test.TestFmwk { if (!kinshasaAvailableMZIDs.contains("Africa_Western") || kinshasaAvailableMZIDs.contains("America_Central")) { errln("ERROR: getAvailableMetaZoneIDs('Africa/Kinshasa') did not return expected value"); } + + try { + new TimeZoneNames.MatchInfo(null, null, null, -1); + assertTrue("MatchInfo doesn't throw IllegalArgumentException", false); + } catch (IllegalArgumentException e) { + assertEquals("MatchInfo constructor exception", "nameType is null", e.getMessage()); + } + + try { + new TimeZoneNames.MatchInfo(NameType.LONG_GENERIC, null, null, -1); + assertTrue("MatchInfo doesn't throw IllegalArgumentException", false); + } catch (IllegalArgumentException e) { + assertEquals("MatchInfo constructor exception", "Either tzID or mzID must be available", e.getMessage()); + } + + try { + new TimeZoneNames.MatchInfo(NameType.LONG_GENERIC, "America/Chicago", null, -1); + assertTrue("MatchInfo doesn't throw IllegalArgumentException", false); + } catch (IllegalArgumentException e) { + assertEquals("MatchInfo constructor exception", "matchLength must be positive value", e.getMessage()); + } } } diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/AbstractBreakIteratorTests.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/AbstractBreakIteratorTests.java new file mode 100644 index 00000000000..0ba50e8e941 --- /dev/null +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/AbstractBreakIteratorTests.java @@ -0,0 +1,107 @@ +// © 2016 and later: Unicode, Inc. and others. +// License & terms of use: http://www.unicode.org/copyright.html#License +package com.ibm.icu.dev.test.rbbi; + +import java.text.CharacterIterator; + +import org.junit.Before; +import org.junit.Test; + +import com.ibm.icu.dev.test.TestFmwk; +import com.ibm.icu.text.BreakIterator; + +/** + * @author sgill + * + */ +public class AbstractBreakIteratorTests extends TestFmwk { + + private class AbstractBreakIterator extends BreakIterator { + private int position = 0; + private static final int LIMIT = 100; + + private int set(int n) { + position = n; + if (position > LIMIT) { + position = LIMIT; + return DONE; + } + if (position < 0) { + position = 0; + return DONE; + } + return position; + } + + @Override + public int first() { + return set(0); + } + + @Override + public int last() { + return set(LIMIT); + } + + @Override + public int next(int n) { + return set(position + n); + } + + @Override + public int next() { + return next(1); + } + + @Override + public int previous() { + return next(-1); + } + + @Override + public int following(int offset) { + return set(offset + 1); + } + + @Override + public int current() { + return position; + } + + @Override + public CharacterIterator getText() { + return null; + } + + @Override + public void setText(CharacterIterator newText) { + } + + } + + private BreakIterator bi; + + @Before + public void createBreakIterator() { + bi = new AbstractBreakIterator(); + } + + @Test + public void testPreceding() { + int pos = bi.preceding(0); + TestFmwk.assertEquals("BreakIterator preceding position not correct", BreakIterator.DONE, pos); + + pos = bi.preceding(5); + TestFmwk.assertEquals("BreakIterator preceding position not correct", 4, pos); + } + + @Test + public void testIsBoundary() { + boolean b = bi.isBoundary(0); + TestFmwk.assertTrue("BreakIterator is boundary not correct", b); + + b = bi.isBoundary(5); + TestFmwk.assertTrue("BreakIterator is boundary not correct", b); + } + +} diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/RBBIAPITest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/RBBIAPITest.java index f20d2d007b9..01ef72d00c8 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/RBBIAPITest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/rbbi/RBBIAPITest.java @@ -7,19 +7,22 @@ ******************************************************************************* */ -/** +/** * Port From: ICU4C v1.8.1 : rbbi : RBBIAPITest * Source File: $ICU4CRoot/source/test/intltest/rbbiapts.cpp **/ package com.ibm.icu.dev.test.rbbi; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.Locale; import org.junit.Test; +import com.ibm.icu.dev.test.TestFmwk; import com.ibm.icu.text.BreakIterator; import com.ibm.icu.text.RuleBasedBreakIterator; import com.ibm.icu.util.ULocale; @@ -29,20 +32,20 @@ import com.ibm.icu.util.ULocale; */ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { /** - * Tests clone() and equals() methods of RuleBasedBreakIterator + * Tests clone() and equals() methods of RuleBasedBreakIterator **/ @Test public void TestCloneEquals() { - RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - RuleBasedBreakIterator biequal = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - RuleBasedBreakIterator bi3 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - RuleBasedBreakIterator bi2 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); + RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator biequal = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator bi3 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator bi2 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); String testString = "Testing word break iterators's clone() and equals()"; bi1.setText(testString); bi2.setText(testString); biequal.setText(testString); - + bi3.setText("hello"); logln("Testing equals()"); logln("Testing == and !="); @@ -70,13 +73,13 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { || bi2clone.equals(bi1clone)) errln("ERROR: RBBI's clone() method failed"); } - + /** * Tests toString() method of RuleBasedBreakIterator **/ @Test public void TestToString() { - RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); RuleBasedBreakIterator bi2 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); logln("Testing toString()"); bi1.setText("Hello there"); @@ -87,14 +90,14 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { if (temp2.equals(temp3) || temp.equals(temp2) || !temp.equals(temp3)) errln("ERROR: error in toString() method"); } - + /** * Tests the method hashCode() of RuleBasedBreakIterator **/ @Test public void TestHashCode() { - RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - RuleBasedBreakIterator bi3 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator bi1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator bi3 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); RuleBasedBreakIterator bi2 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); logln("Testing hashCode()"); bi1.setText("Hash code"); @@ -107,14 +110,14 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { || bi1clone.hashCode() != bi3.hashCode() || bi2.hashCode() != bi2clone.hashCode()) errln("ERROR: identical objects have different hashcodes"); - + if (bi1.hashCode() == bi2.hashCode() || bi2.hashCode() == bi3.hashCode() || bi1clone.hashCode() == bi2clone.hashCode() || bi1clone.hashCode() == bi2.hashCode()) errln("ERROR: different objects have same hashcodes"); } - + /** * Tests the methods getText() and setText() of RuleBasedBreakIterator **/ @@ -123,8 +126,8 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { logln("Testing getText setText "); String str1 = "first string."; String str2 = "Second string."; - //RuleBasedBreakIterator charIter1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - RuleBasedBreakIterator wordIter1 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); + //RuleBasedBreakIterator charIter1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + RuleBasedBreakIterator wordIter1 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); CharacterIterator text1 = new StringCharacterIterator(str1); //CharacterIterator text1Clone = (CharacterIterator) text1.clone(); //CharacterIterator text2 = new StringCharacterIterator(str2); @@ -133,12 +136,12 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { errln("ERROR:1 error in setText or getText "); if (wordIter1.current() != 0) errln("ERROR:1 setText did not set the iteration position to the beginning of the text, it is" - + wordIter1.current() + "\n"); + + wordIter1.current() + "\n"); wordIter1.next(2); wordIter1.setText(str2); if (wordIter1.current() != 0) errln("ERROR:2 setText did not reset the iteration position to the beginning of the text, it is" - + wordIter1.current() + "\n"); + + wordIter1.current() + "\n"); //ICU4J has remove the method adoptText /* charIter1.adoptText(text1Clone); @@ -146,7 +149,7 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { || wordIter1.getText() != text2 || charIter1.getText() != text1) errln((UnicodeString) "ERROR:2 error is getText or setText()"); - + RuleBasedBreakIterator rb = (RuleBasedBreakIterator) wordIter1.clone(); rb.adoptText(text1); if (rb.getText() != text1) @@ -156,7 +159,7 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { errln((UnicodeString) "ERROR:2 error in adoptText "); */ } - + /** * Testing the methods first(), next(), next(int) and following() of RuleBasedBreakIterator * TODO: Most of this test should be retired, rule behavior is much better covered by @@ -193,9 +196,9 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { q = wordIter1.following(wordIter1.last()); if (p != BreakIterator.DONE || q != BreakIterator.DONE) errln("ERROR: next()/following() at last position returned #" - + p + " and " + q + " instead of" + testString.length() + "\n"); - RuleBasedBreakIterator charIter1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); - testString = "Write hindi here. "; + + p + " and " + q + " instead of" + testString.length() + "\n"); + RuleBasedBreakIterator charIter1 = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance(Locale.getDefault()); + testString = "Write hindi here. "; logln("testing char iter - string:- \"" + testString + "\""); charIter1.setText(testString); p = charIter1.first(); @@ -219,9 +222,9 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { q = charIter1.next(charIter1.last()); if (p != BreakIterator.DONE || q != BreakIterator.DONE) errln("ERROR: following()/next() at last position returned #" - + p + " and " + q + " instead of" + testString.length()); - testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This costs $20,00,000."; - RuleBasedBreakIterator sentIter1 = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance(Locale.getDefault()); + + p + " and " + q + " instead of" + testString.length()); + testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This costs $20,00,000."; + RuleBasedBreakIterator sentIter1 = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance(Locale.getDefault()); logln("testing sentence iter - String:- \"" + testString + "\""); sentIter1.setText(testString); p = sentIter1.first(); @@ -251,10 +254,10 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { q = sentIter1.next(sentIter1.last()); if (p != BreakIterator.DONE || q != BreakIterator.DONE) errln("ERROR: following()/next() at last position returned #" - + p + " and " + q + " instead of" + testString.length()); - testString = "Hello! how\r\n (are)\r you? I'am fine- Thankyou. foo\u00a0bar How, are, you? This, costs $20,00,000."; + + p + " and " + q + " instead of" + testString.length()); + testString = "Hello! how\r\n (are)\r you? I'am fine- Thankyou. foo\u00a0bar How, are, you? This, costs $20,00,000."; logln("(UnicodeString)testing line iter - String:- \"" + testString + "\""); - RuleBasedBreakIterator lineIter1 = (RuleBasedBreakIterator) BreakIterator.getLineInstance(Locale.getDefault()); + RuleBasedBreakIterator lineIter1 = (RuleBasedBreakIterator) BreakIterator.getLineInstance(Locale.getDefault()); lineIter1.setText(testString); p = lineIter1.first(); if (p != 0) @@ -289,9 +292,9 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { q = lineIter1.next(lineIter1.last()); if (p != BreakIterator.DONE || q != BreakIterator.DONE) errln("ERROR: following()/next() at last position returned #" - + p + " and " + q + " instead of" + testString.length()); + + p + " and " + q + " instead of" + testString.length()); } - + /** * Testing the methods lastt(), previous(), and preceding() of RuleBasedBreakIterator **/ @@ -301,7 +304,7 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { String testString = "This is a word break. Isn't it? 2.25 dollars"; logln("Testing last(),previous(), preceding() with custom rules"); logln("testing word iteration for string \"" + testString + "\""); - RuleBasedBreakIterator wordIter1 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); + RuleBasedBreakIterator wordIter1 = (RuleBasedBreakIterator) BreakIterator.getWordInstance(Locale.getDefault()); wordIter1.setText(testString); p = wordIter1.last(); if (p != testString.length()) { @@ -322,9 +325,9 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { p = wordIter1.preceding(wordIter1.first()); if (p != BreakIterator.DONE) errln("ERROR: preceding() at starting position returned #" + p + " instead of 0"); - testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This costs $20,00,000."; + testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This costs $20,00,000."; logln("testing sentence iter - String:- \"" + testString + "\""); - RuleBasedBreakIterator sentIter1 = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance(Locale.getDefault()); + RuleBasedBreakIterator sentIter1 = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance(Locale.getDefault()); sentIter1.setText(testString); p = sentIter1.last(); if (p != testString.length()) @@ -343,8 +346,8 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { q = sentIter1.preceding(sentIter1.first()); if (p != BreakIterator.DONE || q != BreakIterator.DONE) errln("ERROR: previous()/preceding() at starting position returned #" - + p + " and " + q + " instead of 0\n"); - testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This\n costs $20,00,000."; + + p + " and " + q + " instead of 0\n"); + testString = "Hello! how are you? I'am fine. Thankyou. How are you doing? This\n costs $20,00,000."; logln("testing line iter - String:- \"" + testString + "\""); RuleBasedBreakIterator lineIter1 = (RuleBasedBreakIterator) BreakIterator.getLineInstance(Locale.getDefault()); lineIter1.setText(testString); @@ -367,7 +370,7 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { errln("ERROR: previous()/preceding() at starting position returned #" + p + " and " + q + " instead of 0\n"); } - + /** * Tests the method IsBoundary() of RuleBasedBreakIterator **/ @@ -383,48 +386,60 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { int bounds2[] = {0, 5, 6, 10, 11, 12, 16, 17, 22, 23, 26}; doBoundaryTest(wordIter2, testString1, bounds2); } - + /** * Tests the rule status return value constants */ @Test public void TestRuleStatus() { BreakIterator bi = BreakIterator.getWordInstance(ULocale.ENGLISH); - + bi.setText("# "); assertEquals(null, bi.next(), 1); assertTrue(null, bi.getRuleStatus() >= RuleBasedBreakIterator.WORD_NONE); assertTrue(null, bi.getRuleStatus() < RuleBasedBreakIterator.WORD_NONE_LIMIT); - + bi.setText("3 "); assertEquals(null, bi.next(), 1); assertTrue(null, bi.getRuleStatus() >= RuleBasedBreakIterator.WORD_NUMBER); assertTrue(null, bi.getRuleStatus() < RuleBasedBreakIterator.WORD_NUMBER_LIMIT); - + bi.setText("a "); assertEquals(null, bi.next(), 1); assertTrue(null, bi.getRuleStatus() >= RuleBasedBreakIterator.WORD_LETTER ); assertTrue(null, bi.getRuleStatus() < RuleBasedBreakIterator.WORD_LETTER_LIMIT); - + bi.setText("イ "); assertEquals(null, bi.next(), 1); assertTrue(null, bi.getRuleStatus() >= RuleBasedBreakIterator.WORD_KANA ); // TODO: ticket #10261, Kana is not returning the correct status. // assertTrue(null, bi.getRuleStatus() < RuleBasedBreakIterator.WORD_KANA_LIMIT); // System.out.println("\n" + bi.getRuleStatus()); - + bi.setText("退 "); assertEquals(null, bi.next(), 1); assertTrue(null, bi.getRuleStatus() >= RuleBasedBreakIterator.WORD_IDEO ); assertTrue(null, bi.getRuleStatus() < RuleBasedBreakIterator.WORD_IDEO_LIMIT); } - + + /** + * Tests the rule dump debug function. + */ + @Test + public void TestRuledump() { + RuleBasedBreakIterator bi = (RuleBasedBreakIterator)BreakIterator.getCharacterInstance(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bos); + bi.dump(out); + assertTrue(null, bos.size() > 100); + } + //--------------------------------------------- //Internal subroutines //--------------------------------------------- - - /* Internal subroutine used by TestIsBoundary() */ + + /* Internal subroutine used by TestIsBoundary() */ private void doBoundaryTest(BreakIterator bi, String text, int[] boundaries) { logln("testIsBoundary():"); int p = 0; @@ -442,7 +457,7 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { } } } - + /*Internal subroutine used for comparision of expected and acquired results */ private void doTest(String testString, int start, int gotoffset, int expectedOffset, String expectedString) { String selected; @@ -459,4 +474,12 @@ public class RBBIAPITest extends com.ibm.icu.dev.test.TestFmwk { else logln("****selected \"" + selected + "\""); } + + @Test + public void testGetTitleInstance() { + BreakIterator bi = BreakIterator.getTitleInstance(new Locale("en", "CA")); + TestFmwk.assertNotEquals("Title instance break iterator not correctly instantiated", bi.first(), null); + bi.setText("Here is some Text"); + TestFmwk.assertEquals("Title instance break iterator not correctly instantiated", bi.first(), 0); + } } diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/shaping/ArabicShapingRegTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/shaping/ArabicShapingRegTest.java index b5bc0ad977e..ea40727c99f 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/shaping/ArabicShapingRegTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/shaping/ArabicShapingRegTest.java @@ -9,8 +9,10 @@ package com.ibm.icu.dev.test.shaping; +import java.lang.reflect.Method; import java.util.MissingResourceException; +import com.sun.org.apache.xpath.internal.operations.Bool; import org.junit.Test; import com.ibm.icu.dev.test.TestFmwk; @@ -294,24 +296,30 @@ public class ArabicShapingRegTest extends TestFmwk { "\ufe8f\u0655\ufeae\u0655\ufecb\u0020"), TestData.standard(tashkeelShaddaRTL, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_BEGIN |ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , - "\u0020\ufeb7\ufe7d\ufee4\ufeb2"), - TestData.standard(tashkeelShaddaRTL, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_END|ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , - "\ufeb7\ufe7d\ufee4\ufeb2\u0020"), - TestData.standard(tashkeelShaddaRTL, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_RESIZE|ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , - "\ufeb7\ufe7d\ufee4\ufeb2"), - - TestData.standard(tashkeelShaddaLTR, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_BEGIN |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , - "\u0020\ufeb2\ufee4\ufe7d\ufeb7"), - TestData.standard(tashkeelShaddaLTR, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_END |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , - "\ufeb2\ufee4\ufe7d\ufeb7\u0020"), - TestData.standard(tashkeelShaddaLTR, - ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_RESIZE |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , - "\ufeb2\ufee4\ufe7d\ufeb7"), + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_BEGIN |ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , + "\u0020\ufeb7\ufe7d\ufee4\ufeb2"), + TestData.standard(tashkeelShaddaRTL, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_END|ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , + "\ufeb7\ufe7d\ufee4\ufeb2\u0020"), + TestData.standard(tashkeelShaddaRTL, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_RESIZE|ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , + "\ufeb7\ufe7d\ufee4\ufeb2"), + TestData.standard(tashkeelShaddaRTL, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_REPLACE_BY_TATWEEL|ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , + "\ufeb7\ufe7d\ufee4\u0640\ufeb2"), + + TestData.standard(tashkeelShaddaLTR, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_BEGIN |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , + "\u0020\ufeb2\ufee4\ufe7d\ufeb7"), + TestData.standard(tashkeelShaddaLTR, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_END |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , + "\ufeb2\ufee4\ufe7d\ufeb7\u0020"), + TestData.standard(tashkeelShaddaLTR, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_RESIZE |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , + "\ufeb2\ufee4\ufe7d\ufeb7"), + TestData.standard(tashkeelShaddaLTR, + ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_REPLACE_BY_TATWEEL |ArabicShaping.TEXT_DIRECTION_VISUAL_LTR , + "\ufeb2\u0640\ufee4\ufe7d\ufeb7"), TestData.standard(ArMathSym, ArabicShaping.LETTERS_SHAPE|ArabicShaping.TASHKEEL_BEGIN |ArabicShaping.TEXT_DIRECTION_VISUAL_RTL , @@ -739,5 +747,52 @@ public class ArabicShapingRegTest extends TestFmwk { } catch (Exception e) {} } } + + @Test + public void TestCoverage() { + ArabicShaping shp = new ArabicShaping(LETTERS_SHAPE | TEXT_DIRECTION_VISUAL_LTR | LENGTH_FIXED_SPACES_NEAR); + + // Test ArabicShaping#toString(); + assertEquals("ArabicShaping#toString() failed.", + shp.toString(), + "com.ibm.icu.text.ArabicShaping@d[LamAlef spaces at near, visual, shape letters," + + " no digit shaping, standard Arabic-Indic digits]"); + + // Test ArabicShaping#hashCode() + assertEquals("ArabicShaping#hashCode() failed.", shp.hashCode(), 13); + } + + private boolean getStaticCharacterHelperFunctionValue(String methodName, char testValue) throws Exception { + Method m = ArabicShaping.class.getDeclaredMethod(methodName, Character.TYPE); + m.setAccessible(true); + Object returnValue = m.invoke(null, testValue); + + if (Integer.class.isInstance(returnValue)) { + return (Integer)returnValue == 1; + } + return (Boolean)returnValue; + } + + @Test + public void TestHelperFunctions() throws Exception { + // Test private static helper functions that are used internally: + + // ArabicShaping.isSeenTailFamilyChar(char) + assertTrue("ArabicShaping.isSeenTailFamilyChar(char) failed.", + getStaticCharacterHelperFunctionValue("isSeenTailFamilyChar", (char)0xfeb1)); + + // ArabicShaping.isAlefMaksouraChar(char) + assertTrue("ArabicShaping.isAlefMaksouraChar(char) failed.", + getStaticCharacterHelperFunctionValue("isAlefMaksouraChar", (char)0xfeef)); + + // ArabicShaping.isTailChar(char) + assertTrue("ArabicShaping.isTailChar(char) failed.", + getStaticCharacterHelperFunctionValue("isTailChar", (char)0x200B)); + + // ArabicShaping.isYehHamzaChar(char) + assertTrue("ArabicShaping.isYehHamzaChar(char) failed.", + getStaticCharacterHelperFunctionValue("isYehHamzaChar", (char)0xfe89)); + + } } diff --git a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/util/CurrencyTest.java b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/util/CurrencyTest.java index aa2a445f24e..d0f5f612b6d 100644 --- a/icu4j/main/tests/core/src/com/ibm/icu/dev/test/util/CurrencyTest.java +++ b/icu4j/main/tests/core/src/com/ibm/icu/dev/test/util/CurrencyTest.java @@ -165,7 +165,7 @@ public class CurrencyTest extends TestFmwk { if (found) { errln("found locale" + fu_FU + " in currency locales after unregister"); } - + Locale[] locs = Currency.getAvailableLocales(); found = false; for (int i = 0; i < locs.length; ++i) { @@ -220,14 +220,14 @@ public class CurrencyTest extends TestFmwk { "$", usd.getSymbol()); } - + // A real test of the CurrencyDisplayNames class. @Test public void TestCurrencyDisplayNames() { if (!CurrencyDisplayNames.hasData()) { errln("hasData() should return true."); } - + // with substitute CurrencyDisplayNames cdn = CurrencyDisplayNames.getInstance(ULocale.GERMANY); assertEquals("de_USD_name", "US-Dollar", cdn.getName("USD")); @@ -235,22 +235,22 @@ public class CurrencyTest extends TestFmwk { assertEquals("de_USD_plural_other", "US-Dollar", cdn.getPluralName("USD", "other")); // unknown plural category, substitute "other" assertEquals("de_USD_plural_foo", "US-Dollar", cdn.getPluralName("USD", "foo")); - + cdn = CurrencyDisplayNames.getInstance(ULocale.forLanguageTag("en-US")); assertEquals("en-US_USD_name", "US Dollar", cdn.getName("USD")); assertEquals("en-US_USD_symbol", "$", cdn.getSymbol("USD")); assertEquals("en-US_USD_plural_one", "US dollar", cdn.getPluralName("USD", "one")); assertEquals("en-US_USD_plural_other", "US dollars", cdn.getPluralName("USD", "other")); - + assertEquals("en-US_FOO_name", "FOO", cdn.getName("FOO")); assertEquals("en-US_FOO_symbol", "FOO", cdn.getSymbol("FOO")); assertEquals("en-US_FOO_plural_other", "FOO", cdn.getPluralName("FOO", "other")); - + assertEquals("en-US bundle", "en", cdn.getULocale().toString()); - + cdn = CurrencyDisplayNames.getInstance(ULocale.forLanguageTag("zz-Gggg-YY")); assertEquals("bundle from current locale", "en", cdn.getULocale().toString()); - + // with no substitute cdn = CurrencyDisplayNames.getInstance(ULocale.GERMANY, true); assertNotNull("have currency data for Germany", cdn); @@ -259,16 +259,16 @@ public class CurrencyTest extends TestFmwk { assertEquals("de_USD_name", "US-Dollar", cdn.getName("USD")); assertEquals("de_USD_symbol", "$", cdn.getSymbol("USD")); assertEquals("de_USD_plural_other", "US-Dollar", cdn.getPluralName("USD", "other")); - + // known currency but unknown plural category assertNull("de_USD_plural_foo", cdn.getPluralName("USD", "foo")); - + // unknown currency, get null assertNull("de_FOO_name", cdn.getName("FOO")); assertNull("de_FOO_symbol", cdn.getSymbol("FOO")); assertNull("de_FOO_plural_other", cdn.getPluralName("FOO", "other")); assertNull("de_FOO_plural_foo", cdn.getPluralName("FOO", "foo")); - + // unknown locale with no substitute cdn = CurrencyDisplayNames.getInstance(ULocale.forLanguageTag("zz-Gggg-YY"), true); String ln = ""; @@ -283,7 +283,7 @@ public class CurrencyTest extends TestFmwk { assertEquals("de_USD_name (Locale)", "US-Dollar", cdn.getName("USD")); assertNull("de_FOO_name (Locale)", cdn.getName("FOO")); } - + // Coverage-only test of CurrencyData @Test public void TestCurrencyData() { @@ -292,66 +292,66 @@ public class CurrencyTest extends TestFmwk { errln("getWithFallback() returned null."); return; } - + CurrencyData.DefaultInfo info_nofallback = (CurrencyData.DefaultInfo)CurrencyData.DefaultInfo.getWithFallback(false); if (info_nofallback == null) { errln("getWithFallback() returned null."); return; } - + if (!info_fallback.getName("isoCode").equals("isoCode") || info_nofallback.getName("isoCode") != null) { errln("Error calling getName()."); return; } - + if (!info_fallback.getPluralName("isoCode", "type").equals("isoCode") || info_nofallback.getPluralName("isoCode", "type") != null) { errln("Error calling getPluralName()."); return; } - + if (!info_fallback.getSymbol("isoCode").equals("isoCode") || info_nofallback.getSymbol("isoCode") != null) { errln("Error calling getSymbol()."); return; } - + if (!info_fallback.symbolMap().isEmpty()) { errln("symbolMap() should return empty map."); return; } - + if (!info_fallback.nameMap().isEmpty()) { errln("nameMap() should return empty map."); return; } - + if (!info_fallback.getUnitPatterns().isEmpty() || info_nofallback.getUnitPatterns() != null) { errln("Error calling getUnitPatterns()."); return; } - + if (!info_fallback.getSpacingInfo().equals((CurrencyData.CurrencySpacingInfo.DEFAULT)) || info_nofallback.getSpacingInfo() != null) { errln("Error calling getSpacingInfo()."); return; } - + if (info_fallback.getULocale() != ULocale.ROOT) { errln("Error calling getLocale()."); return; } - + if (info_fallback.getFormatInfo("isoCode") != null) { errln("Error calling getFormatInfo()."); return; } } - + // A real test of CurrencyMetaInfo. @Test public void testCurrencyMetaInfoRanges() { CurrencyMetaInfo metainfo = CurrencyMetaInfo.getInstance(true); assertNotNull("have metainfo", metainfo); - + CurrencyFilter filter = CurrencyFilter.onRegion("DE"); // must be capitalized List currenciesInGermany = metainfo.currencyInfo(filter); logln("currencies: " + currenciesInGermany.size()); @@ -369,17 +369,17 @@ public class CurrencyTest extends TestFmwk { eurFirstDate = new Date(info.from); } } - + // the Euro and Deutschmark overlapped for several years assertEquals("DEM available at last date", 2, metainfo.currencyInfo(filter.withDate(demLastDate)).size()); - + // demLastDate + 1 millisecond is not the start of the last day, we consider it the next day, so... Date demLastDatePlus1ms = new Date(demLastDate.getTime() + 1); assertEquals("DEM not available after very start of last date", 1, metainfo.currencyInfo(filter.withDate(demLastDatePlus1ms)).size()); - + // both available for start of euro assertEquals("EUR available on start of first date", 2, metainfo.currencyInfo(filter.withDate(eurFirstDate)).size()); - + // but not one millisecond before the start of the first day Date eurFirstDateMinus1ms = new Date(eurFirstDate.getTime() - 1); assertEquals("EUR not avilable before very start of first date", 1, metainfo.currencyInfo(filter.withDate(eurFirstDateMinus1ms)).size()); @@ -392,7 +392,7 @@ public class CurrencyTest extends TestFmwk { assertEquals("minute is 59", 59, cal.get(GregorianCalendar.MINUTE)); assertEquals("second is 59", 59, cal.get(GregorianCalendar.SECOND)); assertEquals("millisecond is 999", 999, cal.get(GregorianCalendar.MILLISECOND)); - + // start time is first millisecond of day cal.setTime(eurFirstDate); assertEquals("hour is 0", 0, cal.get(GregorianCalendar.HOUR_OF_DAY)); @@ -400,12 +400,12 @@ public class CurrencyTest extends TestFmwk { assertEquals("second is 0", 0, cal.get(GregorianCalendar.SECOND)); assertEquals("millisecond is 0", 0, cal.get(GregorianCalendar.MILLISECOND)); } - + @Test public void testCurrencyMetaInfoRangesWithLongs() { CurrencyMetaInfo metainfo = CurrencyMetaInfo.getInstance(true); assertNotNull("have metainfo", metainfo); - + CurrencyFilter filter = CurrencyFilter.onRegion("DE"); // must be capitalized List currenciesInGermany = metainfo.currencyInfo(filter); logln("currencies: " + currenciesInGermany.size()); @@ -421,19 +421,19 @@ public class CurrencyTest extends TestFmwk { } // the Euro and Deutschmark overlapped for several years assertEquals("DEM available at last date", 2, metainfo.currencyInfo(filter.withDate(demLastDate)).size()); - + // demLastDate + 1 millisecond is not the start of the last day, we consider it the next day, so... long demLastDatePlus1ms = demLastDate + 1; assertEquals("DEM not available after very start of last date", 1, metainfo.currencyInfo(filter.withDate(demLastDatePlus1ms)).size()); - + // both available for start of euro assertEquals("EUR available on start of first date", 2, metainfo.currencyInfo(filter.withDate(eurFirstDate)).size()); - + // but not one millisecond before the start of the first day long eurFirstDateMinus1ms = eurFirstDate - 1; assertEquals("EUR not avilable before very start of first date", 1, metainfo.currencyInfo(filter.withDate(eurFirstDateMinus1ms)).size()); } - + @Test public void TestWithTender() { CurrencyMetaInfo metainfo = CurrencyMetaInfo.getInstance(); @@ -450,7 +450,7 @@ public class CurrencyTest extends TestFmwk { Arrays.asList(new String[] {"CHF", "CHE", "CHW"}), metainfo.currencies(filter.withTender())); } - + // Coverage-only test of the CurrencyMetaInfo class @Test public void TestCurrencyMetaInfo() { @@ -459,16 +459,16 @@ public class CurrencyTest extends TestFmwk { errln("Unable to get CurrencyMetaInfo instance."); return; } - + if (!CurrencyMetaInfo.hasData()) { errln("hasData() should note return false."); return; } - + CurrencyMetaInfo.CurrencyFilter filter; CurrencyMetaInfo.CurrencyInfo info; CurrencyMetaInfo.CurrencyDigits digits; - + { // CurrencyFilter filter = CurrencyMetaInfo.CurrencyFilter.onCurrency("currency"); CurrencyMetaInfo.CurrencyFilter filter2 = CurrencyMetaInfo.CurrencyFilter.onCurrency("test"); @@ -476,48 +476,48 @@ public class CurrencyTest extends TestFmwk { errln("Unable to create CurrencyFilter."); return; } - + if (filter.equals(new Object())) { errln("filter should not equal to Object"); return; } - + if (filter.equals(filter2)) { errln("filter should not equal filter2"); return; } - + if (filter.hashCode() == 0) { errln("Error getting filter hashcode"); return; } - + if (filter.toString() == null) { errln("Error calling toString()"); return; } } - + { // CurrencyInfo info = new CurrencyMetaInfo.CurrencyInfo("region", "code", 0, 1, 1, false); if (info == null) { errln("Error creating CurrencyInfo."); return; } - + if (info.toString() == null) { errln("Error calling toString()"); return; } } - + { // CurrencyDigits digits = metainfo.currencyDigits("isoCode"); if (digits == null) { errln("Unable to get CurrencyDigits."); return; } - + if (digits.toString() == null) { errln("Error calling toString()"); return; @@ -559,7 +559,7 @@ public class CurrencyTest extends TestFmwk { { "en_US_PREEURO", null, "USD", "USN" }, { "en_US_Q", null, "USD", "USN" }, }; - + DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd", Locale.US); for (String[] test : tests) { ULocale locale = new ULocale(test[0]); @@ -582,7 +582,7 @@ public class CurrencyTest extends TestFmwk { System.arraycopy(test, 2, expected, 0, expected.length); } String[] actual = Currency.getAvailableCurrencyCodes(locale, date); - + // Order is not important as of 4.4. We never documented that it was. Set expectedSet = new HashSet(); if (expected != null) { @@ -627,7 +627,7 @@ public class CurrencyTest extends TestFmwk { public void TestDeprecatedCurrencyFormat() { // bug 5952 Locale locale = new Locale("sr", "QQ"); - DecimalFormatSymbols icuSymbols = new + DecimalFormatSymbols icuSymbols = new com.ibm.icu.text.DecimalFormatSymbols(locale); String symbol = icuSymbols.getCurrencySymbol(); Currency currency = icuSymbols.getCurrency(); @@ -639,7 +639,7 @@ public class CurrencyTest extends TestFmwk { logln("for " + locale + " expected " + expectSym+"/"+expectCur + " and got " + symbol+"/"+currency); } } - + @Test public void TestGetKeywordValues(){ @@ -668,7 +668,7 @@ public class CurrencyTest extends TestFmwk { for (int i = 0; i < ALL.length; i++) { ALLSET.add(ALL[i]); } - + for (int i = 0; i < PREFERRED.length; i++) { ULocale loc = new ULocale(PREFERRED[i][0]); String[] expected = new String[PREFERRED[i].length - 1]; @@ -677,7 +677,7 @@ public class CurrencyTest extends TestFmwk { assertEquals(loc.toString(), expected, pref); String[] all = Currency.getKeywordValuesForLocale("currency", loc, false); - // The items in the two collections should match (ignore order, + // The items in the two collections should match (ignore order, // behavior change from 4.3.3) Set returnedSet = new HashSet(); returnedSet.addAll(Arrays.asList(all)); @@ -820,4 +820,9 @@ public class CurrencyTest extends TestFmwk { // TODO: replace the JUnit import with TestFmwk assertEquals. assertEquals("Rounding increment not zero", 0.0, roundingIncrement, 0.0); } + + @Test + public void TestCurrencyDataCtor() throws Exception { + checkDefaultPrivateConstructor(CurrencyData.class); + } } diff --git a/icu4j/main/tests/framework/src/com/ibm/icu/dev/test/TestFmwk.java b/icu4j/main/tests/framework/src/com/ibm/icu/dev/test/TestFmwk.java index 10898384eb5..0c42e4eeac0 100644 --- a/icu4j/main/tests/framework/src/com/ibm/icu/dev/test/TestFmwk.java +++ b/icu4j/main/tests/framework/src/com/ibm/icu/dev/test/TestFmwk.java @@ -8,6 +8,9 @@ */ package com.ibm.icu.dev.test; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.security.Policy; import java.util.ArrayList; import java.util.Arrays; @@ -50,16 +53,16 @@ abstract public class TestFmwk extends AbstractTestLog { private static final String EXHAUSTIVENESS = "ICU.exhaustive"; private static final int DEFAULT_EXHAUSTIVENESS = 0; private static final int MAX_EXHAUSTIVENESS = 10; - + private static final String LOGGING_LEVEL = "ICU.logging"; private static final int DEFAULT_LOGGING_LEVEL = 0; private static final int MAX_LOGGING_LEVEL = 3; - + public static final int LOGGING_NONE = 0; public static final int LOGGING_WARN = 1; public static final int LOGGING_INFO = 2; public static final int LOGGING_DEBUG = 3; - + private static final String SEED = "ICU.seed"; private static final String SECURITY_POLICY = "ICU.securitypolicy"; @@ -75,24 +78,24 @@ abstract public class TestFmwk extends AbstractTestLog { public void testInitialize() { Locale.setDefault(defaultLocale); TimeZone.setDefault(defaultTimeZone); - + if (getParams().testSecurityManager != null) { System.setSecurityManager(getParams().testSecurityManager); } } - + @After public void testTeardown() { if (getParams().testSecurityManager != null) { System.setSecurityManager(getParams().originalSecurityManager); } } - + private static TestParams getParams() { //return paramsReference.get(); return testParams; } - + protected static boolean isVerbose() { return getParams().getLoggingLevel() >= LOGGING_INFO; } @@ -122,7 +125,7 @@ abstract public class TestFmwk extends AbstractTestLog { * Log the known issue. * This method returns true unless -prop:logKnownIssue=no is specified * in the argument list. - * + * * @param ticket A ticket number string. For an ICU ticket, use numeric characters only, * such as "10245". For a CLDR ticket, use prefix "cldrbug:" followed by ticket number, * such as "cldrbug:5013". @@ -175,7 +178,7 @@ abstract public class TestFmwk extends AbstractTestLog { protected static boolean getBooleanProperty(String key) { return getParams().getBooleanProperty(key); } - + protected static boolean getBooleanProperty(String key, boolean defVal) { return getParams().getBooleanProperty(key, defVal); } @@ -183,11 +186,11 @@ abstract public class TestFmwk extends AbstractTestLog { protected static int getIntProperty(String key, int defVal) { return getParams().getIntProperty(key, defVal); } - + protected static int getIntProperty(String key, int defVal, int maxVal) { return getParams().getIntProperty(key, defVal, maxVal); } - + protected static TimeZone safeGetTimeZone(String id) { TimeZone tz = TimeZone.getTimeZone(id); if (tz == null) { @@ -200,9 +203,9 @@ abstract public class TestFmwk extends AbstractTestLog { return tz; } - + // Utility Methods - + protected static String hex(char[] s){ StringBuffer result = new StringBuffer(); for (int i = 0; i < s.length; ++i) { @@ -211,7 +214,7 @@ abstract public class TestFmwk extends AbstractTestLog { } return result.toString(); } - + protected static String hex(byte[] s){ StringBuffer result = new StringBuffer(); for (int i = 0; i < s.length; ++i) { @@ -220,7 +223,7 @@ abstract public class TestFmwk extends AbstractTestLog { } return result.toString(); } - + protected static String hex(char ch) { StringBuffer result = new StringBuffer(); String foo = Integer.toString(ch, 16).toUpperCase(); @@ -297,30 +300,30 @@ abstract public class TestFmwk extends AbstractTestLog { } private static class TestParams { - + private int inclusion; private long seed; private int loggingLevel; - + private String policyFileName; private SecurityManager testSecurityManager; private SecurityManager originalSecurityManager; - + private Map> knownIssues; private Properties props; - + private TestParams() { } static TestParams create() { - TestParams params = new TestParams(); + TestParams params = new TestParams(); Properties props = System.getProperties(); params.parseProperties(props); return params; } - + private void parseProperties(Properties props) { this.props = props; @@ -338,7 +341,7 @@ abstract public class TestFmwk extends AbstractTestLog { System.setProperty("java.security.policy", originalPolicyFileName==null ? "" : originalPolicyFileName); } } - + public String getProperty(String key) { String val = null; if (key != null && key.length() > 0) { @@ -350,7 +353,7 @@ abstract public class TestFmwk extends AbstractTestLog { public boolean getBooleanProperty(String key) { return getBooleanProperty(key, false); } - + public boolean getBooleanProperty(String key, boolean defVal) { String s = getProperty(key); if (s == null) { @@ -365,7 +368,7 @@ abstract public class TestFmwk extends AbstractTestLog { public int getIntProperty(String key, int defVal) { return getIntProperty(key, defVal, -1); } - + public int getIntProperty(String key, int defVal, int maxVal) { String s = getProperty(key); if (s == null) { @@ -373,7 +376,7 @@ abstract public class TestFmwk extends AbstractTestLog { } return (maxVal == -1) ? Integer.valueOf(s) : Math.max(Integer.valueOf(s), maxVal); } - + public long getLongProperty(String key, long defVal) { String s = getProperty(key); if (s == null) { @@ -381,15 +384,15 @@ abstract public class TestFmwk extends AbstractTestLog { } return Long.valueOf(s); } - + public int getInclusion() { return inclusion; } - + public long getSeed() { return seed; } - + public int getLoggingLevel() { return loggingLevel; } @@ -575,7 +578,7 @@ abstract public class TestFmwk extends AbstractTestLog { protected static void fail(String message) { if (message == null) { - message = ""; + message = ""; } if (!message.equals("")) { message = ": " + message; @@ -630,7 +633,7 @@ abstract public class TestFmwk extends AbstractTestLog { String source = st.getFileName(); if (source != null && !source.equals("TestFmwk.java") && !source.equals("AbstractTestLog.java")) { String methodName = st.getMethodName(); - if (methodName != null && + if (methodName != null && (methodName.startsWith("Test") || methodName.startsWith("test") || methodName.equals("main"))) { return "(" + source + ":" + st.getLineNumber() + ") "; } @@ -639,6 +642,77 @@ abstract public class TestFmwk extends AbstractTestLog { throw new InternalError(); } + protected static boolean checkDefaultPrivateConstructor(String fullyQualifiedClassName) throws Exception { + return checkDefaultPrivateConstructor(Class.forName(fullyQualifiedClassName)); + } + + protected static boolean checkDefaultPrivateConstructor(Class classToBeTested) throws Exception { + Constructor constructor = classToBeTested.getDeclaredConstructor(); + + // Check that the constructor is private. + boolean isPrivate = Modifier.isPrivate(constructor.getModifiers()); + + // Call the constructor for coverage. + constructor.setAccessible(true); + constructor.newInstance(); + + if (!isPrivate) { + errln("Default private constructor for class: " + classToBeTested.getName() + " is not private."); + } + return isPrivate; + } + + /** + * Tests the toString method on a private or hard-to-reach class. Assumes constructor of the class does not + * take any arguments. + * @param fullyQualifiedClassName + * @return The output of the toString method. + * @throws Exception + */ + protected static String invokeToString(String fullyQualifiedClassName) throws Exception { + return invokeToString(fullyQualifiedClassName, new Class[]{}, new Object[]{}); + } + + /** + * Tests the toString method on a private or hard-to-reach class. Assumes constructor of the class does not + * take any arguments. + * @param classToBeTested + * @return The output of the toString method. + * @throws Exception + */ + protected static String invokeToString(Class classToBeTested) throws Exception { + return invokeToString(classToBeTested, new Class[]{}, new Object[]{}); + } + + /** + * Tests the toString method on a private or hard-to-reach class. Allows you to specify the argument types for + * the constructor. + * @param fullyQualifiedClassName + * @return The output of the toString method. + * @throws Exception + */ + protected static String invokeToString(String fullyQualifiedClassName, + Class[] constructorParamTypes, Object[] constructorParams) throws Exception { + return invokeToString(Class.forName(fullyQualifiedClassName), constructorParamTypes, constructorParams); + } + + /** + * Tests the toString method on a private or hard-to-reach class. Allows you to specify the argument types for + * the constructor. + * @param classToBeTested + * @return The output of the toString method. + * @throws Exception + */ + protected static String invokeToString(Class classToBeTested, + Class[] constructorParamTypes, Object[] constructorParams) throws Exception { + Constructor constructor = classToBeTested.getDeclaredConstructor(constructorParamTypes); + constructor.setAccessible(true); + Object obj = constructor.newInstance(constructorParams); + Method toStringMethod = classToBeTested.getDeclaredMethod("toString"); + toStringMethod.setAccessible(true); + return (String) toStringMethod.invoke(obj); + } + // End JUnit-like assertions