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