View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.text;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  import static org.junit.jupiter.api.Assertions.assertNotEquals;
21  import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
22  
23  import java.text.DateFormat;
24  import java.text.FieldPosition;
25  import java.text.Format;
26  import java.text.MessageFormat;
27  import java.text.NumberFormat;
28  import java.text.ParsePosition;
29  import java.util.Arrays;
30  import java.util.Calendar;
31  import java.util.Collections;
32  import java.util.HashMap;
33  import java.util.HashSet;
34  import java.util.Locale;
35  import java.util.Map;
36  
37  import org.apache.commons.lang3.AbstractLangTest;
38  import org.junit.jupiter.api.BeforeEach;
39  import org.junit.jupiter.api.Test;
40  import org.junit.jupiter.params.ParameterizedTest;
41  import org.junit.jupiter.params.provider.MethodSource;
42  import org.junit.jupiter.params.provider.ValueSource;
43  import org.junitpioneer.jupiter.cartesian.ArgumentSets;
44  import org.junitpioneer.jupiter.cartesian.CartesianTest;
45  
46  /**
47   * Test case for {@link ExtendedMessageFormat}.
48   */
49  @Deprecated
50  class ExtendedMessageFormatTest extends AbstractLangTest {
51  
52      /**
53       * {@link Format} implementation which converts to lower case.
54       */
55      private static final class LowerCaseFormat extends Format {
56          private static final long serialVersionUID = 1L;
57  
58          @Override
59          public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
60              return toAppendTo.append(((String) obj).toLowerCase(Locale.ROOT));
61          }
62          @Override
63          public Object parseObject(final String source, final ParsePosition pos) {
64              throw new UnsupportedOperationException();
65          }
66      }
67  
68      /**
69       * {@link FormatFactory} implementation for lower case format.
70       */
71      private static final class LowerCaseFormatFactory implements FormatFactory {
72          private static final Format LOWER_INSTANCE = new LowerCaseFormat();
73  
74          @Override
75          public Format getFormat(final String name, final String arguments, final Locale locale) {
76              return LOWER_INSTANCE;
77          }
78      }
79  
80      /**
81       * Alternative ExtendedMessageFormat impl.
82       */
83      private static final class OtherExtendedMessageFormat extends ExtendedMessageFormat {
84          private static final long serialVersionUID = 1L;
85  
86          OtherExtendedMessageFormat(final String pattern, final Locale locale,
87                  final Map<String, ? extends FormatFactory> registry) {
88              super(pattern, locale, registry);
89          }
90  
91      }
92  
93      /**
94       * {@link FormatFactory} implementation to override date format "short" to "default".
95       */
96      private static final class OverrideShortDateFormatFactory implements FormatFactory {
97  
98          @Override
99          public Format getFormat(final String name, final String arguments, final Locale locale) {
100             return !"short".equals(arguments) ? null
101                     : locale == null ? DateFormat
102                             .getDateInstance(DateFormat.DEFAULT) : DateFormat
103                             .getDateInstance(DateFormat.DEFAULT, locale);
104         }
105     }
106 
107     /**
108      * {@link Format} implementation which converts to upper case.
109      */
110     private static final class UpperCaseFormat extends Format {
111         private static final long serialVersionUID = 1L;
112 
113         @Override
114         public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) {
115             return toAppendTo.append(((String) obj).toUpperCase(Locale.ROOT));
116         }
117 
118         @Override
119         public Object parseObject(final String source, final ParsePosition pos) {
120             throw new UnsupportedOperationException();
121         }
122     }
123 
124     /**
125      * {@link FormatFactory} implementation for upper case format.
126      */
127     private static final class UpperCaseFormatFactory implements FormatFactory {
128         private static final Format UPPER_INSTANCE = new UpperCaseFormat();
129 
130         @Override
131         public Format getFormat(final String name, final String arguments, final Locale locale) {
132             return UPPER_INSTANCE;
133         }
134     }
135 
136     static ArgumentSets testBuiltInChoiceFormatFactory() {
137         // @formatter:off
138         return ArgumentSets
139                 .argumentsForFirstParameter(Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5"))
140                 .argumentsForNextParameter(DateFormat.getAvailableLocales());
141         // @formatter:on
142     }
143 
144 //    /**
145 //     * Test extended formats with choice format.
146 //     *
147 //     * NOTE: FAILING - currently sub-formats not supported
148 //     */
149 //    void testExtendedWithChoiceFormat() {
150 //        String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}";
151 //        ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
152 //        assertPatterns(null, pattern, emf.toPattern());
153 //        try {
154 //            assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"}));
155 //            assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"}));
156 //        } catch (IllegalArgumentException e) {
157 //            // currently sub-formats not supported
158 //        }
159 //    }
160 
161 //    /**
162 //     * Test mixed extended and built-in formats with choice format.
163 //     *
164 //     * NOTE: FAILING - currently sub-formats not supported
165 //     */
166 //    void testExtendedAndBuiltInWithChoiceFormat() {
167 //        String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}";
168 //        Object[] lowArgs  = new Object[] {Integer.valueOf(1), "Low",  Double.valueOf("1234.56")};
169 //        Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")};
170 //        Locale[] availableLocales = ChoiceFormat.getAvailableLocales();
171 //        Locale[] testLocales = new Locale[availableLocales.length + 1];
172 //        testLocales[0] = null;
173 //        System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length);
174 //        for (int i = 0; i < testLocales.length; i++) {
175 //            NumberFormat nf = null;
176 //            NumberFormat cf = null;
177 //            ExtendedMessageFormat emf = null;
178 //            if (testLocales[i] == null) {
179 //                nf = NumberFormat.getNumberInstance();
180 //                cf = NumberFormat.getCurrencyInstance();
181 //                emf = new ExtendedMessageFormat(pattern, registry);
182 //            } else {
183 //                nf = NumberFormat.getNumberInstance(testLocales[i]);
184 //                cf = NumberFormat.getCurrencyInstance(testLocales[i]);
185 //                emf = new ExtendedMessageFormat(pattern, testLocales[i], registry);
186 //            }
187 //            assertPatterns(null, pattern, emf.toPattern());
188 //            try {
189 //                String lowExpected = lowArgs[0] + " low "    + nf.format(lowArgs[2]);
190 //                String highExpected = highArgs[0] + " HIGH "  + cf.format(highArgs[2]);
191 //                assertEquals(lowExpected,  emf.format(lowArgs));
192 //                assertEquals(highExpected, emf.format(highArgs));
193 //            } catch (IllegalArgumentException e) {
194 //                // currently sub-formats not supported
195 //            }
196 //        }
197 //    }
198 
199     static ArgumentSets testBuiltInDateTimeFormatFactory() {
200         // @formatter:off
201         return ArgumentSets
202                 .argumentsForFirstParameter(
203                         "1: {0,date,short}",
204                         "2: {0,date,medium}",
205                         "3: {0,date,long}",
206                         "4: {0,date,full}",
207                         "5: {0,date,d MMM yy}",
208                         "6: {0,time,short}",
209                         "7: {0,time,medium}",
210                         "8: {0,time,long}",
211                         "9: {0,time,full}",
212                         "10: {0,time,HH:mm}",
213                         "11: {0,date}", "12: {0,time}")
214                 .argumentsForNextParameter(DateFormat.getAvailableLocales());
215         // @formatter:on
216     }
217 
218     static ArgumentSets testBuiltInNumberFormatFactory() {
219         // @formatter:off
220         return ArgumentSets
221                 .argumentsForFirstParameter(
222                         "1: {0,number}",
223                         "2: {0,number,integer}",
224                         "3: {0,number,currency}",
225                         "4: {0,number,percent}",
226                         "5: {0,number,00000.000}")
227                 .argumentsForNextParameter(DateFormat.getAvailableLocales());
228         // @formatter:on
229     }
230 
231     static ArgumentSets testOverriddenBuiltinFormatFactory() {
232         // @formatter:off
233         return ArgumentSets
234                 .argumentsForFirstParameter(
235                         "1: {0,date}",
236                         "2: {0,date,medium}",
237                         "3: {0,date,long}",
238                         "4: {0,date,full}",
239                         "5: {0,date,d MMM yy}")
240                 .argumentsForNextParameter(DateFormat.getAvailableLocales());
241         // @formatter:on
242     }
243 
244     private final Map<String, FormatFactory> registry = new HashMap<>();
245 
246     /**
247      * Create an ExtendedMessageFormat for the specified pattern and locale and check the
248      * formatted output matches the expected result for the parameters.
249      * @param pattern string
250      * @param registryUnused map (currently unused)
251      * @param args Object[]
252      * @param locale Locale
253      */
254     private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) {
255         final StringBuilder buffer = new StringBuilder();
256         buffer.append("Pattern=[");
257         buffer.append(pattern);
258         buffer.append("], locale=[");
259         buffer.append(locale);
260         buffer.append("]");
261         final MessageFormat mf = createMessageFormat(pattern, locale);
262         final ExtendedMessageFormat emf;
263         if (locale == null) {
264             emf = new ExtendedMessageFormat(pattern);
265         } else {
266             emf = new ExtendedMessageFormat(pattern, locale);
267         }
268         assertEquals(mf.format(args), emf.format(args), "format "    + buffer);
269         assertEquals(mf.toPattern(), emf.toPattern(), "toPattern " + buffer);
270     }
271 
272     /**
273      * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4).
274      * @param pattern string
275      * @param locale Locale
276      * @return MessageFormat
277      */
278     private MessageFormat createMessageFormat(final String pattern, final Locale locale) {
279         final MessageFormat result = new MessageFormat(pattern);
280         if (locale != null) {
281             result.setLocale(locale);
282             result.applyPattern(pattern);
283         }
284         return result;
285     }
286 
287     @BeforeEach
288     public void setUp() {
289         registry.put("lower", new LowerCaseFormatFactory());
290         registry.put("upper", new UpperCaseFormatFactory());
291     }
292 
293     @Test
294     void testArgumentIndexTrailingWhitespaceAtEnd() {
295         assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0 ", new HashMap<>()));
296     }
297 
298     /**
299      * Test the built-in choice format.
300      */
301     @CartesianTest
302     @CartesianTest.MethodFactory("testBuiltInChoiceFormatFactory")
303     void testBuiltInChoiceFormat(final Object value, final Locale locale) {
304         String choicePattern;
305         choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}";
306         checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, (Locale) null);
307         checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, locale);
308         //
309         choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}";
310         checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, (Locale) null);
311         checkBuiltInFormat(value + ": " + choicePattern, null, new Object[] { value }, locale);
312     }
313 
314     /**
315      * Test the built-in date/time formats
316      */
317     @CartesianTest
318     @CartesianTest.MethodFactory("testBuiltInDateTimeFormatFactory")
319     void testBuiltInDateTimeFormat(final String pattern, final Locale locale) {
320         final Calendar cal = Calendar.getInstance();
321         cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
322         final Object[] args = { cal.getTime() };
323         checkBuiltInFormat(pattern, null, args, (Locale) null);
324         checkBuiltInFormat(pattern, null, args, locale);
325     }
326 
327     /**
328      * Test the built-in number formats.
329      */
330     @CartesianTest
331     @CartesianTest.MethodFactory("testBuiltInNumberFormatFactory")
332     void testBuiltInNumberFormat(final String pattern, final Locale locale) {
333         final Object[] args = { Double.valueOf("6543.21") };
334         checkBuiltInFormat(pattern, null, args, (Locale) null);
335         checkBuiltInFormat(pattern, null, args, locale);
336     }
337 
338     /**
339      * Test Bug LANG-917 - IndexOutOfBoundsException and/or infinite loop when using a choice pattern
340      */
341     @Test
342     void testEmbeddedPatternInChoice() {
343         final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!";
344         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
345         assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!");
346     }
347 
348     /**
349      * Test equals() and hashCode().
350      */
351     @Test
352     void testEqualsHashcode() {
353         final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
354         final Map<String, ? extends FormatFactory> otherRegistry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory());
355 
356         final String pattern = "Pattern: {0,testfmt}";
357         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
358 
359         ExtendedMessageFormat other;
360 
361         // Same object
362         assertEquals(emf, emf, "same, equals()");
363         assertEquals(emf.hashCode(), emf.hashCode(), "same, hashCode()");
364 
365         // Equal Object
366         other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
367         assertEquals(emf, other, "equal, equals()");
368         assertEquals(emf.hashCode(), other.hashCode(), "equal, hashCode()");
369 
370         // Different Class
371         other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
372         assertNotEquals(emf, other, "class, equals()");
373         assertEquals(emf.hashCode(), other.hashCode(), "class, hashCode()"); // same hash code
374 
375         // Different pattern
376         other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
377         assertNotEquals(emf, other, "pattern, equals()");
378         assertNotEquals(emf.hashCode(), other.hashCode(), "pattern, hashCode()");
379 
380         // Different registry
381         other = new ExtendedMessageFormat(pattern, Locale.US, otherRegistry);
382         assertNotEquals(emf, other, "registry, equals()");
383         assertNotEquals(emf.hashCode(), other.hashCode(), "registry, hashCode()");
384 
385         // Different Locale
386         other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
387         assertNotEquals(emf, other, "locale, equals()");
388         assertEquals(emf.hashCode(), other.hashCode(), "locale, hashCode()"); // same hash code
389     }
390 
391     /**
392      * Test Bug LANG-948 - Exception while using ExtendedMessageFormat and escaping braces
393      */
394     @Test
395     void testEscapedBraces_LANG_948() {
396         // message without placeholder because braces are escaped by quotes
397         final String pattern = "Message without placeholders '{}'";
398         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
399         assertEquals("Message without placeholders {}", emf.format(new Object[] {"DUMMY"}));
400 
401         // message with placeholder because quotes are escaped by quotes
402         final String pattern2 = "Message with placeholder ''{0}''";
403         final ExtendedMessageFormat emf2 = new ExtendedMessageFormat(pattern2, registry);
404         assertEquals("Message with placeholder 'DUMMY'", emf2.format(new Object[] {"DUMMY"}));
405     }
406 
407     /**
408      * Test Bug LANG-477 - out of memory error with escaped quote
409      */
410     @Test
411     void testEscapedQuote_LANG_477() {
412         final String pattern = "it''s a {0,lower} 'test'!";
413         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
414         assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"}));
415     }
416 
417     /**
418      * Test extended and built-in formats with available locales.
419      */
420     @Test
421     void testExtendedAndBuiltInFormatsWithAvailableLocales() {
422         final String extendedPattern = "Name: {0,upper} ";
423         final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
424         final String pattern = extendedPattern + builtinsPattern;
425 
426         final Calendar cal = Calendar.getInstance();
427         cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
428         final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
429 
430         final HashSet<Locale> testLocales = new HashSet<>(Arrays.asList(DateFormat.getAvailableLocales()));
431         testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales()));
432 
433         for (final Locale locale : testLocales) {
434             final MessageFormat builtins = createMessageFormat(builtinsPattern, locale);
435             final String expectedPattern = extendedPattern + builtins.toPattern();
436             final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, locale, registry);
437             assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for locale " + locale);
438 
439             final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
440             final NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
441             final StringBuilder expected = new StringBuilder();
442             expected.append("Name: ");
443             expected.append(args[0].toString().toUpperCase(locale));
444             expected.append(" DOB: ");
445             expected.append(df.format(args[1]));
446             expected.append(" Salary: ");
447             expected.append(nf.format(args[2]));
448             assertEquals(expected.toString(), emf.format(args), String.valueOf(locale));
449         }
450     }
451 
452     /**
453      * Test extended and built-in formats with the default locale.
454      */
455     @Test
456     void testExtendedAndBuiltInFormatsWithDefaultLocale() {
457         final String extendedPattern = "Name: {0,upper} ";
458         final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}";
459         final String pattern = extendedPattern + builtinsPattern;
460 
461         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
462         final MessageFormat builtins = createMessageFormat(builtinsPattern, null);
463         final String expectedPattern = extendedPattern + builtins.toPattern();
464         assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for default locale");
465 
466         final Calendar cal = Calendar.getInstance();
467         cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
468         final Object[] args = {"John Doe", cal.getTime(), Double.valueOf("12345.67")};
469         final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
470         final NumberFormat nf = NumberFormat.getCurrencyInstance();
471         final StringBuilder expected = new StringBuilder();
472         expected.append("Name: ");
473         expected.append(args[0].toString().toUpperCase());
474         expected.append(" DOB: ");
475         expected.append(df.format(args[1]));
476         expected.append(" Salary: ");
477         expected.append(nf.format(args[2]));
478         assertEquals(expected.toString(), emf.format(args));
479     }
480 
481     /**
482      * Test extended formats.
483      */
484     @Test
485     void testExtendedFormats() {
486         final String pattern = "Lower: {0,lower} Upper: {1,upper}";
487         final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry);
488         assertEquals(pattern, emf.toPattern(), "TOPATTERN");
489         assertEquals(emf.format(new Object[] {"foo", "bar"}), "Lower: foo Upper: BAR");
490         assertEquals(emf.format(new Object[] {"Foo", "Bar"}), "Lower: foo Upper: BAR");
491         assertEquals(emf.format(new Object[] {"FOO", "BAR"}), "Lower: foo Upper: BAR");
492         assertEquals(emf.format(new Object[] {"FOO", "bar"}), "Lower: foo Upper: BAR");
493         assertEquals(emf.format(new Object[] {"foo", "BAR"}), "Lower: foo Upper: BAR");
494     }
495 
496     @CartesianTest
497     @CartesianTest.MethodFactory("testOverriddenBuiltinFormatFactory")
498     void testOverriddenBuiltinFormat(final String pattern, final Locale locale) {
499         final Calendar cal = Calendar.getInstance();
500         cal.set(2007, Calendar.JANUARY, 23);
501         final Object[] args = { cal.getTime() };
502         // check the non-overridden builtins:
503         checkBuiltInFormat(pattern, null, args, (Locale) null);
504         checkBuiltInFormat(pattern, null, args, locale);
505     }
506 
507     @ParameterizedTest
508     @MethodSource("java.text.DateFormat#getAvailableLocales")
509     void testOverriddenBuiltinFormat2(final Locale locale) {
510         final Calendar cal = Calendar.getInstance();
511         cal.set(2007, Calendar.JANUARY, 23);
512         final Object[] args = { cal.getTime() };
513         final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory());
514         // check the overridden format:
515         final MessageFormat dateDefault = createMessageFormat("{0,date}", locale);
516         final String pattern = "{0,date,short}";
517         final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry);
518         assertEquals(dateDefault.format(args), dateShort.format(args), "overridden date,short format");
519         assertEquals(pattern, dateShort.toPattern(), "overridden date,short pattern");
520     }
521 
522     /**
523      * A format element whose format style ends with a quoted literal immediately before the closing brace is a valid
524      * pattern (accepted by {@link MessageFormat} and by this class when no registry is supplied), but the registry
525      * parsing path rejected it with "Unterminated format element".
526      */
527     @Test
528     void testQuotedLiteralAtEndOfFormatElement() {
529         assertEquals("ABC", new ExtendedMessageFormat("{0,upper,'x'}", registry).format(new Object[] {"abc"}));
530         assertEquals("ABC", new ExtendedMessageFormat("{0,upper,'}'}", registry).format(new Object[] {"abc"}));
531         // a built-in format style ending in a quote only reaches the registry parser because the registry is non-null
532         assertEquals("5%", new ExtendedMessageFormat("{0,number,0'%'}", registry).format(new Object[] {Integer.valueOf(5)}));
533     }
534 
535     @Test
536     void testTruncatedFormatElementWithRegistry() {
537         // Sanity check to match JRE
538         assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{"));
539         assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{0,"));
540         assertThrowsExactly(IllegalArgumentException.class, () -> new MessageFormat("{0}extra{"));
541         // A format element left unterminated at the end of the pattern used to make the
542         // registry-based constructor seek one past the buffer and throw
543         // ArrayIndexOutOfBoundsException; it should report the documented
544         // IllegalArgumentException, as the plain constructor already does.
545         assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{", new HashMap<>()));
546         assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0,", new HashMap<>()));
547         assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat("{0}extra{", new HashMap<>()));
548     }
549 
550     /**
551      * Test that an unmatched quote is treated as closed at the end of the pattern,
552      * as by java.text.MessageFormat.
553      */
554     @Test
555     void testUnmatchedQuote() {
556         final ExtendedMessageFormat emf = new ExtendedMessageFormat("it's a {0,lower} test!", registry);
557         assertEquals("its a {0,lower} test!", emf.format(new Object[] {"DUMMY"}));
558         assertEquals(emf.format(new Object[] {"DUMMY"}),
559                 new ExtendedMessageFormat(emf.toPattern(), registry).format(new Object[] {"DUMMY"}));
560 
561         final ExtendedMessageFormat emf2 = new ExtendedMessageFormat("Don{0,upper}t panic: '", registry);
562         assertEquals("DonDUMMYt panic: ", emf2.format(new Object[] {"Dummy"}));
563         assertEquals("Don{0,upper}t panic: ", emf2.toPattern());
564         assertEquals(emf2.format(new Object[] {"Dummy"}),
565                 new ExtendedMessageFormat(emf2.toPattern(), registry).format(new Object[] {"Dummy"}));
566     }
567 
568     /**
569      * Checks that an unmatched quote does not make an unfinished format element valid.
570      *
571      * @param pattern pattern containing an unfinished format element
572      */
573     @ParameterizedTest
574     @ValueSource(strings = {"{0,number,0'foo}", "{0,date,yyyy'foo}", "{0,choice,0#'foo}", "{0,upper,'foo}"})
575     void testUnmatchedQuoteInFormatDescription(final String pattern) {
576         assertThrowsExactly(IllegalArgumentException.class, () -> new ExtendedMessageFormat(pattern, registry));
577     }
578 
579     /**
580      * Checks unmatched quotes against MessageFormat with an empty registry, including pattern round-tripping.
581      *
582      * @param pattern pattern containing an unmatched quote
583      */
584     @ParameterizedTest
585     @ValueSource(strings = {"Don't panic {0}", "'", "'''", "prefix '", "'{0}", "{0} suffix '{1}"})
586     void testUnmatchedQuoteWithEmptyRegistry(final String pattern) {
587         final Object[] args = {"Dummy", "Other"};
588         final MessageFormat expected = new MessageFormat(pattern, Locale.ROOT);
589         final ExtendedMessageFormat actual = new ExtendedMessageFormat(pattern, Locale.ROOT, Collections.emptyMap());
590         assertEquals(expected.format(args), actual.format(args));
591         assertEquals(expected.toPattern(), actual.toPattern());
592         final ExtendedMessageFormat reconstructed = new ExtendedMessageFormat(actual.toPattern(), Locale.ROOT, Collections.emptyMap());
593         assertEquals(actual.format(args), reconstructed.format(args));
594     }
595 
596 }