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