]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_2_1-src/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatAPIC.java
go
[Dictionary.git] / jars / icu4j-4_2_1-src / src / com / ibm / icu / dev / test / format / IntlTestDecimalFormatAPIC.java
1 //##header J2SE15
2 /*
3  *******************************************************************************
4  * Copyright (C) 2001-2009, International Business Machines Corporation and    *
5  * others. All Rights Reserved.                                                *
6  *******************************************************************************
7  */
8
9 /** 
10  * Port From:   ICU4C v1.8.1 : format : IntlTestDecimalFormatAPI
11  * Source File: $ICU4CRoot/source/test/intltest/dcfmapts.cpp
12  **/
13
14 package com.ibm.icu.dev.test.format;
15
16 import java.text.AttributedCharacterIterator;
17 import java.text.FieldPosition;
18 import java.text.Format;
19 import java.text.ParsePosition;
20 import java.util.Iterator;
21 import java.util.Locale;
22 import java.util.Vector;
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 //#if defined(FOUNDATION10) || defined(J2SE13)
280 //#else
281     public void testFormatToCharacterIterator() {
282
283         Number number = new Double(350.76);
284         Number negativeNumber = new Double(-350.76);
285
286         Locale us = Locale.US;
287
288         // test number instance
289         t_Format(1, number, NumberFormat.getNumberInstance(us),
290                 getNumberVectorUS());
291
292         // test percent instance
293         t_Format(3, number, NumberFormat.getPercentInstance(us),
294                 getPercentVectorUS());
295
296         // test permille pattern
297         DecimalFormat format = new DecimalFormat("###0.##\u2030");
298         t_Format(4, number, format, getPermilleVector());
299
300         // test exponential pattern with positive exponent
301         format = new DecimalFormat("00.0#E0");
302         t_Format(5, number, format, getPositiveExponentVector());
303
304         // test exponential pattern with negative exponent
305         format = new DecimalFormat("0000.0#E0");
306         t_Format(6, number, format, getNegativeExponentVector());
307
308         // test currency instance with US Locale
309         t_Format(7, number, NumberFormat.getCurrencyInstance(us),
310                 getPositiveCurrencyVectorUS());
311
312         // test negative currency instance with US Locale
313         t_Format(8, negativeNumber, NumberFormat.getCurrencyInstance(us),
314                 getNegativeCurrencyVectorUS());
315
316         // test multiple grouping seperators
317         number = new Long(100300400);
318         t_Format(11, number, NumberFormat.getNumberInstance(us),
319                 getNumberVector2US());
320
321         // test 0
322         number = new Long(0);
323         t_Format(12, number, NumberFormat.getNumberInstance(us),
324                 getZeroVector());
325     }
326
327     private static Vector getNumberVectorUS() {
328         Vector v = new Vector();
329         v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
330         v.add(new FieldContainer(3, 4, NumberFormat.Field.DECIMAL_SEPARATOR));
331         v.add(new FieldContainer(4, 6, NumberFormat.Field.FRACTION));
332         return v;
333     }
334     
335 //    private static Vector getPositiveCurrencyVectorTR() {
336 //        Vector v = new Vector();
337 //        v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
338 //        v.add(new FieldContainer(4, 6, NumberFormat.Field.CURRENCY));
339 //        return v;
340 //    }
341 //
342 //    private static Vector getNegativeCurrencyVectorTR() {
343 //        Vector v = new Vector();
344 //        v.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN));
345 //        v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
346 //        v.add(new FieldContainer(5, 7, NumberFormat.Field.CURRENCY));
347 //        return v;
348 //    }
349
350     private static Vector getPositiveCurrencyVectorUS() {
351         Vector v = new Vector();
352         v.add(new FieldContainer(0, 1, NumberFormat.Field.CURRENCY));
353         v.add(new FieldContainer(1, 4, NumberFormat.Field.INTEGER));
354         v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
355         v.add(new FieldContainer(5, 7, NumberFormat.Field.FRACTION));
356         return v;
357     }
358
359     private static Vector getNegativeCurrencyVectorUS() {
360         Vector v = new Vector();
361         v.add(new FieldContainer(1, 2, NumberFormat.Field.CURRENCY));
362         v.add(new FieldContainer(2, 5, NumberFormat.Field.INTEGER));
363         v.add(new FieldContainer(5, 6, NumberFormat.Field.DECIMAL_SEPARATOR));
364         v.add(new FieldContainer(6, 8, NumberFormat.Field.FRACTION));
365         return v;
366     }
367
368     private static Vector getPercentVectorUS() {
369         Vector v = new Vector();
370         v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
371         v.add(new FieldContainer(2, 3, NumberFormat.Field.INTEGER));
372         v.add(new FieldContainer(2, 3, NumberFormat.Field.GROUPING_SEPARATOR));
373         v.add(new FieldContainer(3, 6, NumberFormat.Field.INTEGER));
374         v.add(new FieldContainer(6, 7, NumberFormat.Field.PERCENT));
375         return v;
376     }
377
378     private static Vector getPermilleVector() {
379         Vector v = new Vector();
380         v.add(new FieldContainer(0, 6, NumberFormat.Field.INTEGER));
381         v.add(new FieldContainer(6, 7, NumberFormat.Field.PERMILLE));
382         return v;
383     }
384
385     private static Vector getNegativeExponentVector() {
386         Vector v = new Vector();
387         v.add(new FieldContainer(0, 4, NumberFormat.Field.INTEGER));
388         v.add(new FieldContainer(4, 5, NumberFormat.Field.DECIMAL_SEPARATOR));
389         v.add(new FieldContainer(5, 6, NumberFormat.Field.FRACTION));
390         v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SYMBOL));
391         v.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT_SIGN));
392         v.add(new FieldContainer(8, 9, NumberFormat.Field.EXPONENT));
393         return v;
394     }
395
396     private static Vector getPositiveExponentVector() {
397         Vector v = new Vector();
398         v.add(new FieldContainer(0, 2, NumberFormat.Field.INTEGER));
399         v.add(new FieldContainer(2, 3, NumberFormat.Field.DECIMAL_SEPARATOR));
400         v.add(new FieldContainer(3, 5, NumberFormat.Field.FRACTION));
401         v.add(new FieldContainer(5, 6, NumberFormat.Field.EXPONENT_SYMBOL));
402         v.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT));
403         return v;
404     }
405
406     private static Vector getNumberVector2US() {
407         Vector v = new Vector();
408         v.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER));
409         v.add(new FieldContainer(3, 4, NumberFormat.Field.GROUPING_SEPARATOR));
410         v.add(new FieldContainer(3, 4, NumberFormat.Field.INTEGER));
411         v.add(new FieldContainer(4, 7, NumberFormat.Field.INTEGER));
412         v.add(new FieldContainer(7, 8, NumberFormat.Field.GROUPING_SEPARATOR));
413         v.add(new FieldContainer(7, 8, NumberFormat.Field.INTEGER));
414         v.add(new FieldContainer(8, 11, NumberFormat.Field.INTEGER));
415         return v;
416     }
417
418     private static Vector getZeroVector() {
419         Vector v = new Vector();
420         v.add(new FieldContainer(0, 1, NumberFormat.Field.INTEGER));
421         return v;
422     }    
423     
424     private void t_Format(int count, Object object, Format format,
425             Vector expectedResults) {
426         Vector results = findFields(format.formatToCharacterIterator(object));
427         assertTrue("Test " + count
428                 + ": Format returned incorrect CharacterIterator for "
429                 + format.format(object), compare(results, expectedResults));
430     }
431
432     /**
433      * compares two vectors regardless of the order of their elements
434      */
435     private static boolean compare(Vector vector1, Vector vector2) {
436         return vector1.size() == vector2.size() && vector1.containsAll(vector2);
437     }
438     
439     /**
440      * finds attributes with regards to char index in this
441      * AttributedCharacterIterator, and puts them in a vector
442      * 
443      * @param iterator
444      * @return a vector, each entry in this vector are of type FieldContainer ,
445      *         which stores start and end indexes and an attribute this range
446      *         has
447      */
448     private static Vector findFields(AttributedCharacterIterator iterator) {
449         Vector result = new Vector();
450         while (iterator.getIndex() != iterator.getEndIndex()) {
451             int start = iterator.getRunStart();
452             int end = iterator.getRunLimit();
453
454             Iterator it = iterator.getAttributes().keySet().iterator();
455             while (it.hasNext()) {
456                 AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute) it
457                         .next();
458                 Object value = iterator.getAttribute(attribute);
459                 result.add(new FieldContainer(start, end, attribute, value));
460                 // System.out.println(start + " " + end + ": " + attribute + ",
461                 // " + value );
462                 // System.out.println("v.add(new FieldContainer(" + start +"," +
463                 // end +"," + attribute+ "," + value+ "));");
464             }
465             iterator.setIndex(end);
466         }
467         return result;
468     }
469     protected static class FieldContainer {
470         int start, end;
471
472         AttributedCharacterIterator.Attribute attribute;
473
474         Object value;
475
476 //         called from support_decimalformat and support_simpledateformat tests
477         public FieldContainer(int start, int end,
478         AttributedCharacterIterator.Attribute attribute) {
479             this(start, end, attribute, attribute);
480         }
481
482 //         called from support_messageformat tests
483         public FieldContainer(int start, int end, AttributedCharacterIterator.Attribute attribute, int value) {
484         this(start, end, attribute, new Integer(value));
485         }
486
487 //         called from support_messageformat tests
488         public FieldContainer(int start, int end, AttributedCharacterIterator.Attribute attribute,
489         Object value) {
490         this.start = start;
491         this.end = end;
492         this.attribute = attribute;
493         this.value = value;
494         }
495
496         public boolean equals(Object obj) {
497         if (!(obj instanceof FieldContainer))
498         return false;
499
500         FieldContainer fc = (FieldContainer) obj;
501         return (start == fc.start && end == fc.end
502         && attribute == fc.attribute && value.equals(fc.value));
503         }
504     } 
505 //#endif
506
507     /*Helper functions */
508     public void verify(String message, String got, double expected) {
509         logln(message + got + " Expected : " + (long)expected);
510         String expectedStr = "";
511         expectedStr=expectedStr + (long)expected;
512         if(!got.equals(expectedStr) ) {
513             errln("ERROR: Round() failed:  " + message + got + "  Expected : " + expectedStr);
514         }
515     }
516 }
517 //eof