Home | History | Annotate | Download | only in format
      1 /* GENERATED SOURCE. DO NOT MODIFY. */
      2 //  2016 and later: Unicode, Inc. and others.
      3 // License & terms of use: http://www.unicode.org/copyright.html#License
      4 /*
      5  *******************************************************************************
      6  * Copyright (C) 2001-2016, International Business Machines Corporation and
      7  * others. All Rights Reserved.
      8  *******************************************************************************
      9  */
     10 
     11 /**
     12  * Port From:   ICU4C v1.8.1 : format : IntlTestDecimalFormatAPI
     13  * Source File: $ICU4CRoot/source/test/intltest/dcfmapts.cpp
     14  **/
     15 
     16 package android.icu.dev.test.format;
     17 
     18 import java.text.AttributedCharacterIterator;
     19 import java.text.FieldPosition;
     20 import java.text.Format;
     21 import java.text.ParsePosition;
     22 import java.util.ArrayList;
     23 import java.util.Iterator;
     24 import java.util.List;
     25 import java.util.Locale;
     26 
     27 import org.junit.Test;
     28 
     29 import android.icu.text.CurrencyPluralInfo;
     30 import android.icu.text.DecimalFormat;
     31 import android.icu.text.DecimalFormatSymbols;
     32 import android.icu.text.NumberFormat;
     33 import android.icu.util.ULocale;
     34 
     35 // This is an API test, not a unit test.  It doesn't test very many cases, and doesn't
     36 // try to test the full functionality.  It just calls each function in the class and
     37 // verifies that it works on a basic level.
     38 public class IntlTestDecimalFormatAPIC extends android.icu.dev.test.TestFmwk {
     39 
     40     // This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
     41     @Test
     42     public void TestAPI() {
     43 
     44         logln("DecimalFormat API test---");
     45         logln("");
     46         Locale.setDefault(Locale.ENGLISH);
     47 
     48         // ======= Test constructors
     49 
     50         logln("Testing DecimalFormat constructors");
     51 
     52         DecimalFormat def = new DecimalFormat();
     53 
     54         final String pattern = new String("#,##0.# FF");
     55         final DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
     56         final CurrencyPluralInfo infoInput = new CurrencyPluralInfo(ULocale.FRENCH);
     57 
     58         DecimalFormat pat = null;
     59         try {
     60             pat = new DecimalFormat(pattern);
     61         } catch (IllegalArgumentException e) {
     62             errln("ERROR: Could not create DecimalFormat (pattern)");
     63         }
     64 
     65         DecimalFormat cust1 = null;
     66         try {
     67             cust1 = new DecimalFormat(pattern, symbols);
     68         } catch (IllegalArgumentException e) {
     69             errln("ERROR: Could not create DecimalFormat (pattern, symbols)");
     70         }
     71 
     72         @SuppressWarnings("unused")
     73         DecimalFormat cust2 = null;
     74         try {
     75             cust2 = new DecimalFormat(pattern, symbols, infoInput, NumberFormat.PLURALCURRENCYSTYLE);
     76         } catch (IllegalArgumentException e) {
     77             errln("ERROR: Could not create DecimalFormat (pattern, symbols, infoInput, style)");
     78         }
     79 
     80 
     81         // ======= Test clone(), assignment, and equality
     82 
     83         logln("Testing clone() and equality operators");
     84 
     85         Format clone = (Format) def.clone();
     86         if (!def.equals(clone)) {
     87             errln("ERROR: Clone() failed");
     88         }
     89 
     90         // ======= Test various format() methods
     91 
     92         logln("Testing various format() methods");
     93 
     94         //        final double d = -10456.0037; // this appears as -10456.003700000001 on NT
     95         //        final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
     96         final double d = -10456.00370000000000; // this works!
     97         final long l = 100000000;
     98         logln("" + Double.toString(d) + " is the double value");
     99 
    100         StringBuffer res1 = new StringBuffer();
    101         StringBuffer res2 = new StringBuffer();
    102         StringBuffer res3 = new StringBuffer();
    103         StringBuffer res4 = new StringBuffer();
    104         FieldPosition pos1 = new FieldPosition(0);
    105         FieldPosition pos2 = new FieldPosition(0);
    106         FieldPosition pos3 = new FieldPosition(0);
    107         FieldPosition pos4 = new FieldPosition(0);
    108 
    109         res1 = def.format(d, res1, pos1);
    110         logln("" + Double.toString(d) + " formatted to " + res1);
    111 
    112         res2 = pat.format(l, res2, pos2);
    113         logln("" + l + " formatted to " + res2);
    114 
    115         res3 = cust1.format(d, res3, pos3);
    116         logln("" + Double.toString(d) + " formatted to " + res3);
    117 
    118         res4 = cust1.format(l, res4, pos4);
    119         logln("" + l + " formatted to " + res4);
    120 
    121         // ======= Test parse()
    122 
    123         logln("Testing parse()");
    124 
    125         String text = new String("-10,456.0037");
    126         ParsePosition pos = new ParsePosition(0);
    127         String patt = new String("#,##0.#");
    128         pat.applyPattern(patt);
    129         double d2 = pat.parse(text, pos).doubleValue();
    130         if (d2 != d) {
    131             errln(
    132                 "ERROR: Roundtrip failed (via parse(" + Double.toString(d2) + " != " + Double.toString(d) + ")) for " + text);
    133         }
    134         logln(text + " parsed into " + (long) d2);
    135 
    136         // ======= Test getters and setters
    137 
    138         logln("Testing getters and setters");
    139 
    140         final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
    141         def.setDecimalFormatSymbols(syms);
    142         if (!pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
    143             errln("ERROR: set DecimalFormatSymbols() failed");
    144         }
    145 
    146         String posPrefix;
    147         pat.setPositivePrefix("+");
    148         posPrefix = pat.getPositivePrefix();
    149         logln("Positive prefix (should be +): " + posPrefix);
    150         if (posPrefix != "+") {
    151             errln("ERROR: setPositivePrefix() failed");
    152         }
    153 
    154         String negPrefix;
    155         pat.setNegativePrefix("-");
    156         negPrefix = pat.getNegativePrefix();
    157         logln("Negative prefix (should be -): " + negPrefix);
    158         if (negPrefix != "-") {
    159             errln("ERROR: setNegativePrefix() failed");
    160         }
    161 
    162         String posSuffix;
    163         pat.setPositiveSuffix("_");
    164         posSuffix = pat.getPositiveSuffix();
    165         logln("Positive suffix (should be _): " + posSuffix);
    166         if (posSuffix != "_") {
    167             errln("ERROR: setPositiveSuffix() failed");
    168         }
    169 
    170         String negSuffix;
    171         pat.setNegativeSuffix("~");
    172         negSuffix = pat.getNegativeSuffix();
    173         logln("Negative suffix (should be ~): " + negSuffix);
    174         if (negSuffix != "~") {
    175             errln("ERROR: setNegativeSuffix() failed");
    176         }
    177 
    178         long multiplier = 0;
    179         pat.setMultiplier(8);
    180         multiplier = pat.getMultiplier();
    181         logln("Multiplier (should be 8): " + multiplier);
    182         if (multiplier != 8) {
    183             errln("ERROR: setMultiplier() failed");
    184         }
    185 
    186         int groupingSize = 0;
    187         pat.setGroupingSize(2);
    188         groupingSize = pat.getGroupingSize();
    189         logln("Grouping size (should be 2): " + (long) groupingSize);
    190         if (groupingSize != 2) {
    191             errln("ERROR: setGroupingSize() failed");
    192         }
    193 
    194         pat.setDecimalSeparatorAlwaysShown(true);
    195         boolean tf = pat.isDecimalSeparatorAlwaysShown();
    196         logln(
    197             "DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
    198         if (tf != true) {
    199             errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
    200         }
    201 
    202         String funkyPat;
    203         funkyPat = pat.toPattern();
    204         logln("Pattern is " + funkyPat);
    205 
    206         String locPat;
    207         locPat = pat.toLocalizedPattern();
    208         logln("Localized pattern is " + locPat);
    209 
    210         pat.setCurrencyPluralInfo(infoInput);
    211         if(!infoInput.equals(pat.getCurrencyPluralInfo())) {
    212             errln("ERROR: set/get CurrencyPluralInfo() failed");
    213         }
    214 
    215 
    216         pat.setCurrencyPluralInfo(infoInput);
    217         if(!infoInput.equals(pat.getCurrencyPluralInfo())) {
    218             errln("ERROR: set/get CurrencyPluralInfo() failed");
    219         }
    220 
    221         // ======= Test applyPattern()
    222 
    223         logln("Testing applyPattern()");
    224 
    225         String p1 = new String("#,##0.0#;(#,##0.0#)");
    226         logln("Applying pattern " + p1);
    227         pat.applyPattern(p1);
    228         String s2;
    229         s2 = pat.toPattern();
    230         logln("Extracted pattern is " + s2);
    231         if (!s2.equals(p1)) {
    232             errln("ERROR: toPattern() result did not match pattern applied");
    233         }
    234 
    235         String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
    236         logln("Applying pattern " + p2);
    237         pat.applyLocalizedPattern(p2);
    238         String s3;
    239         s3 = pat.toLocalizedPattern();
    240         logln("Extracted pattern is " + s3);
    241         if (!s3.equals(p2)) {
    242             errln("ERROR: toLocalizedPattern() result did not match pattern applied");
    243         }
    244 
    245         // ======= Test getStaticClassID()
    246 
    247         //        logln("Testing instanceof()");
    248 
    249         //        try {
    250         //           NumberFormat test = new DecimalFormat();
    251 
    252         //            if (! (test instanceof DecimalFormat)) {
    253         //                errln("ERROR: instanceof failed");
    254         //            }
    255         //        }
    256         //        catch (Exception e) {
    257         //            errln("ERROR: Couldn't create a DecimalFormat");
    258         //        }
    259 
    260     }
    261 
    262     @Test
    263     public void TestRounding() {
    264         double Roundingnumber = 2.55;
    265         double Roundingnumber1 = -2.55;
    266         //+2.55 results   -2.55 results
    267         double result[] = {
    268             3, -3,
    269             2, -2,
    270             3, -2,
    271             2, -3,
    272             3, -3,
    273             3, -3,
    274             3, -3
    275         };
    276         DecimalFormat pat = new DecimalFormat();
    277         String s = "";
    278         s = pat.toPattern();
    279         logln("pattern = " + s);
    280         int mode;
    281         int i = 0;
    282         String message;
    283         String resultStr;
    284         for (mode = 0; mode < 7; mode++) {
    285             pat.setRoundingMode(mode);
    286             if (pat.getRoundingMode() != mode) {
    287                 errln(
    288                      "SetRoundingMode or GetRoundingMode failed for mode=" + mode);
    289             }
    290 
    291             //for +2.55 with RoundingIncrement=1.0
    292             pat.setRoundingIncrement(1.0);
    293             resultStr = pat.format(Roundingnumber);
    294             message = "round(" + Roundingnumber
    295                     + "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
    296             verify(message, resultStr, result[i++]);
    297             message = "";
    298             resultStr = "";
    299 
    300             //for -2.55 with RoundingIncrement=1.0
    301             resultStr = pat.format(Roundingnumber1);
    302             message = "round(" + Roundingnumber1
    303                     + "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
    304             verify(message, resultStr, result[i++]);
    305             message = "";
    306             resultStr = "";
    307         }
    308     }
    309 
    310     @Test
    311     public void testFormatToCharacterIterator() {
    312 
    313         Number number = new Double(350.76);
    314         Number negativeNumber = new Double(-350.76);
    315 
    316         Locale us = Locale.US;
    317 
    318         // test number instance
    319         t_Format(1, number, NumberFormat.getNumberInstance(us),
    320                 getNumberVectorUS());
    321 
    322         // test percent instance
    323         t_Format(3, number, NumberFormat.getPercentInstance(us),
    324                 getPercentVectorUS());
    325 
    326         // test permille pattern
    327         DecimalFormat format = new DecimalFormat("###0.##\u2030");
    328         t_Format(4, number, format, getPermilleVector());
    329 
    330         // test exponential pattern with positive exponent
    331         format = new DecimalFormat("00.0#E0");
    332         t_Format(5, number, format, getPositiveExponentVector());
    333 
    334         // test exponential pattern with negative exponent
    335         format = new DecimalFormat("0000.0#E0");
    336         t_Format(6, number, format, getNegativeExponentVector());
    337 
    338         // test currency instance with US Locale
    339         t_Format(7, number, NumberFormat.getCurrencyInstance(us),
    340                 getPositiveCurrencyVectorUS());
    341 
    342         // test negative currency instance with US Locale
    343         t_Format(8, negativeNumber, NumberFormat.getCurrencyInstance(us),
    344                 getNegativeCurrencyVectorUS());
    345 
    346         // test multiple grouping separators
    347         number = new Long(100300400);
    348         t_Format(11, number, NumberFormat.getNumberInstance(us),
    349                 getNumberVector2US());
    350 
    351         // test 0
    352         number = new Long(0);
    353         t_Format(12, number, NumberFormat.getNumberInstance(us),
    354                 getZeroVector());
    355     }
    356 
    357     private static List<FieldContainer> getNumberVectorUS() {
    358         List<FieldContainer> v = new ArrayList<FieldContainer>(3);
    359         v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
    360         v.add(new FieldContainer(3, 4, NumberFormat.Field.DECIMAL_SEPARATOR));
    361         v.add(new FieldContainer(4, 6, NumberFormat.Field.FRACTION));
    362         return v;
    363     }
    364 
    365 //    private static Vector getPositiveCurrencyVectorTR() {
    366 //        Vector v = new Vector();
    367 //        v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
    368 //        v.add(new FieldContainer(4, 6, NumberFormat.Field.CURRENCY));
    369 //        return v;
    370 //    }
    371 //
    372 //    private static Vector getNegativeCurrencyVectorTR() {
    373 //        Vector v = new Vector();
    374 //        v.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN));
    375 //        v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
    376 //        v.add(new FieldContainer(5, 7, NumberFormat.Field.CURRENCY));
    377 //        return v;
    378 //    }
    379 
    380     private static List<FieldContainer> getPositiveCurrencyVectorUS() {
    381         List<FieldContainer> v = new ArrayList<FieldContainer>(4);
    382         v.add(new FieldContainer(0, 1, NumberFormat.Field.CURRENCY));
    383         v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
    384         v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
    385         v.add(new FieldContainer(5, 7, NumberFormat.Field.FRACTION));
    386         return v;
    387     }
    388 
    389     private static List<FieldContainer> getNegativeCurrencyVectorUS() {
    390         List<FieldContainer> v = new ArrayList<FieldContainer>(4);
    391         // SIGN added with fix for issue 11805.
    392         v.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN));
    393         v.add(new FieldContainer(1, 2, NumberFormat.Field.CURRENCY));
    394         v.add(new FieldContainer(2, 5, NumberFormat.Field.INTEGER));
    395         v.add(new FieldContainer(5, 6, NumberFormat.Field.DECIMAL_SEPARATOR));
    396         v.add(new FieldContainer(6, 8, NumberFormat.Field.FRACTION));
    397         return v;
    398     }
    399 
    400     private static List<FieldContainer> getPercentVectorUS() {
    401         List<FieldContainer> v = new ArrayList<FieldContainer>(5);
    402         v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
    403         v.add(new FieldContainer(2, 3, NumberFormat.Field.INTEGER));
    404         v.add(new FieldContainer(2, 3, NumberFormat.Field.GROUPING_SEPARATOR));
    405         v.add(new FieldContainer(3, 6, NumberFormat.Field.INTEGER));
    406         v.add(new FieldContainer(6, 7, NumberFormat.Field.PERCENT));
    407         return v;
    408     }
    409 
    410     private static List<FieldContainer> getPermilleVector() {
    411         List<FieldContainer> v = new ArrayList<FieldContainer>(2);
    412         v.add(new FieldContainer(0, 6, NumberFormat.Field.INTEGER));
    413         v.add(new FieldContainer(6, 7, NumberFormat.Field.PERMILLE));
    414         return v;
    415     }
    416 
    417     private static List<FieldContainer> getNegativeExponentVector() {
    418         List<FieldContainer> v = new ArrayList<FieldContainer>(6);
    419         v.add(new FieldContainer(0, 4, NumberFormat.Field.INTEGER));
    420         v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
    421         v.add(new FieldContainer(5, 6, NumberFormat.Field.FRACTION));
    422         v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SYMBOL));
    423         v.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT_SIGN));
    424         v.add(new FieldContainer(8, 9, NumberFormat.Field.EXPONENT));
    425         return v;
    426     }
    427 
    428     private static List<FieldContainer> getPositiveExponentVector() {
    429         List<FieldContainer> v = new ArrayList<FieldContainer>(5);
    430         v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
    431         v.add(new FieldContainer(2, 3, NumberFormat.Field.DECIMAL_SEPARATOR));
    432         v.add(new FieldContainer(3, 5, NumberFormat.Field.FRACTION));
    433         v.add(new FieldContainer(5, 6, NumberFormat.Field.EXPONENT_SYMBOL));
    434         v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT));
    435         return v;
    436     }
    437 
    438     private static List<FieldContainer> getNumberVector2US() {
    439         List<FieldContainer> v = new ArrayList<FieldContainer>(7);
    440         v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
    441         v.add(new FieldContainer(3, 4, NumberFormat.Field.GROUPING_SEPARATOR));
    442         v.add(new FieldContainer(3, 4, NumberFormat.Field.INTEGER));
    443         v.add(new FieldContainer(4, 7, NumberFormat.Field.INTEGER));
    444         v.add(new FieldContainer(7, 8, NumberFormat.Field.GROUPING_SEPARATOR));
    445         v.add(new FieldContainer(7, 8, NumberFormat.Field.INTEGER));
    446         v.add(new FieldContainer(8, 11, NumberFormat.Field.INTEGER));
    447         return v;
    448     }
    449 
    450     private static List<FieldContainer> getZeroVector() {
    451         List<FieldContainer> v = new ArrayList<FieldContainer>(1);
    452         v.add(new FieldContainer(0, 1, NumberFormat.Field.INTEGER));
    453         return v;
    454     }
    455 
    456     private void t_Format(int count, Object object, Format format,
    457             List<FieldContainer> expectedResults) {
    458         List<FieldContainer> results = findFields(format.formatToCharacterIterator(object));
    459         assertTrue("Test " + count
    460                 + ": Format returned incorrect CharacterIterator for "
    461                 + format.format(object), compare(results, expectedResults));
    462     }
    463 
    464     /**
    465      * compares two vectors regardless of the order of their elements
    466      */
    467     private static boolean compare(List vector1, List vector2) {
    468         return vector1.size() == vector2.size() && vector1.containsAll(vector2);
    469     }
    470 
    471     /**
    472      * finds attributes with regards to char index in this
    473      * AttributedCharacterIterator, and puts them in a vector
    474      *
    475      * @param iterator
    476      * @return a vector, each entry in this vector are of type FieldContainer ,
    477      *         which stores start and end indexes and an attribute this range
    478      *         has
    479      */
    480     private static List<FieldContainer> findFields(AttributedCharacterIterator iterator) {
    481         List<FieldContainer> result = new ArrayList<FieldContainer>();
    482         while (iterator.getIndex() != iterator.getEndIndex()) {
    483             int start = iterator.getRunStart();
    484             int end = iterator.getRunLimit();
    485 
    486             Iterator it = iterator.getAttributes().keySet().iterator();
    487             while (it.hasNext()) {
    488                 AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute) it
    489                         .next();
    490                 Object value = iterator.getAttribute(attribute);
    491                 result.add(new FieldContainer(start, end, attribute, value));
    492                 // System.out.println(start + " " + end + ": " + attribute + ",
    493                 // " + value );
    494                 // System.out.println("v.add(new FieldContainer(" + start +"," +
    495                 // end +"," + attribute+ "," + value+ "));");
    496             }
    497             iterator.setIndex(end);
    498         }
    499         return result;
    500     }
    501     protected static class FieldContainer {
    502         int start, end;
    503 
    504         AttributedCharacterIterator.Attribute attribute;
    505 
    506         Object value;
    507 
    508 //         called from support_decimalformat and support_simpledateformat tests
    509         public FieldContainer(int start, int end,
    510         AttributedCharacterIterator.Attribute attribute) {
    511             this(start, end, attribute, attribute);
    512         }
    513 
    514 //         called from support_messageformat tests
    515         public FieldContainer(int start, int end, AttributedCharacterIterator.Attribute attribute, int value) {
    516         this(start, end, attribute, new Integer(value));
    517         }
    518 
    519 //         called from support_messageformat tests
    520         public FieldContainer(int start, int end, AttributedCharacterIterator.Attribute attribute,
    521         Object value) {
    522         this.start = start;
    523         this.end = end;
    524         this.attribute = attribute;
    525         this.value = value;
    526         }
    527 
    528         @Override
    529         public boolean equals(Object obj) {
    530         if (!(obj instanceof FieldContainer))
    531         return false;
    532 
    533         FieldContainer fc = (FieldContainer) obj;
    534         return (start == fc.start && end == fc.end
    535         && attribute == fc.attribute && value.equals(fc.value));
    536         }
    537     }
    538 
    539     /*Helper functions */
    540     public void verify(String message, String got, double expected) {
    541         logln(message + got + " Expected : " + (long)expected);
    542         String expectedStr = "";
    543         expectedStr=expectedStr + (long)expected;
    544         if(!got.equals(expectedStr) ) {
    545             errln("ERROR: Round() failed:  " + message + got + "  Expected : " + expectedStr);
    546         }
    547     }
    548 }
    549 //eof
    550