]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_4_2-src/main/tests/core/src/com/ibm/icu/dev/test/format/MessageRegression.java
go
[Dictionary.git] / jars / icu4j-4_4_2-src / main / tests / core / src / com / ibm / icu / dev / test / format / MessageRegression.java
1 /*\r
2 **********************************************************************\r
3 * Copyright (c) 2005-2010, International Business Machines\r
4 * Corporation and others.  All Rights Reserved.\r
5 **********************************************************************\r
6 * Author: Alan Liu\r
7 * Created: April 12, 2004\r
8 * Since: ICU 3.0\r
9 **********************************************************************\r
10 */\r
11 /**\r
12  * MessageRegression.java\r
13  *\r
14  * @test 1.29 01/03/12\r
15  * @bug 4031438 4058973 4074764 4094906 4104976 4105380 4106659 4106660 4106661\r
16  * 4111739 4112104 4113018 4114739 4114743 4116444 4118592 4118594 4120552\r
17  * 4142938 4169959 4232154 4293229\r
18  * @summary Regression tests for MessageFormat and associated classes\r
19  */\r
20 /*\r
21 (C) Copyright Taligent, Inc. 1996 - All Rights Reserved\r
22 (C) Copyright IBM Corp. 1996 - All Rights Reserved\r
23 \r
24   The original version of this source code and documentation is copyrighted and\r
25 owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are\r
26 provided under terms of a License Agreement between Taligent and Sun. This\r
27 technology is protected by multiple US and International patents. This notice and\r
28 attribution to Taligent may not be removed.\r
29   Taligent is a registered trademark of Taligent, Inc.\r
30 */\r
31 package com.ibm.icu.dev.test.format;\r
32 \r
33 import java.io.ByteArrayInputStream;\r
34 import java.io.ByteArrayOutputStream;\r
35 import java.io.IOException;\r
36 import java.io.ObjectInputStream;\r
37 import java.io.ObjectOutputStream;\r
38 import java.text.ChoiceFormat;\r
39 import java.text.ParsePosition;\r
40 import java.util.Date;\r
41 import java.util.HashMap;\r
42 import java.util.Iterator;\r
43 import java.util.Locale;\r
44 import java.util.Map;\r
45 \r
46 import com.ibm.icu.text.MessageFormat;\r
47 \r
48 public class MessageRegression extends com.ibm.icu.dev.test.TestFmwk {\r
49 \r
50     public static void main(String[] args) throws Exception {\r
51         new MessageRegression().run(args);\r
52     }\r
53 \r
54     /* @bug 4074764\r
55      * Null exception when formatting pattern with MessageFormat\r
56      * with no parameters.\r
57      */\r
58     public void Test4074764() {\r
59         String[] pattern = {"Message without param",\r
60         "Message with param:{0}",\r
61         "Longer Message with param {0}"};\r
62         //difference between the two param strings are that\r
63         //in the first one, the param position is within the\r
64         //length of the string without param while it is not so\r
65         //in the other case.\r
66 \r
67         MessageFormat messageFormatter = new MessageFormat("");\r
68 \r
69         try {\r
70             //Apply pattern with param and print the result\r
71             messageFormatter.applyPattern(pattern[1]);\r
72             Object[] paramArray = {new String("BUG"), new Date()};\r
73             String tempBuffer = messageFormatter.format(paramArray);\r
74             if (!tempBuffer.equals("Message with param:BUG"))\r
75                 errln("MessageFormat with one param test failed.");\r
76             logln("Formatted with one extra param : " + tempBuffer);\r
77 \r
78             //Apply pattern without param and print the result\r
79             messageFormatter.applyPattern(pattern[0]);\r
80             tempBuffer = messageFormatter.format(null);\r
81             if (!tempBuffer.equals("Message without param"))\r
82                 errln("MessageFormat with no param test failed.");\r
83             logln("Formatted with no params : " + tempBuffer);\r
84 \r
85              tempBuffer = messageFormatter.format(paramArray);\r
86              if (!tempBuffer.equals("Message without param"))\r
87                 errln("Formatted with arguments > subsitution failed. result = " + tempBuffer.toString());\r
88              logln("Formatted with extra params : " + tempBuffer);\r
89             //This statement gives an exception while formatting...\r
90             //If we use pattern[1] for the message with param,\r
91             //we get an NullPointerException in MessageFormat.java(617)\r
92             //If we use pattern[2] for the message with param,\r
93             //we get an StringArrayIndexOutOfBoundsException in MessageFormat.java(614)\r
94             //Both are due to maxOffset not being reset to -1\r
95             //in applyPattern() when the pattern does not\r
96             //contain any param.\r
97         } catch (Exception foo) {\r
98             errln("Exception when formatting with no params.");\r
99         }\r
100     }\r
101 \r
102     /* @bug 4058973\r
103      * MessageFormat.toPattern has weird rounding behavior.\r
104      */\r
105     public void Test4058973() {\r
106 \r
107         MessageFormat fmt = new MessageFormat("{0,choice,0#no files|1#one file|1< {0,number,integer} files}");\r
108         String pat = fmt.toPattern();\r
109         if (!pat.equals("{0,choice,0.0#no files|1.0#one file|1.0< {0,number,integer} files}")) {\r
110             errln("MessageFormat.toPattern failed");\r
111         }\r
112     }\r
113     /* @bug 4031438\r
114      * More robust message formats.\r
115      */\r
116     public void Test4031438() {\r
117         String pattern1 = "Impossible {1} has occurred -- status code is {0} and message is {2}.";\r
118         String pattern2 = "Double '' Quotes {0} test and quoted '{1}' test plus 'other {2} stuff'.";\r
119 \r
120         MessageFormat messageFormatter = new MessageFormat("");\r
121 \r
122         try {\r
123             logln("Apply with pattern : " + pattern1);\r
124             messageFormatter.applyPattern(pattern1);\r
125             Object[] paramArray = {new Integer(7)};\r
126             String tempBuffer = messageFormatter.format(paramArray);\r
127             if (!tempBuffer.equals("Impossible {1} has occurred -- status code is 7 and message is {2}."))\r
128                 errln("Tests arguments < substitution failed");\r
129             logln("Formatted with 7 : " + tempBuffer);\r
130             ParsePosition status = new ParsePosition(0);\r
131             Object[] objs = messageFormatter.parse(tempBuffer, status);\r
132             if (objs[paramArray.length] != null)\r
133                 errln("Parse failed with more than expected arguments");\r
134             for (int i = 0; i < objs.length; i++) {\r
135                 if (objs[i] != null && !objs[i].toString().equals(paramArray[i].toString())) {\r
136                     errln("Parse failed on object " + objs[i] + " at index : " + i);\r
137                 }\r
138             }\r
139             tempBuffer = messageFormatter.format(null);\r
140             if (!tempBuffer.equals("Impossible {1} has occurred -- status code is {0} and message is {2}."))\r
141                 errln("Tests with no arguments failed");\r
142             logln("Formatted with null : " + tempBuffer);\r
143             logln("Apply with pattern : " + pattern2);\r
144             messageFormatter.applyPattern(pattern2);\r
145             tempBuffer = messageFormatter.format(paramArray);\r
146             if (!tempBuffer.equals("Double ' Quotes 7 test and quoted {1} test plus other {2} stuff."))\r
147                 errln("quote format test (w/ params) failed.");\r
148             logln("Formatted with params : " + tempBuffer);\r
149             tempBuffer = messageFormatter.format(null);\r
150             if (!tempBuffer.equals("Double ' Quotes {0} test and quoted {1} test plus other {2} stuff."))\r
151                 errln("quote format test (w/ null) failed.");\r
152             logln("Formatted with null : " + tempBuffer);\r
153             logln("toPattern : " + messageFormatter.toPattern());\r
154         } catch (Exception foo) {\r
155             warnln("Exception when formatting in bug 4031438. "+foo.getMessage());\r
156         }\r
157     }\r
158     public void Test4052223()\r
159     {\r
160         ParsePosition pos = new ParsePosition(0);\r
161         if (pos.getErrorIndex() != -1) {\r
162             errln("ParsePosition.getErrorIndex initialization failed.");\r
163         }\r
164         MessageFormat fmt = new MessageFormat("There are {0} apples growing on the {1} tree.");\r
165         String str = new String("There is one apple growing on the peach tree.");\r
166         Object[] objs = fmt.parse(str, pos);\r
167         logln("unparsable string , should fail at " + pos.getErrorIndex());\r
168         if (pos.getErrorIndex() == -1)\r
169             errln("Bug 4052223 failed : parsing string " + str);\r
170         pos.setErrorIndex(4);\r
171         if (pos.getErrorIndex() != 4)\r
172             errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4");\r
173         \r
174         if (objs != null) {\r
175             errln("objs should be null");\r
176         }\r
177         ChoiceFormat f = new ChoiceFormat(\r
178             "-1#are negative|0#are no or fraction|1#is one|1.0<is 1+|2#are two|2<are more than 2.");\r
179         pos.setIndex(0); pos.setErrorIndex(-1);\r
180         Number obj = f.parse("are negative", pos);\r
181         if (pos.getErrorIndex() != -1 && obj.doubleValue() == -1.0)\r
182             errln("Parse with \"are negative\" failed, at " + pos.getErrorIndex());\r
183         pos.setIndex(0); pos.setErrorIndex(-1);\r
184         obj = f.parse("are no or fraction ", pos);\r
185         if (pos.getErrorIndex() != -1 && obj.doubleValue() == 0.0)\r
186             errln("Parse with \"are no or fraction\" failed, at " + pos.getErrorIndex());\r
187         pos.setIndex(0); pos.setErrorIndex(-1);\r
188         obj = f.parse("go postal", pos);\r
189         if (pos.getErrorIndex() == -1 && !Double.isNaN(obj.doubleValue()))\r
190             errln("Parse with \"go postal\" failed, at " + pos.getErrorIndex());\r
191     }\r
192     /* @bug 4104976\r
193      * ChoiceFormat.equals(null) throws NullPointerException\r
194      */\r
195     public void Test4104976()\r
196     {\r
197         double[] limits = {1, 20};\r
198         String[] formats = {"xyz", "abc"};\r
199         ChoiceFormat cf = new ChoiceFormat(limits, formats);\r
200         try {\r
201             log("Compares to null is always false, returned : ");\r
202             logln(cf.equals(null) ? "TRUE" : "FALSE");\r
203         } catch (Exception foo) {\r
204             errln("ChoiceFormat.equals(null) throws exception.");\r
205         }\r
206     }\r
207     /* @bug 4106659\r
208      * ChoiceFormat.ctor(double[], String[]) doesn't check\r
209      * whether lengths of input arrays are equal.\r
210      */\r
211     public void Test4106659()\r
212     {\r
213         double[] limits = {1, 2, 3};\r
214         String[] formats = {"one", "two"};\r
215         ChoiceFormat cf = null;\r
216         try {\r
217             cf = new ChoiceFormat(limits, formats);\r
218         } catch (Exception foo) {\r
219             logln("ChoiceFormat constructor should check for the array lengths");\r
220             cf = null;\r
221         }\r
222         if (cf != null) errln(cf.format(5));\r
223     }\r
224 \r
225     /* @bug 4106660\r
226      * ChoiceFormat.ctor(double[], String[]) allows unordered double array.\r
227      * This is not a bug, added javadoc to emphasize the use of limit\r
228      * array must be in ascending order.\r
229      */\r
230     public void Test4106660()\r
231     {\r
232         double[] limits = {3, 1, 2};\r
233         String[] formats = {"Three", "One", "Two"};\r
234         ChoiceFormat cf = new ChoiceFormat(limits, formats);\r
235         double d = 5.0;\r
236         String str = cf.format(d);\r
237         if (!str.equals("Two"))\r
238             errln("format(" + d + ") = " + cf.format(d));\r
239     }\r
240 \r
241     /* @bug 4111739\r
242      * MessageFormat is incorrectly serialized/deserialized.\r
243      */\r
244     public void Test4111739()\r
245     {\r
246         MessageFormat format1 = null;\r
247         MessageFormat format2 = null;\r
248         ObjectOutputStream ostream = null;\r
249         ByteArrayOutputStream baos = null;\r
250         ObjectInputStream istream = null;\r
251 \r
252         try {\r
253             baos = new ByteArrayOutputStream();\r
254             ostream = new ObjectOutputStream(baos);\r
255         } catch(IOException e) {\r
256             errln("Unexpected exception : " + e.getMessage());\r
257             return;\r
258         }\r
259 \r
260         try {\r
261             format1 = new MessageFormat("pattern{0}");\r
262             ostream.writeObject(format1);\r
263             ostream.flush();\r
264 \r
265             byte bytes[] = baos.toByteArray();\r
266 \r
267             istream = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
268             format2 = (MessageFormat)istream.readObject();\r
269         } catch(Exception e) {\r
270             errln("Unexpected exception : " + e.getMessage());\r
271         }\r
272 \r
273         if (!format1.equals(format2)) {\r
274             errln("MessageFormats before and after serialization are not" +\r
275                 " equal\nformat1 = " + format1 + "(" + format1.toPattern() + ")\nformat2 = " +\r
276                 format2 + "(" + format2.toPattern() + ")");\r
277         } else {\r
278             logln("Serialization for MessageFormat is OK.");\r
279         }\r
280     }\r
281     /* @bug 4114743\r
282      * MessageFormat.applyPattern allows illegal patterns.\r
283      */\r
284     public void Test4114743()\r
285     {\r
286         String originalPattern = "initial pattern";\r
287         MessageFormat mf = new MessageFormat(originalPattern);\r
288         try {\r
289             String illegalPattern = "ab { '}' de";\r
290             mf.applyPattern(illegalPattern);\r
291             errln("illegal pattern: \"" + illegalPattern + "\"");\r
292         } catch (IllegalArgumentException foo) {\r
293             if (!originalPattern.equals(mf.toPattern()))\r
294                 errln("pattern after: \"" + mf.toPattern() + "\"");\r
295         }\r
296     }\r
297 \r
298     /* @bug 4116444\r
299      * MessageFormat.parse has different behavior in case of null.\r
300      */\r
301     public void Test4116444()\r
302     {\r
303         String[] patterns = {"", "one", "{0,date,short}"};\r
304         MessageFormat mf = new MessageFormat("");\r
305 \r
306         for (int i = 0; i < patterns.length; i++) {\r
307             String pattern = patterns[i];\r
308             mf.applyPattern(pattern);\r
309             try {\r
310                 Object[] array = mf.parse(null, new ParsePosition(0));\r
311                 logln("pattern: \"" + pattern + "\"");\r
312                 log(" parsedObjects: ");\r
313                 if (array != null) {\r
314                     log("{");\r
315                     for (int j = 0; j < array.length; j++) {\r
316                         if (array[j] != null)\r
317                             err("\"" + array[j].toString() + "\"");\r
318                         else\r
319                             log("null");\r
320                         if (j < array.length - 1) log(",");\r
321                     }\r
322                     log("}") ;\r
323                 } else {\r
324                     log("null");\r
325                 }\r
326                 logln("");\r
327             } catch (Exception e) {\r
328                 errln("pattern: \"" + pattern + "\"");\r
329                 errln("  Exception: " + e.getMessage());\r
330             }\r
331         }\r
332 \r
333     }\r
334     /* @bug 4114739 (FIX and add javadoc)\r
335      * MessageFormat.format has undocumented behavior about empty format objects.\r
336      */\r
337     public void Test4114739()\r
338     {\r
339 \r
340         MessageFormat mf = new MessageFormat("<{0}>");\r
341         Object[] objs1 = null;\r
342         Object[] objs2 = {};\r
343         Object[] objs3 = {null};\r
344         try {\r
345             logln("pattern: \"" + mf.toPattern() + "\"");\r
346             log("format(null) : ");\r
347             logln("\"" + mf.format(objs1) + "\"");\r
348             log("format({})   : ");\r
349             logln("\"" + mf.format(objs2) + "\"");\r
350             log("format({null}) :");\r
351             logln("\"" + mf.format(objs3) + "\"");\r
352         } catch (Exception e) {\r
353             errln("Exception thrown for null argument tests.");\r
354         }\r
355     }\r
356 \r
357     /* @bug 4113018\r
358      * MessageFormat.applyPattern works wrong with illegal patterns.\r
359      */\r
360     public void Test4113018()\r
361     {\r
362         String originalPattern = "initial pattern";\r
363         MessageFormat mf = new MessageFormat(originalPattern);\r
364         String illegalPattern = "format: {0, xxxYYY}";\r
365         logln("pattern before: \"" + mf.toPattern() + "\"");\r
366         logln("illegal pattern: \"" + illegalPattern + "\"");\r
367         try {\r
368             mf.applyPattern(illegalPattern);\r
369             errln("Should have thrown IllegalArgumentException for pattern : " + illegalPattern);\r
370         } catch (IllegalArgumentException e) {\r
371             if (!originalPattern.equals(mf.toPattern()))\r
372                 errln("pattern after: \"" + mf.toPattern() + "\"");\r
373         }\r
374     }\r
375     /* @bug 4106661\r
376      * ChoiceFormat is silent about the pattern usage in javadoc.\r
377      */\r
378     public void Test4106661()\r
379     {\r
380         ChoiceFormat fmt = new ChoiceFormat(\r
381           "-1#are negative| 0#are no or fraction | 1#is one |1.0<is 1+ |2#are two |2<are more than 2.");\r
382         logln("Formatter Pattern : " + fmt.toPattern());\r
383 \r
384         logln("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));\r
385         logln("Format with -1.0 : " + fmt.format(-1.0));\r
386         logln("Format with 0 : " + fmt.format(0));\r
387         logln("Format with 0.9 : " + fmt.format(0.9));\r
388         logln("Format with 1.0 : " + fmt.format(1));\r
389         logln("Format with 1.5 : " + fmt.format(1.5));\r
390         logln("Format with 2 : " + fmt.format(2));\r
391         logln("Format with 2.1 : " + fmt.format(2.1));\r
392         logln("Format with NaN : " + fmt.format(Double.NaN));\r
393         logln("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));\r
394     }\r
395     /* @bug 4094906\r
396      * ChoiceFormat should accept \u221E as eq. to INF.\r
397      */\r
398     public void Test4094906()\r
399     {\r
400         ChoiceFormat fmt = new ChoiceFormat(\r
401           "-\u221E<are negative|0<are no or fraction|1#is one|1.0<is 1+|\u221E<are many.");\r
402         if (!fmt.toPattern().startsWith("-\u221E<are negative|0.0<are no or fraction|1.0#is one|1.0<is 1+|\u221E<are many."))\r
403             errln("Formatter Pattern : " + fmt.toPattern());\r
404         logln("Format with -INF : " + fmt.format(Double.NEGATIVE_INFINITY));\r
405         logln("Format with -1.0 : " + fmt.format(-1.0));\r
406         logln("Format with 0 : " + fmt.format(0));\r
407         logln("Format with 0.9 : " + fmt.format(0.9));\r
408         logln("Format with 1.0 : " + fmt.format(1));\r
409         logln("Format with 1.5 : " + fmt.format(1.5));\r
410         logln("Format with 2 : " + fmt.format(2));\r
411         logln("Format with +INF : " + fmt.format(Double.POSITIVE_INFINITY));\r
412     }\r
413 \r
414     /* @bug 4118592\r
415      * MessageFormat.parse fails with ChoiceFormat.\r
416      */\r
417     public void Test4118592()\r
418     {\r
419         MessageFormat mf = new MessageFormat("");\r
420         String pattern = "{0,choice,1#YES|2#NO}";\r
421         String prefix = "";\r
422         for (int i = 0; i < 5; i++) {\r
423             String formatted = prefix + "YES";\r
424             mf.applyPattern(prefix + pattern);\r
425             prefix += "x";\r
426             Object[] objs = mf.parse(formatted, new ParsePosition(0));\r
427             logln(i + ". pattern :\"" + mf.toPattern() + "\"");\r
428             log(" \"" + formatted + "\" parsed as ");\r
429             if (objs == null) logln("  null");\r
430             else logln("  " + objs[0]);\r
431         }\r
432     }\r
433     /* @bug 4118594\r
434      * MessageFormat.parse fails for some patterns.\r
435      */\r
436     public void Test4118594()\r
437     {\r
438         MessageFormat mf = new MessageFormat("{0}, {0}, {0}");\r
439         String forParsing = "x, y, z";\r
440         Object[] objs = mf.parse(forParsing, new ParsePosition(0));\r
441         logln("pattern: \"" + mf.toPattern() + "\"");\r
442         logln("text for parsing: \"" + forParsing + "\"");\r
443         if (!objs[0].toString().equals("z"))\r
444             errln("argument0: \"" + objs[0] + "\"");\r
445         mf.setLocale(Locale.US);\r
446         mf.applyPattern("{0,number,#.##}, {0,number,#.#}");\r
447         Object[] oldobjs = {new Double(3.1415)};\r
448         String result = mf.format( oldobjs );\r
449         logln("pattern: \"" + mf.toPattern() + "\"");\r
450         logln("text for parsing: \"" + result + "\"");\r
451         // result now equals "3.14, 3.1"\r
452         if (!result.equals("3.14, 3.1"))\r
453             errln("result = " + result);\r
454         Object[] newobjs = mf.parse(result, new ParsePosition(0));\r
455         // newobjs now equals {new Double(3.1)}\r
456         if (((Number)newobjs[0]).doubleValue() != 3.1) // was (Double) [alan]\r
457             errln( "newobjs[0] = " + newobjs[0]);\r
458     }\r
459     /* @bug 4105380\r
460      * When using ChoiceFormat, MessageFormat is not good for I18n.\r
461      */\r
462     public void Test4105380()\r
463     {\r
464         String patternText1 = "The disk \"{1}\" contains {0}.";\r
465         String patternText2 = "There are {0} on the disk \"{1}\"";\r
466         MessageFormat form1 = new MessageFormat(patternText1);\r
467         MessageFormat form2 = new MessageFormat(patternText2);\r
468         double[] filelimits = {0,1,2};\r
469         String[] filepart = {"no files","one file","{0,number} files"};\r
470         ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);\r
471         form1.setFormat(1, fileform);\r
472         form2.setFormat(0, fileform);\r
473         Object[] testArgs = {new Long(12373), "MyDisk"};\r
474         logln(form1.format(testArgs));\r
475         logln(form2.format(testArgs));\r
476     }\r
477     /* @bug 4120552\r
478      * MessageFormat.parse incorrectly sets errorIndex.\r
479      */\r
480     public void Test4120552()\r
481     {\r
482         MessageFormat mf = new MessageFormat("pattern");\r
483         String texts[] = {"pattern", "pat", "1234"};\r
484         logln("pattern: \"" + mf.toPattern() + "\"");\r
485         for (int i = 0; i < texts.length; i++) {\r
486             ParsePosition pp = new ParsePosition(0);\r
487             Object[] objs = mf.parse(texts[i], pp);\r
488             log("  text for parsing: \"" + texts[i] + "\"");\r
489             if (objs == null) {\r
490                 logln("  (incorrectly formatted string)");\r
491                 if (pp.getErrorIndex() == -1)\r
492                     errln("Incorrect error index: " + pp.getErrorIndex());\r
493             } else {\r
494                 logln("  (correctly formatted string)");\r
495             }\r
496         }\r
497     }\r
498 \r
499     /**\r
500      * @bug 4142938\r
501      * MessageFormat handles single quotes in pattern wrong.\r
502      * This is actually a problem in ChoiceFormat; it doesn't\r
503      * understand single quotes.\r
504      */\r
505     public void Test4142938() {\r
506         String pat = "''Vous'' {0,choice,0#n''|1#}avez s\u00E9lectionne\u00E9 " + \r
507             "{0,choice,0#aucun|1#{0}} client{0,choice,0#s|1#|2#s} " + \r
508             "personnel{0,choice,0#s|1#|2#s}.";\r
509         MessageFormat mf = new MessageFormat(pat);\r
510 \r
511         String[] PREFIX = {\r
512             "'Vous' n'avez s\u00E9lectionne\u00E9 aucun clients personnels.",\r
513             "'Vous' avez s\u00E9lectionne\u00E9 ",\r
514             "'Vous' avez s\u00E9lectionne\u00E9 "\r
515         };  \r
516         String[] SUFFIX = {\r
517             null,\r
518             " client personnel.",\r
519             " clients personnels."\r
520         };\r
521     \r
522         for (int i=0; i<3; i++) {\r
523             String out = mf.format(new Object[]{new Integer(i)});\r
524             if (SUFFIX[i] == null) {\r
525                 if (!out.equals(PREFIX[i]))\r
526                     errln("" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"");\r
527             }\r
528             else {\r
529                 if (!out.startsWith(PREFIX[i]) ||\r
530                     !out.endsWith(SUFFIX[i]))\r
531                     errln("" + i + ": Got \"" + out + "\"; Want \"" + PREFIX[i] + "\"...\"" +\r
532                           SUFFIX[i] + "\"");\r
533             }\r
534         }\r
535     }\r
536 \r
537     /**\r
538      * @bug 4142938\r
539      * Test the applyPattern and toPattern handling of single quotes\r
540      * by ChoiceFormat.  (This is in here because this was a bug reported\r
541      * against MessageFormat.)  The single quote is used to quote the\r
542      * pattern characters '|', '#', '<', and '\u2264'.  Two quotes in a row\r
543      * is a quote literal.\r
544      */\r
545     public void TestChoicePatternQuote() {\r
546         String[] DATA = {\r
547             // Pattern                  0 value           1 value\r
548             "0#can''t|1#can",           "can't",          "can",\r
549             "0#'pound(#)=''#'''|1#xyz", "pound(#)='#'",   "xyz",\r
550             "0#'1<2 | 1\u22641'|1#''",  "1<2 | 1\u22641", "'",\r
551         };\r
552         for (int i=0; i<DATA.length; i+=3) {\r
553             try {\r
554                 ChoiceFormat cf = new ChoiceFormat(DATA[i]);\r
555                 for (int j=0; j<=1; ++j) {\r
556                     String out = cf.format(j);\r
557                     if (!out.equals(DATA[i+1+j]))\r
558                         errln("Fail: Pattern \"" + DATA[i] + "\" x "+j+" -> " +\r
559                               out + "; want \"" + DATA[i+1+j] + '"');\r
560                 }\r
561                 String pat = cf.toPattern();\r
562                 String pat2 = new ChoiceFormat(pat).toPattern();\r
563                 if (!pat.equals(pat2))\r
564                     errln("Fail: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"');\r
565                 else\r
566                     logln("Ok: Pattern \"" + DATA[i] + "\" x toPattern -> \"" + pat + '"');\r
567             }\r
568             catch (IllegalArgumentException e) {\r
569                 errln("Fail: Pattern \"" + DATA[i] + "\" -> " + e);\r
570             }\r
571         }\r
572     }\r
573 \r
574     /**\r
575      * @bug 4112104\r
576      * MessageFormat.equals(null) throws a NullPointerException.  The JLS states\r
577      * that it should return false.\r
578      */\r
579     public void Test4112104() {\r
580         MessageFormat format = new MessageFormat("");\r
581         try {\r
582             // This should NOT throw an exception\r
583             if (format.equals(null)) {\r
584                 // It also should return false\r
585                 errln("MessageFormat.equals(null) returns false");\r
586             }\r
587         }\r
588         catch (NullPointerException e) {\r
589             errln("MessageFormat.equals(null) throws " + e);\r
590         }\r
591     }\r
592 \r
593     /**\r
594      * @bug 4169959\r
595      * MessageFormat does not format null objects. CANNOT REPRODUCE THIS BUG.\r
596      */\r
597     public void Test4169959() {\r
598         // This works\r
599         logln(MessageFormat.format( "This will {0}",\r
600                                     new String[]{"work"} ) );\r
601         \r
602         // This fails\r
603         logln(MessageFormat.format( "This will {0}",\r
604                                     new Object[]{ null } ) );\r
605     }\r
606     \r
607     public void test4232154() {\r
608         boolean gotException = false;\r
609         try {\r
610             new MessageFormat("The date is {0:date}");\r
611         } catch (Exception e) {\r
612             gotException = true;\r
613             if (!(e instanceof IllegalArgumentException)) {\r
614                 throw new RuntimeException("got wrong exception type");\r
615             }\r
616             if ("argument number too large at ".equals(e.getMessage())) {\r
617                 throw new RuntimeException("got wrong exception message");\r
618             }\r
619         }\r
620         if (!gotException) {\r
621             throw new RuntimeException("didn't get exception for invalid input");\r
622         }\r
623     }\r
624     \r
625     public void test4293229() {\r
626         MessageFormat format = new MessageFormat("'''{'0}'' '''{0}'''");\r
627         Object[] args = { null };\r
628         String expected = "'{0}' '{0}'";\r
629         String result = format.format(args);\r
630         if (!result.equals(expected)) {\r
631             throw new RuntimeException("wrong format result - expected \"" +\r
632                     expected + "\", got \"" + result + "\"");\r
633         }\r
634     }\r
635      \r
636     // This test basically ensures that the tests defined above also work with\r
637     // valid named arguments.\r
638     public void testBugTestsWithNamesArguments() {\r
639         \r
640       { // Taken from Test4031438().\r
641         String pattern1 = "Impossible {arg1} has occurred -- status code is {arg0} and message is {arg2}.";\r
642         String pattern2 = "Double '' Quotes {ARG_ZERO} test and quoted '{ARG_ONE}' test plus 'other {ARG_TWO} stuff'.";\r
643 \r
644         MessageFormat messageFormatter = new MessageFormat("");\r
645 \r
646         try {\r
647             logln("Apply with pattern : " + pattern1);\r
648             messageFormatter.applyPattern(pattern1);\r
649             HashMap paramsMap = new HashMap();\r
650             paramsMap.put("arg0", new Integer(7));\r
651             String tempBuffer = messageFormatter.format(paramsMap);\r
652             if (!tempBuffer.equals("Impossible {arg1} has occurred -- status code is 7 and message is {arg2}."))\r
653                 errln("Tests arguments < substitution failed");\r
654             logln("Formatted with 7 : " + tempBuffer);\r
655             ParsePosition status = new ParsePosition(0);\r
656             Map objs = messageFormatter.parseToMap(tempBuffer, status);\r
657             if (objs.get("arg1") != null || objs.get("arg2") != null)\r
658                 errln("Parse failed with more than expected arguments");\r
659             for (Iterator keyIter = objs.keySet().iterator();\r
660                  keyIter.hasNext();) {\r
661                 String key = (String) keyIter.next();\r
662                 if (objs.get(key) != null && !objs.get(key).toString().equals(paramsMap.get(key).toString())) {\r
663                     errln("Parse failed on object " + objs.get(key) + " with argument name : " + key );\r
664                 }\r
665             }\r
666             tempBuffer = messageFormatter.format(null);\r
667             if (!tempBuffer.equals("Impossible {arg1} has occurred -- status code is {arg0} and message is {arg2}."))\r
668                 errln("Tests with no arguments failed");\r
669             logln("Formatted with null : " + tempBuffer);\r
670             logln("Apply with pattern : " + pattern2);\r
671             messageFormatter.applyPattern(pattern2);\r
672             paramsMap.clear();\r
673             paramsMap.put("ARG_ZERO", new Integer(7));\r
674             tempBuffer = messageFormatter.format(paramsMap);\r
675             if (!tempBuffer.equals("Double ' Quotes 7 test and quoted {ARG_ONE} test plus other {ARG_TWO} stuff."))\r
676                 errln("quote format test (w/ params) failed.");\r
677             logln("Formatted with params : " + tempBuffer);\r
678             tempBuffer = messageFormatter.format(null);\r
679             if (!tempBuffer.equals("Double ' Quotes {ARG_ZERO} test and quoted {ARG_ONE} test plus other {ARG_TWO} stuff."))\r
680                 errln("quote format test (w/ null) failed.");\r
681             logln("Formatted with null : " + tempBuffer);\r
682             logln("toPattern : " + messageFormatter.toPattern());\r
683         } catch (Exception foo) {\r
684             warnln("Exception when formatting in bug 4031438. "+foo.getMessage());\r
685         }\r
686       }{ // Taken from Test4052223().\r
687         ParsePosition pos = new ParsePosition(0);\r
688         if (pos.getErrorIndex() != -1) {\r
689             errln("ParsePosition.getErrorIndex initialization failed.");\r
690         }\r
691         MessageFormat fmt = new MessageFormat("There are {numberOfApples} apples growing on the {whatKindOfTree} tree.");\r
692         String str = new String("There is one apple growing on the peach tree.");\r
693         Map objs = fmt.parseToMap(str, pos);\r
694         logln("unparsable string , should fail at " + pos.getErrorIndex());\r
695         if (pos.getErrorIndex() == -1)\r
696             errln("Bug 4052223 failed : parsing string " + str);\r
697         pos.setErrorIndex(4);\r
698         if (pos.getErrorIndex() != 4)\r
699             errln("setErrorIndex failed, got " + pos.getErrorIndex() + " instead of 4");\r
700         if (objs != null)\r
701             errln("unparsable string, should return null");\r
702     }{ // Taken from Test4111739().\r
703         MessageFormat format1 = null;\r
704         MessageFormat format2 = null;\r
705         ObjectOutputStream ostream = null;\r
706         ByteArrayOutputStream baos = null;\r
707         ObjectInputStream istream = null;\r
708 \r
709         try {\r
710             baos = new ByteArrayOutputStream();\r
711             ostream = new ObjectOutputStream(baos);\r
712         } catch(IOException e) {\r
713             errln("Unexpected exception : " + e.getMessage());\r
714             return;\r
715         }\r
716 \r
717         try {\r
718             format1 = new MessageFormat("pattern{argument}");\r
719             ostream.writeObject(format1);\r
720             ostream.flush();\r
721 \r
722             byte bytes[] = baos.toByteArray();\r
723 \r
724             istream = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
725             format2 = (MessageFormat)istream.readObject();\r
726         } catch(Exception e) {\r
727             errln("Unexpected exception : " + e.getMessage());\r
728         }\r
729 \r
730         if (!format1.equals(format2)) {\r
731             errln("MessageFormats before and after serialization are not" +\r
732                 " equal\nformat1 = " + format1 + "(" + format1.toPattern() + ")\nformat2 = " +\r
733                 format2 + "(" + format2.toPattern() + ")");\r
734         } else {\r
735             logln("Serialization for MessageFormat is OK.");\r
736         }\r
737     }{ // Taken from Test4116444().\r
738         String[] patterns = {"", "one", "{namedArgument,date,short}"};\r
739         MessageFormat mf = new MessageFormat("");\r
740 \r
741         for (int i = 0; i < patterns.length; i++) {\r
742             String pattern = patterns[i];\r
743             mf.applyPattern(pattern);\r
744             try {\r
745                 Map objs = mf.parseToMap(null, new ParsePosition(0));\r
746                 logln("pattern: \"" + pattern + "\"");\r
747                 log(" parsedObjects: ");\r
748                 if (objs != null) {\r
749                     log("{");\r
750                     for (Iterator keyIter = objs.keySet().iterator();\r
751                          keyIter.hasNext();) {\r
752                         String key = (String)keyIter.next();\r
753                         if (objs.get(key) != null) {\r
754                             err("\"" + objs.get(key).toString() + "\"");\r
755                         } else {\r
756                             log("null");\r
757                         }\r
758                         if (keyIter.hasNext()) {\r
759                             log(",");\r
760                         }\r
761                     }\r
762                     log("}") ;\r
763                 } else {\r
764                     log("null");\r
765                 }\r
766                 logln("");\r
767             } catch (Exception e) {\r
768                 errln("pattern: \"" + pattern + "\"");\r
769                 errln("  Exception: " + e.getMessage());\r
770             }\r
771         }\r
772     }{ // Taken from Test4114739().\r
773         MessageFormat mf = new MessageFormat("<{arg}>");\r
774         Map objs1 = null;\r
775         Map objs2 = new HashMap();\r
776         Map objs3 = new HashMap();\r
777         objs3.put("arg", null);\r
778         try {\r
779             logln("pattern: \"" + mf.toPattern() + "\"");\r
780             log("format(null) : ");\r
781             logln("\"" + mf.format(objs1) + "\"");\r
782             log("format({})   : ");\r
783             logln("\"" + mf.format(objs2) + "\"");\r
784             log("format({null}) :");\r
785             logln("\"" + mf.format(objs3) + "\"");\r
786         } catch (Exception e) {\r
787             errln("Exception thrown for null argument tests.");\r
788         } \r
789     }{ // Taken from Test4118594().\r
790         String argName = "something_stupid";\r
791         MessageFormat mf = new MessageFormat("{"+ argName + "}, {" + argName + "}, {" + argName + "}");\r
792         String forParsing = "x, y, z";\r
793         Map objs = mf.parseToMap(forParsing, new ParsePosition(0));\r
794         logln("pattern: \"" + mf.toPattern() + "\"");\r
795         logln("text for parsing: \"" + forParsing + "\"");\r
796         if (!objs.get(argName).toString().equals("z"))\r
797             errln("argument0: \"" + objs.get(argName) + "\"");\r
798         mf.setLocale(Locale.US);\r
799         mf.applyPattern("{" + argName + ",number,#.##}, {" + argName + ",number,#.#}");\r
800         Map oldobjs = new HashMap();\r
801         oldobjs.put(argName, new Double(3.1415));\r
802         String result = mf.format( oldobjs );\r
803         logln("pattern: \"" + mf.toPattern() + "\"");\r
804         logln("text for parsing: \"" + result + "\"");\r
805         // result now equals "3.14, 3.1"\r
806         if (!result.equals("3.14, 3.1"))\r
807             errln("result = " + result);\r
808         Map newobjs = mf.parseToMap(result, new ParsePosition(0));\r
809         // newobjs now equals {new Double(3.1)}\r
810         if (((Number)newobjs.get(argName)).doubleValue() != 3.1) // was (Double) [alan]\r
811             errln( "newobjs.get(argName) = " + newobjs.get(argName));\r
812     }{ // Taken from Test4105380().\r
813         String patternText1 = "The disk \"{diskName}\" contains {numberOfFiles}.";\r
814         String patternText2 = "There are {numberOfFiles} on the disk \"{diskName}\"";\r
815         MessageFormat form1 = new MessageFormat(patternText1);\r
816         MessageFormat form2 = new MessageFormat(patternText2);\r
817         double[] filelimits = {0,1,2};\r
818         String[] filepart = {"no files","one file","{numberOfFiles,number} files"};\r
819         ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);\r
820         form1.setFormat(1, fileform);\r
821         form2.setFormat(0, fileform);\r
822         Map testArgs = new HashMap();\r
823         testArgs.put("diskName", "MyDisk");\r
824         testArgs.put("numberOfFiles", new Long(12373));\r
825         logln(form1.format(testArgs));\r
826         logln(form2.format(testArgs));\r
827     }{ // Taken from test4293229().\r
828         MessageFormat format = new MessageFormat("'''{'myNamedArgument}'' '''{myNamedArgument}'''");\r
829         Map args = new HashMap();\r
830         String expected = "'{myNamedArgument}' '{myNamedArgument}'";\r
831         String result = format.format(args);\r
832         if (!result.equals(expected)) {\r
833             throw new RuntimeException("wrong format result - expected \"" +\r
834                     expected + "\", got \"" + result + "\"");\r
835         }\r
836     }\r
837   }\r
838 }\r
839 \r