http://git-wip-us.apache.org/repos/asf/commons-text/blob/165c8e60/src/test/java/org/apache/commons/text/beta/AlphabetConverterTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/text/beta/AlphabetConverterTest.java b/src/test/java/org/apache/commons/text/beta/AlphabetConverterTest.java new file mode 100644 index 0000000..88e5926 --- /dev/null +++ b/src/test/java/org/apache/commons/text/beta/AlphabetConverterTest.java @@ -0,0 +1,204 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.text.beta; + +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.List; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +/** + * Unit tests for {@link AlphabetConverter}. + */ +public class AlphabetConverterTest { + + private static Character[] lower_case_english = {' ','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; + private static Character[] english_and_numbers = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ' }; + private static Character[] lower_case_english_and_numbers = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ' }; + private static Character[] numbers = {'0','1','2','3','4','5','6','7','8','9'}; + private static Character[] binary = {'0','1'}; + private static Character[] hebrew = {'_', ' ', '\u05e7','\u05e8','\u05d0','\u05d8','\u05d5','\u05df','\u05dd','\u05e4','\u05e9','\u05d3','\u05d2','\u05db','\u05e2','\u05d9','\u05d7','\u05dc','\u05da','\u05e3','\u05d6','\u05e1','\u05d1','\u05d4','\u05e0','\u05de','\u05e6','\u05ea','\u05e5'}; + private static Character[] empty = {}; + + private static Integer[] unicode = {32,35395,35397,36302,36291,35203,35201,35215,35219,35268,97,98,99,100,101,102,103,104,105,106,107,108,109,110,1001,1002,1003,1004,1005}; + private static Integer[] lower_case_english_codepoints = {32,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122}; + private static Integer[] doNotEncodePoints = {32,97,98,99}; // space, a, b, c + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void encodeFailureTest() throws UnsupportedEncodingException { + thrown.expect(UnsupportedEncodingException.class); + thrown.expectMessage("Couldn't find encoding for '3'"); + test(binary, numbers, empty, "3"); + } + + @Test + public void binaryTest() throws UnsupportedEncodingException { + test(binary, numbers, empty, "0", "1", "10", "11"); + test(numbers, binary, empty, "12345", "0"); + test(lower_case_english, binary, empty, "abc", "a"); + } + + @Test + public void hebrewTest() throws UnsupportedEncodingException { + test(hebrew, binary, empty, "\u05d0", "\u05e2", "\u05d0\u05dc\u05e3_\u05d0\u05d5\u05d4\u05d1\u05dc_\u05d1\u05d9\u05ea_\u05d6\u05d4_\u05d1\u05d9\u05ea_\u05d2\u05d9\u05de\u05dc_\u05d6\u05d4_\u05db\u05de\u05dc_\u05d2\u05d3\u05d5\u05dc"); + test(hebrew, numbers, empty, "\u05d0", "\u05e2", "\u05d0\u05dc\u05e3_\u05d0\u05d5\u05d4\u05d1\u05dc_\u05d1\u05d9\u05ea_\u05d6\u05d4_\u05d1\u05d9\u05ea_\u05d2\u05d9\u05de\u05dc_\u05d6\u05d4_\u05db\u05de\u05dc_\u05d2\u05d3\u05d5\u05dc"); + test(numbers, hebrew, empty, "123456789", "1", "5"); + test(lower_case_english, hebrew, empty, "this is a test"); + } + + @Test + public void doNotEncodeTest() throws UnsupportedEncodingException { + test(english_and_numbers, lower_case_english_and_numbers, lower_case_english, "1", "456", "abc", "ABC", "this will not be converted but THIS WILL"); + test(english_and_numbers, lower_case_english_and_numbers, numbers, "1", "456", "abc", "ABC", "this will be converted but 12345 and this will be"); + } + + private AlphabetConverter createJavadocExample() { + final Character[] original = {'a','b','c','d'}; + final Character[] encoding = {'0','1','d'}; + final Character[] doNotEncode = {'d'}; + + return AlphabetConverter.createConverterFromChars(original, encoding, doNotEncode); + } + + /* + * Test example in javadocs for consistency + */ + @Test + public void javadocExampleTest() throws UnsupportedEncodingException { + final AlphabetConverter ac = createJavadocExample(); + + Assert.assertEquals("00", ac.encode("a")); + Assert.assertEquals("01", ac.encode("b")); + Assert.assertEquals("0d", ac.encode("c")); + Assert.assertEquals("d", ac.encode("d")); + Assert.assertEquals("00010dd", ac.encode("abcd")); + } + + @Test + public void unexpectedEndwhileDecodingTest() throws UnsupportedEncodingException { + final String toDecode = "00d01d0"; + + thrown.expect(UnsupportedEncodingException.class); + thrown.expectMessage("Unexpected end of string while decoding " + toDecode); + + final AlphabetConverter ac = createJavadocExample(); + ac.decode(toDecode); + } + + @Test + public void unexpectedStringWhileDecodingTest() throws UnsupportedEncodingException { + final String toDecode = "00XX"; + + thrown.expect(UnsupportedEncodingException.class); + thrown.expectMessage("Unexpected string without decoding (XX) in " + toDecode); + + final AlphabetConverter ac = createJavadocExample(); + ac.decode(toDecode); + } + + /* + * Test constructor from code points + */ + @Test + public void unicodeTest() throws UnsupportedEncodingException { + final AlphabetConverter ac = AlphabetConverter.createConverter(unicode, lower_case_english_codepoints, doNotEncodePoints); + + Assert.assertEquals(2, ac.getEncodedCharLength()); + + final String original = "\u8a43\u8a45 \u8dce ab \u8dc3 c \u8983"; + final String encoded = ac.encode(original); + final String decoded = ac.decode(encoded); + + Assert.assertEquals("Encoded '" + original + "' into '" + encoded + "', but decoded into '" + decoded + "'", original, decoded); + } + + @Test + public void noEncodingLettersTest() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 0"); + + AlphabetConverter.createConverterFromChars(english_and_numbers, numbers, numbers); + } + + @Test + public void onlyOneEncodingLettersTest() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 1"); + + final Character[] numbersPlusUnderscore = Arrays.copyOf(numbers, numbers.length + 1); + numbersPlusUnderscore[numbersPlusUnderscore.length -1] = '_'; + + AlphabetConverter.createConverterFromChars(english_and_numbers, numbersPlusUnderscore, numbers); + } + + @Test + public void missingDoNotEncodeLettersFromEncodingTest() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Can not use 'do not encode' list because encoding alphabet does not contain"); + + AlphabetConverter.createConverterFromChars(english_and_numbers, lower_case_english, numbers); + } + + @Test + public void missingDoNotEncodeLettersFromOriginalTest() { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Can not use 'do not encode' list because original alphabet does not contain"); + + AlphabetConverter.createConverterFromChars(lower_case_english, english_and_numbers, numbers); + } + + private void test(final Character[] originalChars, final Character[] encodingChars, final Character[] doNotEncodeChars, final String... strings) throws UnsupportedEncodingException { + + final AlphabetConverter ac = AlphabetConverter.createConverterFromChars(originalChars, encodingChars, doNotEncodeChars); + + final AlphabetConverter reconstructedAlphabetConverter = AlphabetConverter.createConverterFromMap(ac.getOriginalToEncoded()); + + Assert.assertEquals(ac, reconstructedAlphabetConverter); + Assert.assertEquals(ac.hashCode(), reconstructedAlphabetConverter.hashCode()); + Assert.assertEquals(ac.toString(), reconstructedAlphabetConverter.toString()); + Assert.assertEquals(null, ac.encode(null)); // test null conversions + Assert.assertEquals("", ac.encode("")); // test empty conversion + + // test all the trial strings + for (final String s : strings) { + final String encoded = ac.encode(s); + + // test that only encoding chars are used + final List<Character> originalEncodingChars = Arrays.asList(encodingChars); + for (int i = 0; i < encoded.length(); i++) { + Assert.assertTrue(originalEncodingChars.contains(encoded.charAt(i))); + } + + final String decoded = ac.decode(encoded); + + // test that only the original alphabet is used after decoding + final List<Character> originalCharsList = Arrays.asList(originalChars); + for (int i = 0; i < decoded.length(); i++) { + Assert.assertTrue(originalCharsList.contains(decoded.charAt(i))); + } + + Assert.assertEquals("Encoded '" + s + "' into '" + encoded + "', but decoded into '" + decoded + "'", s, decoded); + } + } +}
http://git-wip-us.apache.org/repos/asf/commons-text/blob/165c8e60/src/test/java/org/apache/commons/text/beta/CharacterPredicatesTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/text/beta/CharacterPredicatesTest.java b/src/test/java/org/apache/commons/text/beta/CharacterPredicatesTest.java new file mode 100644 index 0000000..7e5d24e --- /dev/null +++ b/src/test/java/org/apache/commons/text/beta/CharacterPredicatesTest.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.text.beta; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests for {@link CharacterPredicates}. + */ +public class CharacterPredicatesTest { + + @Test + public void testLetters() throws Exception { + assertTrue(CharacterPredicates.LETTERS.test('a')); + assertTrue(CharacterPredicates.LETTERS.test('Z')); + + assertFalse(CharacterPredicates.LETTERS.test('1')); + assertFalse(CharacterPredicates.LETTERS.test('?')); + assertFalse(CharacterPredicates.LETTERS.test('@')); + } + + @Test + public void testDigits() { + assertTrue(CharacterPredicates.DIGITS.test('0')); + assertTrue(CharacterPredicates.DIGITS.test('9')); + + assertFalse(CharacterPredicates.DIGITS.test('-')); + assertFalse(CharacterPredicates.DIGITS.test('.')); + assertFalse(CharacterPredicates.DIGITS.test('L')); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/commons-text/blob/165c8e60/src/test/java/org/apache/commons/text/beta/CompositeFormatTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/text/beta/CompositeFormatTest.java b/src/test/java/org/apache/commons/text/beta/CompositeFormatTest.java new file mode 100644 index 0000000..a96a098 --- /dev/null +++ b/src/test/java/org/apache/commons/text/beta/CompositeFormatTest.java @@ -0,0 +1,85 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.text.beta; + +import org.junit.Test; +import static org.junit.Assert.*; +import java.text.FieldPosition; +import java.text.Format; +import java.text.ParsePosition; +import java.text.SimpleDateFormat; +import java.util.Locale; + +/** + * Unit tests for {@link CompositeFormat}. + */ +public class CompositeFormatTest { + + /** + * Ensures that the parse/format separation is correctly maintained. + */ + @Test + public void testCompositeFormat() { + + final Format parser = new Format() { + private static final long serialVersionUID = 1L; + + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + throw new UnsupportedOperationException("Not implemented"); + } + + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return null; // do nothing + } + }; + + final Format formatter = new Format() { + private static final long serialVersionUID = 1L; + + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return null; // do nothing + } + + @Override + public Object parseObject(final String source, final ParsePosition pos) { + throw new UnsupportedOperationException("Not implemented"); + } + }; + + final CompositeFormat composite = new CompositeFormat(parser, formatter); + + composite.parseObject("", null); + composite.format(new Object(), new StringBuffer(), null); + assertEquals( "Parser get method incorrectly implemented", parser, composite.getParser() ); + assertEquals( "Formatter get method incorrectly implemented", formatter, composite.getFormatter() ); + } + + @Test + public void testUsage() throws Exception { + final Format f1 = new SimpleDateFormat("MMddyyyy", Locale.ENGLISH); + final Format f2 = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH); + final CompositeFormat c = new CompositeFormat(f1, f2); + final String testString = "January 3, 2005"; + assertEquals(testString, c.format(c.parseObject("01032005"))); + assertEquals(testString, c.reformat("01032005")); + } + +} http://git-wip-us.apache.org/repos/asf/commons-text/blob/165c8e60/src/test/java/org/apache/commons/text/beta/ExtendedMessageFormatTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/text/beta/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/text/beta/ExtendedMessageFormatTest.java new file mode 100644 index 0000000..0c47b2a --- /dev/null +++ b/src/test/java/org/apache/commons/text/beta/ExtendedMessageFormatTest.java @@ -0,0 +1,497 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.text.beta; + +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.Format; +import java.text.MessageFormat; +import java.text.NumberFormat; +import java.text.ParsePosition; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; + +/** + * Test case for {@link ExtendedMessageFormat}. + */ +public class ExtendedMessageFormatTest { + + private final Map<String, FormatFactory> registry = new HashMap<>(); + + @Before + public void setUp() throws Exception { + registry.put("lower", new LowerCaseFormatFactory()); + registry.put("upper", new UpperCaseFormatFactory()); + } + + /** + * Test extended formats. + */ + @Test + public void testExtendedFormats() { + final String pattern = "Lower: {0,lower} Upper: {1,upper}"; + final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); + assertEquals("TOPATTERN", pattern, emf.toPattern()); + assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "bar"})); + assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"Foo", "Bar"})); + assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "BAR"})); + assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"FOO", "bar"})); + assertEquals("Lower: foo Upper: BAR", emf.format(new Object[] {"foo", "BAR"})); + } + + /** + * Test Bug LANG-477 - out of memory error with escaped quote + */ + @Test + public void testEscapedQuote_LANG_477() { + final String pattern = "it''s a {0,lower} 'test'!"; + final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); + assertEquals("it's a dummy test!", emf.format(new Object[] {"DUMMY"})); + } + + /** + * Test Bug LANG-917 - IndexOutOfBoundsException and/or infinite loop when using a choice pattern + */ + @Test + public void testEmbeddedPatternInChoice() { + final String pattern = "Hi {0,lower}, got {1,choice,0#none|1#one|1<{1,number}}, {2,upper}!"; + final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); + assertEquals(emf.format(new Object[] {"there", 3, "great"}), "Hi there, got 3, GREAT!"); + } + + /** + * Test Bug LANG-948 - Exception while using ExtendedMessageFormat and escaping braces + */ + @Test + public void testEscapedBraces_LANG_948() { + // message without placeholder because braces are escaped by quotes + final String pattern = "Message without placeholders '{}'"; + final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); + assertEquals("Message without placeholders {}", emf.format(new Object[] {"DUMMY"})); + + // message with placeholder because quotes are escaped by quotes + final String pattern2 = "Message with placeholder ''{0}''"; + final ExtendedMessageFormat emf2 = new ExtendedMessageFormat(pattern2, registry); + assertEquals("Message with placeholder 'DUMMY'", emf2.format(new Object[] {"DUMMY"})); + } + + /** + * Test extended and built in formats. + */ + @Test + public void testExtendedAndBuiltInFormats() { + final Calendar cal = Calendar.getInstance(); + cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); + final Object[] args = new Object[] {"John Doe", cal.getTime(), Double.valueOf("12345.67")}; + final String builtinsPattern = "DOB: {1,date,short} Salary: {2,number,currency}"; + final String extendedPattern = "Name: {0,upper} "; + final String pattern = extendedPattern + builtinsPattern; + + final HashSet<Locale> testLocales = new HashSet<>(); + testLocales.addAll(Arrays.asList(DateFormat.getAvailableLocales())); + testLocales.retainAll(Arrays.asList(NumberFormat.getAvailableLocales())); + testLocales.add(null); + + for (final Locale locale : testLocales) { + final MessageFormat builtins = createMessageFormat(builtinsPattern, locale); + final String expectedPattern = extendedPattern + builtins.toPattern(); + DateFormat df = null; + NumberFormat nf = null; + ExtendedMessageFormat emf = null; + if (locale == null) { + df = DateFormat.getDateInstance(DateFormat.SHORT); + nf = NumberFormat.getCurrencyInstance(); + emf = new ExtendedMessageFormat(pattern, registry); + } else { + df = DateFormat.getDateInstance(DateFormat.SHORT, locale); + nf = NumberFormat.getCurrencyInstance(locale); + emf = new ExtendedMessageFormat(pattern, locale, registry); + } + final StringBuilder expected = new StringBuilder(); + expected.append("Name: "); + expected.append(args[0].toString().toUpperCase()); + expected.append(" DOB: "); + expected.append(df.format(args[1])); + expected.append(" Salary: "); + expected.append(nf.format(args[2])); + assertEquals("pattern comparison for locale " + locale, expectedPattern, emf.toPattern()); + assertEquals(String.valueOf(locale), expected.toString(), emf.format(args)); + } + } + +// /** +// * Test extended formats with choice format. +// * +// * NOTE: FAILING - currently sub-formats not supported +// */ +// public void testExtendedWithChoiceFormat() { +// String pattern = "Choice: {0,choice,1.0#{1,lower}|2.0#{1,upper}}"; +// ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, registry); +// assertPatterns(null, pattern, emf.toPattern()); +// try { +// assertEquals("one", emf.format(new Object[] {Integer.valueOf(1), "ONE"})); +// assertEquals("TWO", emf.format(new Object[] {Integer.valueOf(2), "two"})); +// } catch (IllegalArgumentException e) { +// // currently sub-formats not supported +// } +// } + +// /** +// * Test mixed extended and built-in formats with choice format. +// * +// * NOTE: FAILING - currently sub-formats not supported +// */ +// public void testExtendedAndBuiltInWithChoiceFormat() { +// String pattern = "Choice: {0,choice,1.0#{0} {1,lower} {2,number}|2.0#{0} {1,upper} {2,number,currency}}"; +// Object[] lowArgs = new Object[] {Integer.valueOf(1), "Low", Double.valueOf("1234.56")}; +// Object[] highArgs = new Object[] {Integer.valueOf(2), "High", Double.valueOf("9876.54")}; +// Locale[] availableLocales = ChoiceFormat.getAvailableLocales(); +// Locale[] testLocales = new Locale[availableLocales.length + 1]; +// testLocales[0] = null; +// System.arraycopy(availableLocales, 0, testLocales, 1, availableLocales.length); +// for (int i = 0; i < testLocales.length; i++) { +// NumberFormat nf = null; +// NumberFormat cf = null; +// ExtendedMessageFormat emf = null; +// if (testLocales[i] == null) { +// nf = NumberFormat.getNumberInstance(); +// cf = NumberFormat.getCurrencyInstance(); +// emf = new ExtendedMessageFormat(pattern, registry); +// } else { +// nf = NumberFormat.getNumberInstance(testLocales[i]); +// cf = NumberFormat.getCurrencyInstance(testLocales[i]); +// emf = new ExtendedMessageFormat(pattern, testLocales[i], registry); +// } +// assertPatterns(null, pattern, emf.toPattern()); +// try { +// String lowExpected = lowArgs[0] + " low " + nf.format(lowArgs[2]); +// String highExpected = highArgs[0] + " HIGH " + cf.format(highArgs[2]); +// assertEquals(lowExpected, emf.format(lowArgs)); +// assertEquals(highExpected, emf.format(highArgs)); +// } catch (IllegalArgumentException e) { +// // currently sub-formats not supported +// } +// } +// } + + /** + * Test the built in choice format. + */ + @Test + public void testBuiltInChoiceFormat() { + final Object[] values = new Number[] {Integer.valueOf(1), Double.valueOf("2.2"), Double.valueOf("1234.5")}; + String choicePattern = null; + final Locale[] availableLocales = NumberFormat.getAvailableLocales(); + + choicePattern = "{0,choice,1#One|2#Two|3#Many {0,number}}"; + for (final Object value : values) { + checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); + } + + choicePattern = "{0,choice,1#''One''|2#\"Two\"|3#''{Many}'' {0,number}}"; + for (final Object value : values) { + checkBuiltInFormat(value + ": " + choicePattern, new Object[] {value}, availableLocales); + } + } + + /** + * Test the built in date/time formats + */ + @Test + public void testBuiltInDateTimeFormat() { + final Calendar cal = Calendar.getInstance(); + cal.set(2007, Calendar.JANUARY, 23, 18, 33, 05); + final Object[] args = new Object[] {cal.getTime()}; + final Locale[] availableLocales = DateFormat.getAvailableLocales(); + + checkBuiltInFormat("1: {0,date,short}", args, availableLocales); + checkBuiltInFormat("2: {0,date,medium}", args, availableLocales); + checkBuiltInFormat("3: {0,date,long}", args, availableLocales); + checkBuiltInFormat("4: {0,date,full}", args, availableLocales); + checkBuiltInFormat("5: {0,date,d MMM yy}", args, availableLocales); + checkBuiltInFormat("6: {0,time,short}", args, availableLocales); + checkBuiltInFormat("7: {0,time,medium}", args, availableLocales); + checkBuiltInFormat("8: {0,time,long}", args, availableLocales); + checkBuiltInFormat("9: {0,time,full}", args, availableLocales); + checkBuiltInFormat("10: {0,time,HH:mm}", args, availableLocales); + checkBuiltInFormat("11: {0,date}", args, availableLocales); + checkBuiltInFormat("12: {0,time}", args, availableLocales); + } + + @Test + public void testOverriddenBuiltinFormat() { + final Calendar cal = Calendar.getInstance(); + cal.set(2007, Calendar.JANUARY, 23); + final Object[] args = new Object[] {cal.getTime()}; + final Locale[] availableLocales = DateFormat.getAvailableLocales(); + final Map<String, ? extends FormatFactory> dateRegistry = Collections.singletonMap("date", new OverrideShortDateFormatFactory()); + + //check the non-overridden builtins: + checkBuiltInFormat("1: {0,date}", dateRegistry, args, availableLocales); + checkBuiltInFormat("2: {0,date,medium}", dateRegistry, args, availableLocales); + checkBuiltInFormat("3: {0,date,long}", dateRegistry, args, availableLocales); + checkBuiltInFormat("4: {0,date,full}", dateRegistry, args, availableLocales); + checkBuiltInFormat("5: {0,date,d MMM yy}", dateRegistry, args, availableLocales); + + //check the overridden format: + for (int i = -1; i < availableLocales.length; i++) { + final Locale locale = i < 0 ? null : availableLocales[i]; + final MessageFormat dateDefault = createMessageFormat("{0,date}", locale); + final String pattern = "{0,date,short}"; + final ExtendedMessageFormat dateShort = new ExtendedMessageFormat(pattern, locale, dateRegistry); + assertEquals("overridden date,short format", dateDefault.format(args), dateShort.format(args)); + assertEquals("overridden date,short pattern", pattern, dateShort.toPattern()); + } + } + + /** + * Test the built in number formats. + */ + @Test + public void testBuiltInNumberFormat() { + final Object[] args = new Object[] {Double.valueOf("6543.21")}; + final Locale[] availableLocales = NumberFormat.getAvailableLocales(); + checkBuiltInFormat("1: {0,number}", args, availableLocales); + checkBuiltInFormat("2: {0,number,integer}", args, availableLocales); + checkBuiltInFormat("3: {0,number,currency}", args, availableLocales); + checkBuiltInFormat("4: {0,number,percent}", args, availableLocales); + checkBuiltInFormat("5: {0,number,00000.000}", args, availableLocales); + } + + /** + * Test equals() and hashcode. + */ + @Test + public void testEqualsHashcode() { + final Map<String, ? extends FormatFactory> fmtRegistry = Collections.singletonMap("testfmt", new LowerCaseFormatFactory()); + final Map<String, ? extends FormatFactory> otherRegitry = Collections.singletonMap("testfmt", new UpperCaseFormatFactory()); + + final String pattern = "Pattern: {0,testfmt}"; + final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry); + + ExtendedMessageFormat other = null; + + // Same object + assertTrue("same, equals()", emf.equals(emf)); + assertTrue("same, hashcode()", emf.hashCode() == emf.hashCode()); + + assertFalse("null, equals", emf.equals(null)); + + // Equal Object + other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry); + assertTrue("equal, equals()", emf.equals(other)); + assertTrue("equal, hashcode()", emf.hashCode() == other.hashCode()); + + // Different Class + other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry); + assertFalse("class, equals()", emf.equals(other)); + assertTrue("class, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode + + // Different pattern + other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry); + assertFalse("pattern, equals()", emf.equals(other)); + assertFalse("pattern, hashcode()", emf.hashCode() == other.hashCode()); + + // Different registry + other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry); + assertFalse("registry, equals()", emf.equals(other)); + assertFalse("registry, hashcode()", emf.hashCode() == other.hashCode()); + + // Different Locale + other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry); + assertFalse("locale, equals()", emf.equals(other)); + assertTrue("locale, hashcode()", emf.hashCode() == other.hashCode()); // same hashcode + } + + /** + * Test a built in format for the specified Locales, plus <code>null</code> Locale. + * @param pattern MessageFormat pattern + * @param args MessageFormat arguments + * @param locales to test + */ + private void checkBuiltInFormat(final String pattern, final Object[] args, final Locale[] locales) { + checkBuiltInFormat(pattern, null, args, locales); + } + + /** + * Test a built in format for the specified Locales, plus <code>null</code> Locale. + * @param pattern MessageFormat pattern + * @param fmtRegistry FormatFactory registry to use + * @param args MessageFormat arguments + * @param locales to test + */ + private void checkBuiltInFormat(final String pattern, final Map<String, ?> fmtRegistry, final Object[] args, final Locale[] locales) { + checkBuiltInFormat(pattern, fmtRegistry, args, (Locale) null); + for (final Locale locale : locales) { + checkBuiltInFormat(pattern, fmtRegistry, args, locale); + } + } + + /** + * Create an ExtendedMessageFormat for the specified pattern and locale and check the + * formated output matches the expected result for the parameters. + * @param pattern string + * @param registryUnused map (currently unused) + * @param args Object[] + * @param locale Locale + */ + private void checkBuiltInFormat(final String pattern, final Map<String, ?> registryUnused, final Object[] args, final Locale locale) { + final StringBuilder buffer = new StringBuilder(); + buffer.append("Pattern=["); + buffer.append(pattern); + buffer.append("], locale=["); + buffer.append(locale); + buffer.append("]"); + final MessageFormat mf = createMessageFormat(pattern, locale); + // System.out.println(buffer + ", result=[" + mf.format(args) +"]"); + ExtendedMessageFormat emf = null; + if (locale == null) { + emf = new ExtendedMessageFormat(pattern); + } else { + emf = new ExtendedMessageFormat(pattern, locale); + } + assertEquals("format " + buffer.toString(), mf.format(args), emf.format(args)); + assertEquals("toPattern " + buffer.toString(), mf.toPattern(), emf.toPattern()); + } + + /** + * Replace MessageFormat(String, Locale) constructor (not available until JDK 1.4). + * @param pattern string + * @param locale Locale + * @return MessageFormat + */ + private MessageFormat createMessageFormat(final String pattern, final Locale locale) { + final MessageFormat result = new MessageFormat(pattern); + if (locale != null) { + result.setLocale(locale); + result.applyPattern(pattern); + } + return result; + } + + @Test(expected = UnsupportedOperationException.class) + public void testSetFormatIsUnsupported() { + final ExtendedMessageFormat emf = new ExtendedMessageFormat(""); + emf.setFormat(0, new LowerCaseFormat()); + } + + @Test(expected = UnsupportedOperationException.class) + public void testSetFormatByArgumentIndexIsUnsupported() { + final ExtendedMessageFormat emf = new ExtendedMessageFormat(""); + emf.setFormatByArgumentIndex(0, new LowerCaseFormat()); + } + + @Test(expected = UnsupportedOperationException.class) + public void testSetFormatsIsUnsupported() { + final ExtendedMessageFormat emf = new ExtendedMessageFormat(""); + emf.setFormats(new Format[]{new LowerCaseFormat(), new UpperCaseFormat()}); + } + + @Test(expected = UnsupportedOperationException.class) + public void testSetFormatsByArgumentIndex() { + final ExtendedMessageFormat emf = new ExtendedMessageFormat(""); + emf.setFormatsByArgumentIndex(new Format[]{new LowerCaseFormat(), new UpperCaseFormat()}); + } + + // ------------------------ Test Formats ------------------------ + + /** + * {@link Format} implementation which converts to lower case. + */ + private static class LowerCaseFormat extends Format { + private static final long serialVersionUID = 1L; + + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return toAppendTo.append(((String)obj).toLowerCase()); + } + @Override + public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} + } + + /** + * {@link Format} implementation which converts to upper case. + */ + private static class UpperCaseFormat extends Format { + private static final long serialVersionUID = 1L; + + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + return toAppendTo.append(((String)obj).toUpperCase()); + } + @Override + public Object parseObject(final String source, final ParsePosition pos) {throw new UnsupportedOperationException();} + } + + + // ------------------------ Test Format Factories --------------- + /** + * {@link FormatFactory} implementation for lower case format. + */ + private static class LowerCaseFormatFactory implements FormatFactory { + private static final Format LOWER_INSTANCE = new LowerCaseFormat(); + @Override + public Format getFormat(final String name, final String arguments, final Locale locale) { + return LOWER_INSTANCE; + } + } + /** + * {@link FormatFactory} implementation for upper case format. + */ + private static class UpperCaseFormatFactory implements FormatFactory { + private static final Format UPPER_INSTANCE = new UpperCaseFormat(); + @Override + public Format getFormat(final String name, final String arguments, final Locale locale) { + return UPPER_INSTANCE; + } + } + /** + * {@link FormatFactory} implementation to override date format "short" to "default". + */ + private static class OverrideShortDateFormatFactory implements FormatFactory { + @Override + public Format getFormat(final String name, final String arguments, final Locale locale) { + return !"short".equals(arguments) ? null + : locale == null ? DateFormat + .getDateInstance(DateFormat.DEFAULT) : DateFormat + .getDateInstance(DateFormat.DEFAULT, locale); + } + } + + /** + * Alternative ExtendedMessageFormat impl. + */ + private static class OtherExtendedMessageFormat extends ExtendedMessageFormat { + private static final long serialVersionUID = 1L; + + public OtherExtendedMessageFormat(final String pattern, final Locale locale, + final Map<String, ? extends FormatFactory> registry) { + super(pattern, locale, registry); + } + + } + +} http://git-wip-us.apache.org/repos/asf/commons-text/blob/165c8e60/src/test/java/org/apache/commons/text/beta/FormattableUtilsTest.java ---------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/text/beta/FormattableUtilsTest.java b/src/test/java/org/apache/commons/text/beta/FormattableUtilsTest.java new file mode 100644 index 0000000..6192373 --- /dev/null +++ b/src/test/java/org/apache/commons/text/beta/FormattableUtilsTest.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.text.beta; + +import static java.util.FormattableFlags.LEFT_JUSTIFY; +import static org.junit.Assert.assertEquals; + +import java.util.Formattable; +import java.util.Formatter; + +import org.junit.Test; + +/** + * Unit tests {@link FormattableUtils}. + */ +public class FormattableUtilsTest { + + @Test + public void testPublicConstructorExists() { + new FormattableUtils(); + } + + @Test + public void testSimplestFormat() { + final Formattable formattable = new SimplestFormattable("foo"); + + assertEquals("foo", FormattableUtils.toString(formattable)); + } + + @Test + public void testDefaultAppend() { + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1).toString()); + assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2).toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1).toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1).toString()); + assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 3, 2).toString()); + assertEquals(" fo", FormattableUtils.append("foo", new Formatter(), 0, 5, 2).toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1).toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1).toString()); + assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2).toString()); + assertEquals("fo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2).toString()); + } + + @Test + public void testAlternatePadCharacter() { + final char pad='_'; + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString()); + assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString()); + assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString()); + assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, pad).toString()); + assertEquals("_fo", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, pad).toString()); + assertEquals("___fo", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, pad).toString()); + assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, pad).toString()); + assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, pad).toString()); + assertEquals("fo_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, pad).toString()); + assertEquals("fo___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, pad).toString()); + } + + @Test + public void testEllipsis() { + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "*").toString()); + assertEquals("f*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "*").toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "*").toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "*").toString()); + assertEquals(" f*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "*").toString()); + assertEquals(" f*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "*").toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, "*").toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, "*").toString()); + assertEquals("f* ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, "*").toString()); + assertEquals("f* ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, "*").toString()); + + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "+*").toString()); + assertEquals("+*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "+*").toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "+*").toString()); + assertEquals(" foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "+*").toString()); + assertEquals(" +*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "+*").toString()); + assertEquals(" +*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "+*").toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, "+*").toString()); + assertEquals("foo ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, "+*").toString()); + assertEquals("+* ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, "+*").toString()); + assertEquals("+* ", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, "+*").toString()); + } + + @Test(expected=IllegalArgumentException.class) + public void testIllegalEllipsis() { + FormattableUtils.append("foo", new Formatter(), 0, -1, 1, "xx"); + } + + @Test + public void testAlternatePadCharAndEllipsis() { + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "*").toString()); + assertEquals("f*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "*").toString()); + assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "*").toString()); + assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "*").toString()); + assertEquals("_f*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "*").toString()); + assertEquals("___f*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "*").toString()); + assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, '_', "*").toString()); + assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, '_', "*").toString()); + assertEquals("f*_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, '_', "*").toString()); + assertEquals("f*___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, '_', "*").toString()); + + assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "+*").toString()); + assertEquals("+*", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "+*").toString()); + assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "+*").toString()); + assertEquals("___foo", FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "+*").toString()); + assertEquals("_+*", FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "+*").toString()); + assertEquals("___+*", FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "+*").toString()); + assertEquals("foo_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, '_', "+*").toString()); + assertEquals("foo___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, '_', "+*").toString()); + assertEquals("+*_", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, '_', "+*").toString()); + assertEquals("+*___", FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, '_', "+*").toString()); + } + + static class SimplestFormattable implements Formattable { + private final String text; + + SimplestFormattable(final String text) { + this.text = text; + } + + @Override + public void formatTo(Formatter formatter, int flags, int width, int precision) { + formatter.format(text); + } + }; + + +}