The initial implementation of the Myers algorithm was adapted from the
- * commons-collections sequence package.
- *
- * @since 1.0
- */
-package org.apache.commons.text.diff;
diff --git a/src/main/java/org/apache/commons/text/lookup/package-info.java b/src/main/java/org/apache/commons/text/lookup/package-info.java
deleted file mode 100644
index 984aeb4714..0000000000
--- a/src/main/java/org/apache/commons/text/lookup/package-info.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-/**
- *
- * Provides algorithms for looking up strings for use with a {@link org.apache.commons.text.StringSubstitutor}. The main
- * class here is {@link org.apache.commons.text.lookup.StringLookupFactory}.
- *
- *
- *
- * The initial implementation was adapted from Apache Commons Log4j 2.10.1-SNAPSHOT.
- *
- *
- * @since 1.3
- */
-package org.apache.commons.text.lookup;
diff --git a/src/main/java/org/apache/commons/text/matcher/package-info.java b/src/main/java/org/apache/commons/text/matcher/package-info.java
deleted file mode 100644
index a7a3aae65e..0000000000
--- a/src/main/java/org/apache/commons/text/matcher/package-info.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-/**
- *
- * Provides algorithms for matching up strings for use with a {@link org.apache.commons.text.StringSubstitutor}. The
- * main class here is {@link org.apache.commons.text.matcher.StringMatcherFactory}
- *
- *
- * @since 1.3
- */
-package org.apache.commons.text.matcher;
diff --git a/src/main/java/org/apache/commons/text/package-info.java b/src/main/java/org/apache/commons/text/package-info.java
deleted file mode 100644
index f36b6dc0d1..0000000000
--- a/src/main/java/org/apache/commons/text/package-info.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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.
- */
-/**
- *
Basic classes for text handling.
- *
- * @since 1.0
- */
-package org.apache.commons.text;
diff --git a/src/main/java/org/apache/commons/text/similarity/package-info.java b/src/main/java/org/apache/commons/text/similarity/package-info.java
deleted file mode 100644
index 703e427cc7..0000000000
--- a/src/main/java/org/apache/commons/text/similarity/package-info.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-/**
- *
Provides algorithms for string similarity.
- *
- *
The algorithms that implement the EditDistance interface follow the same
- * simple principle: the more similar (closer) strings are, lower is the distance.
- * For example, the words house and hose are closer than house and trousers.
- *
- *
The following algorithms are available at the moment:
The {@link org.apache.commons.text.similarity.CosineDistance Cosine Distance}
- * utilises a {@link org.apache.commons.text.similarity.RegexTokenizer regular expression tokenizer (\w+)}.
- * And the {@link org.apache.commons.text.similarity.LevenshteinDistance Levenshtein Distance}'s
- * behaviour can be changed to take into consideration a maximum throughput.
- *
- * @since 1.0
- */
-package org.apache.commons.text.similarity;
diff --git a/src/main/java/org/apache/commons/text/translate/package-info.java b/src/main/java/org/apache/commons/text/translate/package-info.java
deleted file mode 100644
index 5ccb000468..0000000000
--- a/src/main/java/org/apache/commons/text/translate/package-info.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-/**
- *
An API for creating text translation routines from a set of smaller building blocks. Initially created to make it
- * possible for the user to customize the rules in the StringEscapeUtils class.
- *
These classes are immutable, and therefore thread-safe.
- *
- * @since 1.0
- */
-package org.apache.commons.text.translate;
diff --git a/src/test/java/org/apache/commons/text/AlphabetConverterTest.java b/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
deleted file mode 100644
index 1ce32a7d01..0000000000
--- a/src/test/java/org/apache/commons/text/AlphabetConverterTest.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * 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;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.jupiter.api.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-
-/**
- * Unit tests for {@link AlphabetConverter}.
- */
-public class AlphabetConverterTest {
-
- private static Character[] lowerCaseEnglish = {' ', '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[] englishAndNumbers = {'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[] lowerCaseEnglishAndNumbers = {'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[] lowerCaseEnglishCodepoints = {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[] doNotEncodeCodepoints = {32, 97, 98, 99}; // space, a, b, c
-
- @Test
- public void encodeFailureTest() {
- assertThatThrownBy(() -> {
- test(binary, numbers, empty, "3");
- }).isInstanceOf(UnsupportedEncodingException.class).hasMessage("Couldn't find encoding for '3' in 3");
- }
-
- @Test
- public void binaryTest() throws UnsupportedEncodingException {
- test(binary, numbers, empty, "0", "1", "10", "11");
- test(numbers, binary, empty, "12345", "0");
- test(lowerCaseEnglish, 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(lowerCaseEnglish, hebrew, empty, "this is a test");
- }
-
- @Test
- public void doNotEncodeTest() throws UnsupportedEncodingException {
- test(englishAndNumbers, lowerCaseEnglishAndNumbers, lowerCaseEnglish, "1", "456", "abc", "ABC",
- "this will not be converted but THIS WILL");
- test(englishAndNumbers, lowerCaseEnglishAndNumbers, 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();
-
- assertThat(ac.encode("a")).isEqualTo("00");
- assertThat(ac.encode("b")).isEqualTo("01");
- assertThat(ac.encode("c")).isEqualTo("0d");
- assertThat(ac.encode("d")).isEqualTo("d");
- assertThat(ac.encode("abcd")).isEqualTo("00010dd");
- }
-
- @Test
- public void unexpectedEndwhileDecodingTest() throws UnsupportedEncodingException {
- final String toDecode = "00d01d0";
- assertThatThrownBy(() -> {
- final AlphabetConverter ac = createJavadocExample();
- ac.decode(toDecode);
- }).isInstanceOf(UnsupportedEncodingException.class).hasMessage(
- "Unexpected end of string while decoding " + toDecode);
- }
-
- @Test
- public void unexpectedStringWhileDecodingTest() throws UnsupportedEncodingException {
- final String toDecode = "00XX";
- assertThatThrownBy(() -> {
- final AlphabetConverter ac = createJavadocExample();
- ac.decode(toDecode);
- }).isInstanceOf(UnsupportedEncodingException.class).hasMessage(
- "Unexpected string without decoding (XX) in " + toDecode);
- }
-
- /*
- * Test constructor from code points
- */
- @Test
- public void unicodeTest() throws UnsupportedEncodingException {
- final AlphabetConverter ac = AlphabetConverter.createConverter(unicode, lowerCaseEnglishCodepoints,
- doNotEncodeCodepoints);
-
- assertThat(ac.getEncodedCharLength()).isEqualTo(2);
-
- final String original = "\u8a43\u8a45 \u8dce ab \u8dc3 c \u8983";
- final String encoded = ac.encode(original);
- final String decoded = ac.decode(encoded);
-
- assertThat(decoded).as("Encoded '" + original + "' into '" + encoded + "', but decoded into '" + decoded + "'")
- .isEqualTo(original);
- }
-
- @Test
- public void noEncodingLettersTest() {
- assertThatThrownBy(() -> {
- AlphabetConverter.createConverterFromChars(englishAndNumbers, numbers, numbers);
- }).isInstanceOf(IllegalArgumentException.class).hasMessage(
- "Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 0");
- }
-
- @Test
- public void onlyOneEncodingLettersTest() {
- assertThatThrownBy(() -> {
- final Character[] numbersPlusUnderscore = Arrays.copyOf(numbers, numbers.length + 1);
- numbersPlusUnderscore[numbersPlusUnderscore.length - 1] = '_';
-
- AlphabetConverter.createConverterFromChars(englishAndNumbers, numbersPlusUnderscore, numbers);
- }).isInstanceOf(IllegalArgumentException.class).hasMessage(
- "Must have at least two encoding characters (excluding those in the 'do not encode' list), but has 1");
- }
-
- @Test
- public void missingDoNotEncodeLettersFromEncodingTest() {
- assertThatThrownBy(() -> {
- AlphabetConverter.createConverterFromChars(englishAndNumbers, lowerCaseEnglish, numbers);
- }).isInstanceOf(IllegalArgumentException.class).hasMessage(
- "Can not use 'do not encode' list because encoding alphabet does not contain '0'");
- }
-
- @Test
- public void missingDoNotEncodeLettersFromOriginalTest() {
- assertThatThrownBy(() -> {
- AlphabetConverter.createConverterFromChars(lowerCaseEnglish, englishAndNumbers, numbers);
- }).isInstanceOf(IllegalArgumentException.class).hasMessage(
- "Can not use 'do not encode' list because original alphabet does not contain '0'");
- }
-
- 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());
-
- assertThat(reconstructedAlphabetConverter).isEqualTo(ac);
- assertThat(reconstructedAlphabetConverter.hashCode()).isEqualTo(ac.hashCode());
- assertThat(reconstructedAlphabetConverter.toString()).isEqualTo(ac.toString());
- assertThat(ac.encode(null)).isNull(); // test null conversions
- assertThat(ac.encode("")).isEqualTo(""); // 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 originalEncodingChars = Arrays.asList(encodingChars);
- for (int i = 0; i < encoded.length(); i++) {
- assertThat(originalEncodingChars.contains(encoded.charAt(i))).isTrue();
- }
-
- final String decoded = ac.decode(encoded);
-
- // test that only the original alphabet is used after decoding
- final List originalCharsList = Arrays.asList(originalChars);
- for (int i = 0; i < decoded.length(); i++) {
- assertThat(originalCharsList.contains(decoded.charAt(i))).isTrue();
- }
-
- assertThat(decoded).as("Encoded '" + s + "' into '" + encoded + "', but decoded into '" + decoded + "'")
- .isEqualTo(s);
- }
- }
-
- @Test
- public void testCreateConverterFromCharsWithNullAndNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- final Character[] characterArray = new Character[2];
- characterArray[0] = '$';
- characterArray[1] = characterArray[0];
-
- AlphabetConverter.createConverterFromChars(characterArray, null, null);
- });
- }
-
- @Test
- public void testCreateConverterFromCharsOne() {
- final Character[] characterArray = new Character[2];
- characterArray[0] = '5';
- characterArray[1] = characterArray[0];
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromChars(characterArray,
- characterArray, characterArray);
-
- assertThat(alphabetConverter.getEncodedCharLength()).isEqualTo(1);
- }
-
- @Test
- public void testCreateConverterFromMapAndEquals() {
- final Map hashMap = new HashMap<>();
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromMap(hashMap);
- hashMap.put(0, "CtDs");
- final AlphabetConverter alphabetConverterTwo = AlphabetConverter.createConverterFromMap(hashMap);
-
- assertThat(alphabetConverter.equals(alphabetConverterTwo)).isFalse();
- assertThat(alphabetConverter.getEncodedCharLength()).isEqualTo(1);
- }
-
- @Test
- public void testEquals() {
- final Character[] characterArray = new Character[2];
- final Character character = 'R';
- characterArray[0] = character;
- characterArray[1] = character;
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromChars(characterArray,
- characterArray, characterArray);
- final Map map = new HashMap<>();
- final AlphabetConverter alphabetConverterTwo = AlphabetConverter.createConverterFromMap(map);
-
- assertThat(alphabetConverterTwo.getEncodedCharLength()).isEqualTo(1);
- assertThat(alphabetConverter.equals(alphabetConverterTwo)).isFalse();
- }
-
- @Test
- public void testEqualsWithSameObject() {
- final Character[] characterArray = new Character[2];
- final Character character = 'R';
- characterArray[0] = character;
- characterArray[1] = character;
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromChars(characterArray,
- characterArray, characterArray);
-
- assertThat(alphabetConverter.equals(alphabetConverter)).isTrue();
- }
-
- @Test
- public void testEqualsWithNull() {
- final Character[] characterArray = new Character[0];
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromChars(characterArray, null,
- null);
-
- assertThat(alphabetConverter.equals(null)).isFalse();
- }
-
- @Test
- public void testCreateConverterFromCharsAndEquals() {
- final Character[] characterArray = new Character[2];
- final char charOne = '+';
- final Character character = '+';
- characterArray[0] = character;
- characterArray[1] = characterArray[0];
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromChars(characterArray,
- characterArray, characterArray);
-
- assertThat(alphabetConverter.equals(charOne)).isFalse();
- }
-
- @Test
- public void testDecodeReturningNull() throws UnsupportedEncodingException {
- final Map map = new HashMap<>();
- final AlphabetConverter alphabetConverter = AlphabetConverter.createConverterFromMap(map);
- alphabetConverter.decode(null);
-
- assertThat(alphabetConverter.getEncodedCharLength()).isEqualTo(1);
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/CaseUtilsTest.java b/src/test/java/org/apache/commons/text/CaseUtilsTest.java
deleted file mode 100644
index c3f4353025..0000000000
--- a/src/test/java/org/apache/commons/text/CaseUtilsTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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;
-
-import org.junit.jupiter.api.Test;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Modifier;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * Unit tests for {@link CaseUtils} class.
- */
-public class CaseUtilsTest {
-
- //-----------------------------------------------------------------------
- @Test
- public void testConstructor() {
- assertThat(new CaseUtils()).isNotNull();
- final Constructor>[] cons = CaseUtils.class.getDeclaredConstructors();
- assertThat(cons.length).isEqualTo(1);
- assertThat(Modifier.isPublic(cons[0].getModifiers())).isTrue();
- assertThat(Modifier.isPublic(CaseUtils.class.getModifiers())).isTrue();
- assertThat(Modifier.isFinal(CaseUtils.class.getModifiers())).isFalse();
- }
-
- //------------------------------------------------------------------------
- @Test
- public void testToCamelCase() {
- assertThat(CaseUtils.toCamelCase(null, false, null)).isNull();
- assertThat(CaseUtils.toCamelCase("", true, null)).isEqualTo("");
- assertThat(CaseUtils.toCamelCase(" ", false, null)).isEqualTo(" ");
- assertThat(CaseUtils.toCamelCase("a b c @def", false, null)).isEqualTo("aBC@def");
- assertThat(CaseUtils.toCamelCase("a b c @def", true, new char[]{})).isEqualTo("ABC@def");
- assertThat(CaseUtils.toCamelCase("a b c @def", true, new char[]{'-'})).isEqualTo("ABC@def");
- assertThat(CaseUtils.toCamelCase("a b c @def", true, new char[]{'-'})).isEqualTo("ABC@def");
-
- final char[] chars = {'-', '+', ' ', '@'};
- assertThat(CaseUtils.toCamelCase("-+@ ", true, chars)).isEqualTo("-+@ ");
- assertThat(CaseUtils.toCamelCase(" to-CAMEL-cASE", false, chars)).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase("@@@@ to+CAMEL@cASE ", true, chars)).isEqualTo("ToCamelCase");
- assertThat(CaseUtils.toCamelCase("To+CA+ME L@cASE", true, chars)).isEqualTo("ToCaMeLCase");
-
- assertThat(CaseUtils.toCamelCase("To.Camel.Case", false, new char[]{'.'})).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase("To.Camel-Case", false, new char[]{'-', '.'})).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase(" to @ Camel case", false, new char[]{'-', '@'})).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase(" @to @ Camel case", true, new char[]{'-', '@'})).isEqualTo("ToCamelCase");
-
- assertThat(CaseUtils.toCamelCase("TO CAMEL CASE", true, null)).isEqualTo("ToCamelCase");
- assertThat(CaseUtils.toCamelCase("TO CAMEL CASE", false, null)).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase("TO CAMEL CASE", false, null)).isEqualTo("toCamelCase");
- assertThat(CaseUtils.toCamelCase("tocamelcase", false, null)).isEqualTo("tocamelcase");
- assertThat(CaseUtils.toCamelCase("tocamelcase", true, null)).isEqualTo("Tocamelcase");
- assertThat(CaseUtils.toCamelCase("Tocamelcase", false, null)).isEqualTo("tocamelcase");
-
- assertThat(CaseUtils.toCamelCase("tocamelcase", true)).isEqualTo("Tocamelcase");
- assertThat(CaseUtils.toCamelCase("tocamelcase", false)).isEqualTo("tocamelcase");
-
- assertThat(CaseUtils.toCamelCase("\uD800\uDF00 \uD800\uDF02", true)).isEqualTo("\uD800\uDF00\uD800\uDF02");
- assertThat(CaseUtils.toCamelCase("\uD800\uDF00\uD800\uDF01\uD800\uDF14\uD800\uDF02\uD800\uDF03", true,
- new char[]{'\uD800', '\uDF14'}))
- .isEqualTo("\uD800\uDF00\uD800\uDF01\uD800\uDF02\uD800\uDF03");
- }
-}
diff --git a/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java b/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
deleted file mode 100644
index 53879e473a..0000000000
--- a/src/test/java/org/apache/commons/text/CharacterPredicatesTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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;
-
-import org.junit.jupiter.api.Test;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-/**
- * Tests for {@link CharacterPredicates}.
- */
-public class CharacterPredicatesTest {
-
- @Test
- public void testLetters() {
- assertThat(CharacterPredicates.LETTERS.test('a')).isTrue();
- assertThat(CharacterPredicates.LETTERS.test('Z')).isTrue();
-
- assertThat(CharacterPredicates.LETTERS.test('1')).isFalse();
- assertThat(CharacterPredicates.LETTERS.test('?')).isFalse();
- assertThat(CharacterPredicates.LETTERS.test('@')).isFalse();
- }
-
- @Test
- public void testDigits() {
- assertThat(CharacterPredicates.DIGITS.test('0')).isTrue();
- assertThat(CharacterPredicates.DIGITS.test('9')).isTrue();
-
- assertThat(CharacterPredicates.DIGITS.test('-')).isFalse();
- assertThat(CharacterPredicates.DIGITS.test('.')).isFalse();
- assertThat(CharacterPredicates.DIGITS.test('L')).isFalse();
- }
-
- @Test
- public void testArabicNumerals() {
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test('0')).isTrue();
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test('1')).isTrue();
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test('9')).isTrue();
-
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test('/')).isFalse();
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test(':')).isFalse();
- assertThat(CharacterPredicates.ARABIC_NUMERALS.test('a')).isFalse();
- }
-
- @Test
- public void testAsciiLowercaseLetters() {
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('a')).isTrue();
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('z')).isTrue();
-
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('9')).isFalse();
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('A')).isFalse();
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('Z')).isFalse();
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('`')).isFalse();
- assertThat(CharacterPredicates.ASCII_LOWERCASE_LETTERS.test('{')).isFalse();
- }
-
- @Test
- public void testAsciiUppercaseLetters() {
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('A')).isTrue();
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('Z')).isTrue();
-
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('9')).isFalse();
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('@')).isFalse();
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('[')).isFalse();
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('a')).isFalse();
- assertThat(CharacterPredicates.ASCII_UPPERCASE_LETTERS.test('z')).isFalse();
- }
-
- @Test
- public void testAsciiLetters() {
- assertThat(CharacterPredicates.ASCII_LETTERS.test('a')).isTrue();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('z')).isTrue();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('A')).isTrue();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('Z')).isTrue();
-
- assertThat(CharacterPredicates.ASCII_LETTERS.test('9')).isFalse();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('`')).isFalse();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('{')).isFalse();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('@')).isFalse();
- assertThat(CharacterPredicates.ASCII_LETTERS.test('[')).isFalse();
- }
-
- @Test
- public void testAsciiAlphaNumerals() {
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('a')).isTrue();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('z')).isTrue();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('A')).isTrue();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('Z')).isTrue();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('0')).isTrue();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('9')).isTrue();
-
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('`')).isFalse();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('{')).isFalse();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('@')).isFalse();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('[')).isFalse();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test('/')).isFalse();
- assertThat(CharacterPredicates.ASCII_ALPHA_NUMERALS.test(':')).isFalse();
- }
-}
diff --git a/src/test/java/org/apache/commons/text/CompositeFormatTest.java b/src/test/java/org/apache/commons/text/CompositeFormatTest.java
deleted file mode 100644
index 24b358605b..0000000000
--- a/src/test/java/org/apache/commons/text/CompositeFormatTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.text.FieldPosition;
-import java.text.Format;
-import java.text.ParsePosition;
-import java.text.SimpleDateFormat;
-import java.util.Locale;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * 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, composite.getParser(), "Parser get method incorrectly implemented");
- assertEquals(formatter, composite.getFormatter(), "Formatter get method incorrectly implemented");
- }
-
- @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"));
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java b/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
deleted file mode 100644
index 626ae93c97..0000000000
--- a/src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java
+++ /dev/null
@@ -1,579 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-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;
-
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test case for {@link ExtendedMessageFormat}.
- */
-public class ExtendedMessageFormatTest {
-
- private final Map registry = new HashMap<>();
-
- @BeforeEach
- public void setUp() {
- 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(pattern, emf.toPattern(), "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("Hi there, got 3, GREAT!", emf.format(new Object[] {"there", 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 Bug TEXT-106 - Exception while using ExtendedMessageFormat and choice format element with quote just
- * before brace end
- */
- @Test
- public void testChoiceQuoteJustBeforeBraceEnd_TEXT_106() {
- final String pattern2 = "Choice format element with quote just before brace end ''{0,choice,0#0|0<'1'}''";
- final ExtendedMessageFormat emf = new ExtendedMessageFormat(pattern2, registry);
- assertEquals("Choice format element with quote just before brace end '0'", emf.format(new Object[] {0}));
- assertEquals("Choice format element with quote just before brace end '1'", emf.format(new Object[] {1}));
- }
-
- /**
- * Test extended and built in formats.
- */
- @Test
- public void testExtendedAndBuiltInFormats() {
- final Calendar cal = Calendar.getInstance();
- cal.set(2007, Calendar.JANUARY, 23, 18, 33, 5);
- 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 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(Locale.ROOT));
- expected.append(" DOB: ");
- expected.append(df.format(args[1]));
- expected.append(" Salary: ");
- expected.append(nf.format(args[2]));
- assertEquals(expectedPattern, emf.toPattern(), "pattern comparison for locale " + locale);
- assertEquals(expected.toString(), emf.format(args), String.valueOf(locale));
- }
- }
-
-// /**
-// * 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[] {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, 5);
- 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 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(dateDefault.format(args), dateShort.format(args), "overridden date,short format");
- assertEquals(pattern, dateShort.toPattern(), "overridden date,short pattern");
- }
- }
-
- /**
- * 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 fmtRegistry =
- Collections.singletonMap("testfmt", new LowerCaseFormatFactory());
- final Map 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(emf.equals(emf), "same, equals()");
- assertEquals(emf.hashCode(), emf.hashCode(), "same, hashcode()");
-
- assertFalse(emf.equals(null), "null, equals");
-
- // Equal Object
- other = new ExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
- assertTrue(emf.equals(other), "equal, equals()");
- assertTrue(emf.hashCode() == other.hashCode(), "equal, hashcode()");
-
- // Different Class
- other = new OtherExtendedMessageFormat(pattern, Locale.US, fmtRegistry);
- assertFalse(emf.equals(other), "class, equals()");
- assertTrue(emf.hashCode() == other.hashCode(), "class, hashcode()"); // same hashcode
-
- // Different pattern
- other = new ExtendedMessageFormat("X" + pattern, Locale.US, fmtRegistry);
- assertFalse(emf.equals(other), "pattern, equals()");
- assertFalse(emf.hashCode() == other.hashCode(), "pattern, hashcode()");
-
- // Different registry
- other = new ExtendedMessageFormat(pattern, Locale.US, otherRegitry);
- assertFalse(emf.equals(other), "registry, equals()");
- assertFalse(emf.hashCode() == other.hashCode(), "registry, hashcode()");
-
- // Different Locale
- other = new ExtendedMessageFormat(pattern, Locale.FRANCE, fmtRegistry);
- assertFalse(emf.equals(other), "locale, equals()");
- assertTrue(emf.hashCode() == other.hashCode(), "locale, hashcode()"); // same hashcode
- }
-
- /**
- * Test a built in format for the specified Locales, plus null 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 null 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 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 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(mf.format(args), emf.format(args), "format " + buffer.toString());
- assertEquals(mf.toPattern(), emf.toPattern(), "toPattern " + buffer.toString());
- }
-
- /**
- * 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
- public void testSetFormatIsUnsupported() {
- assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormat(0, new LowerCaseFormat());
- });
- }
-
- @Test
- public void testSetFormatByArgumentIndexIsUnsupported() {
- assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormatByArgumentIndex(0, new LowerCaseFormat());
- });
- }
-
- @Test
- public void testSetFormatsIsUnsupported() {
- assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormats(new Format[] {new LowerCaseFormat(), new UpperCaseFormat()});
- });
- }
-
- @Test
- public void testSetFormatsByArgumentIndex() {
- assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> {
- final ExtendedMessageFormat emf = new ExtendedMessageFormat("");
- emf.setFormatsByArgumentIndex(new Format[] {new LowerCaseFormat(), new UpperCaseFormat()});
- });
- }
-
- @Test
- public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionOne() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new ExtendedMessageFormat("agdXdkR;T1{9 ^,LzXf?", new HashMap());
- });
- }
-
- @Test
- public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionTwo() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new ExtendedMessageFormat("a5XdkR;T1{9 ,LzXf?", new HashMap());
- });
- }
-
- @Test
- public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionThree() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new ExtendedMessageFormat("9jLh_D9{ ", new HashMap());
- });
- }
-
- @Test
- public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionFour() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new ExtendedMessageFormat("RD,nXhM{}{", new HashMap());
- });
- }
-
- @Test
- public void testFailsToCreateExtendedMessageFormatTakingTwoArgumentsThrowsIllegalArgumentExceptionFive() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new ExtendedMessageFormat("j/[_D9{0,\"&'+0o", new HashMap());
- });
- }
-
- @Test
- public void testCreatesExtendedMessageFormatTakingString() {
- final ExtendedMessageFormat extendedMessageFormat =
- new ExtendedMessageFormat("Unterminated format element at position ");
- final Map map = new HashMap<>();
- final ExtendedMessageFormat extendedMessageFormatTwo =
- new ExtendedMessageFormat("Unterminated format element at position ", map);
-
- assertEquals("Unterminated format element at position ", extendedMessageFormatTwo.toPattern());
- assertFalse(extendedMessageFormat.equals(extendedMessageFormatTwo));
- }
-
- // ------------------------ 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(Locale.ROOT));
- }
-
- @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(Locale.ROOT));
- }
-
- @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;
-
- OtherExtendedMessageFormat(final String pattern, final Locale locale,
- final Map registry) {
- super(pattern, locale, registry);
- }
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/FormattableUtilsTest.java b/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
deleted file mode 100644
index 273cea1ca9..0000000000
--- a/src/test/java/org/apache/commons/text/FormattableUtilsTest.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * 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;
-
-import static java.util.FormattableFlags.LEFT_JUSTIFY;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.assertj.core.api.Assertions.assertThatNullPointerException;
-
-import java.util.Formattable;
-import java.util.Formatter;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests {@link FormattableUtils}.
- */
-public class FormattableUtilsTest {
-
- @Test
- public void testPublicConstructorExists() {
- new FormattableUtils();
- }
-
- @Test
- public void testSimplestFormat() {
- final Formattable formattable = new SimplestFormattable("foo");
-
- assertThat(FormattableUtils.toString(formattable)).isEqualTo("foo");
- }
-
- @Test
- public void testDefaultAppend() {
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1).toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2).toString()).isEqualTo("fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1).toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1).toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2).toString()).isEqualTo(" fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2).toString()).isEqualTo(" fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1).toString()).isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1).toString()).isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2).toString()).isEqualTo("fo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2).toString()).isEqualTo("fo ");
- }
-
- @Test
- public void testAlternatePadCharacter() {
- final char pad = '_';
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString()).isEqualTo("fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString()).isEqualTo("_foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1, pad).toString()).isEqualTo("___foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2, pad).toString()).isEqualTo("_fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2, pad).toString()).isEqualTo("___fo");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, pad).toString())
- .isEqualTo("foo_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, pad).toString())
- .isEqualTo("foo___");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, pad).toString())
- .isEqualTo("fo_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, pad).toString())
- .isEqualTo("fo___");
- }
-
- @Test
- public void testEllipsis() {
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "*").toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "*").toString()).isEqualTo("f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "*").toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "*").toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "*").toString()).isEqualTo(" f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "*").toString()).isEqualTo(" f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, "*").toString())
- .isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, "*").toString())
- .isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, "*").toString())
- .isEqualTo("f* ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, "*").toString())
- .isEqualTo("f* ");
-
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1, "+*").toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2, "+*").toString()).isEqualTo("+*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1, "+*").toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1, "+*").toString()).isEqualTo(" foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2, "+*").toString()).isEqualTo(" +*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2, "+*").toString()).isEqualTo(" +*");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, "+*").toString())
- .isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, "+*").toString())
- .isEqualTo("foo ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, "+*").toString())
- .isEqualTo("+* ");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, "+*").toString())
- .isEqualTo("+* ");
- }
-
- @Test
- public void testIllegalEllipsis() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- FormattableUtils.append("foo", new Formatter(), 0, -1, 1, "xx");
- });
- }
-
- @Test
- public void testAlternatePadCharAndEllipsis() {
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "*").toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "*").toString()).isEqualTo("f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "*").toString()).isEqualTo("_foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "*").toString()).isEqualTo("___foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "*").toString()).isEqualTo("_f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "*").toString()).isEqualTo("___f*");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, '_', "*").toString())
- .isEqualTo("foo_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, '_', "*").toString())
- .isEqualTo("foo___");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, '_', "*").toString())
- .isEqualTo("f*_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, '_', "*").toString())
- .isEqualTo("f*___");
-
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, -1, '_', "+*").toString()).isEqualTo("foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, -1, 2, '_', "+*").toString()).isEqualTo("+*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 4, -1, '_', "+*").toString()).isEqualTo("_foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 6, -1, '_', "+*").toString())
- .isEqualTo("___foo");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 3, 2, '_', "+*").toString()).isEqualTo("_+*");
- assertThat(FormattableUtils.append("foo", new Formatter(), 0, 5, 2, '_', "+*").toString()).isEqualTo("___+*");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 4, -1, '_', "+*").toString())
- .isEqualTo("foo_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 6, -1, '_', "+*").toString())
- .isEqualTo("foo___");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 3, 2, '_', "+*").toString())
- .isEqualTo("+*_");
- assertThat(FormattableUtils.append("foo", new Formatter(), LEFT_JUSTIFY, 5, 2, '_', "+*").toString())
- .isEqualTo("+*___");
- }
-
- @Test
- public void testAppendWithNullFormatterAndIntsThrowsNullPointerException() {
- assertThatNullPointerException().isThrownBy(() -> FormattableUtils.append("", null, 0, 0, 0, '}'));
- }
-
- static class SimplestFormattable implements Formattable {
- private final String text;
-
- SimplestFormattable(final String text) {
- this.text = text;
- }
-
- @Override
- public void formatTo(final Formatter formatter, final int flags, final int width, final int precision) {
- formatter.format(text);
- }
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java b/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
deleted file mode 100644
index bc343bedd6..0000000000
--- a/src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.assertj.core.api.Assertions.assertThatNullPointerException;
-import static org.assertj.core.api.Assertions.fail;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Tests for {@link RandomStringGenerator}
- */
-public class RandomStringGeneratorTest {
-
- private static final CharacterPredicate A_FILTER = new CharacterPredicate() {
- @Override
- public boolean test(final int codePoint) {
- return codePoint == 'a';
- }
- };
-
- private static final CharacterPredicate B_FILTER = new CharacterPredicate() {
- @Override
- public boolean test(final int codePoint) {
- return codePoint == 'b';
- }
- };
-
- @Test
- public void testInvalidLength() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(-1);
- });
- }
-
- @Test
- public void testGenerateMinMaxLengthInvalidLength() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(-1, 0);
- });
- }
-
- @Test
- public void testGenerateMinMaxLengthMinGreaterThanMax() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- generator.generate(1, 0);
- });
- }
-
- private static int codePointLength(final String s) {
- return s.codePointCount(0, s.length());
- }
-
- @Test
- public void testSetLength() {
- final int length = 99;
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- final String str = generator.generate(length);
- assertThat(codePointLength(str)).isEqualTo(length);
- }
-
- @Test
- public void testGenerateMinMaxLength() {
- final int minLength = 0;
- final int maxLength = 3;
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- final String str = generator.generate(minLength, maxLength);
- assertThat(codePointLength(str)).isBetween(0, 3);
- }
-
- @Test
- public void testBadMinimumCodePoint() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new RandomStringGenerator.Builder().withinRange(-1, 1);
- });
- }
-
- @Test
- public void testBadMaximumCodePoint() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new RandomStringGenerator.Builder().withinRange(0, Character.MAX_CODE_POINT + 1);
- });
- }
-
- @Test
- public void testWithinRange() {
- final int length = 5000;
- final int minimumCodePoint = 'a';
- final int maximumCodePoint = 'z';
- final RandomStringGenerator generator = new RandomStringGenerator.Builder()
- .withinRange(minimumCodePoint, maximumCodePoint).build();
- final String str = generator.generate(length);
-
- int i = 0;
- do {
- final int codePoint = str.codePointAt(i);
- assertThat(codePoint >= minimumCodePoint && codePoint <= maximumCodePoint).isTrue();
- i += Character.charCount(codePoint);
- } while (i < str.length());
- }
-
- @Test
- public void testWithinMultipleRanges() {
- final int length = 5000;
- final char[][] pairs = {{'a', 'z'}, {'0', '9'}};
- final RandomStringGenerator generator = new RandomStringGenerator.Builder()
- .withinRange(pairs).build();
- final String str = generator.generate(length);
-
- int minimumCodePoint = 0, maximumCodePoint = 0;
-
- for (final char[] pair : pairs) {
- minimumCodePoint = Math.min(minimumCodePoint, pair[0]);
- maximumCodePoint = Math.max(maximumCodePoint, pair[1]);
- }
-
- int i = 0;
- do {
- final int codePoint = str.codePointAt(i);
- assertThat(codePoint >= minimumCodePoint && codePoint <= maximumCodePoint).isTrue();
- i += Character.charCount(codePoint);
- } while (i < str.length());
- }
-
- @Test
- public void testNoLoneSurrogates() {
- final int length = 5000;
- final String str = new RandomStringGenerator.Builder().build().generate(length);
-
- char lastChar = str.charAt(0);
- for (int i = 1; i < str.length(); i++) {
- final char c = str.charAt(i);
-
- if (Character.isLowSurrogate(c)) {
- assertThat(Character.isHighSurrogate(lastChar)).isTrue();
- }
-
- if (Character.isHighSurrogate(lastChar)) {
- assertThat(Character.isLowSurrogate(c)).isTrue();
- }
-
- if (Character.isHighSurrogate(c)) {
- // test this isn't the last character in the string
- assertThat(i + 1 < str.length()).isTrue();
- }
-
- lastChar = c;
- }
- }
-
- @Test
- public void testUsingRandom() {
- final char testChar = 'a';
- final TextRandomProvider testRandom = new TextRandomProvider() {
-
- @Override
- public int nextInt(final int n) {
- return testChar;
- }
- };
-
- final String str = new RandomStringGenerator.Builder().usingRandom(testRandom).build().generate(10);
- for (final char c : str.toCharArray()) {
- assertThat(c).isEqualTo(testChar);
- }
- }
-
- @Test
- public void testMultipleFilters() {
- final String str = new RandomStringGenerator.Builder().withinRange('a', 'd')
- .filteredBy(A_FILTER, B_FILTER).build().generate(5000);
-
- boolean aFound = false;
- boolean bFound = false;
-
- for (final char c : str.toCharArray()) {
- if (c == 'a') {
- aFound = true;
- } else if (c == 'b') {
- bFound = true;
- } else {
- fail("Invalid character");
- }
- }
-
- assertThat(aFound && bFound).isTrue();
- }
-
- @Test
- public void testNoPrivateCharacters() {
- final int startOfPrivateBMPChars = 0xE000;
-
- // Request a string in an area of the Basic Multilingual Plane that is
- // largely occupied by private characters
- final String str = new RandomStringGenerator.Builder().withinRange(startOfPrivateBMPChars,
- Character.MIN_SUPPLEMENTARY_CODE_POINT - 1).build().generate(5000);
-
- int i = 0;
- do {
- final int codePoint = str.codePointAt(i);
- assertThat(Character.getType(codePoint) == Character.PRIVATE_USE).isFalse();
- i += Character.charCount(codePoint);
- } while (i < str.length());
- }
-
- @Test
- public void testBadMinAndMax() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- new RandomStringGenerator.Builder().withinRange(2, 1);
- });
- }
-
- @Test
- public void testRemoveFilters() {
- final RandomStringGenerator.Builder builder = new RandomStringGenerator.Builder().withinRange('a', 'z')
- .filteredBy(A_FILTER);
-
- builder.filteredBy();
-
- final String str = builder.build().generate(100);
- for (final char c : str.toCharArray()) {
- if (c != 'a') {
- // filter was successfully removed
- return;
- }
- }
-
- fail("Filter appears to have remained in place");
- }
-
- @Test
- public void testChangeOfFilter() {
- final RandomStringGenerator.Builder builder = new RandomStringGenerator.Builder().withinRange('a', 'z')
- .filteredBy(A_FILTER);
- final String str = builder.filteredBy(B_FILTER).build().generate(100);
-
- for (final char c : str.toCharArray()) {
- assertThat(c == 'b').isTrue();
- }
- }
-
- @Test
- public void testZeroLength() {
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().build();
- assertThat(generator.generate(0)).isEqualTo("");
- }
-
- @Test
- public void testSelectFromCharArray() {
- final String str = "abc";
- final char[] charArray = str.toCharArray();
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().selectFrom(charArray).build();
-
- final String randomText = generator.generate(5);
-
- for (final char c : randomText.toCharArray()) {
- assertThat(str.indexOf(c) != -1).isTrue();
- }
- }
-
- @Test
- public void testSelectFromCharVarargs() {
- final String str = "abc";
- final RandomStringGenerator generator = new RandomStringGenerator.Builder().selectFrom('a', 'b', 'c').build();
- final String randomText = generator.generate(5);
- for (final char c : randomText.toCharArray()) {
- assertThat(str.indexOf(c) != -1).isTrue();
- }
- }
-
- @Test
- public void testGenerateTakingIntThrowsNullPointerException() {
- assertThatNullPointerException().isThrownBy(() -> {
- final RandomStringGenerator.Builder randomStringGeneratorBuilder = new RandomStringGenerator.Builder();
- final CharacterPredicate[] characterPredicateArray = new CharacterPredicate[2];
- randomStringGeneratorBuilder.filteredBy(characterPredicateArray);
- final RandomStringGenerator randomStringGenerator = randomStringGeneratorBuilder.build();
-
- randomStringGenerator.generate(18);
- });
- }
-}
diff --git a/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java b/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
deleted file mode 100644
index 78b03d91c2..0000000000
--- a/src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java
+++ /dev/null
@@ -1,1477 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.fail;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import java.text.DecimalFormatSymbols;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for {@link StrBuilder}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrBuilderAppendInsertTest {
-
- /** The system line separator. */
- private static final String SEP = System.lineSeparator();
-
- /** Test subclass of Object, with a toString method. */
- private static final Object FOO = new Object() {
- @Override
- public String toString() {
- return "foo";
- }
- };
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendNewLine() {
- StrBuilder sb = new StrBuilder("---");
- sb.appendNewLine().append("+++");
- assertThat(sb.toString()).isEqualTo("---" + SEP + "+++");
-
- sb = new StrBuilder("---");
- sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine();
- assertThat(sb.toString()).isEqualTo("---#" + SEP);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendWithNullText() {
- final StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.appendNull();
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb.append((Object) null);
- assertThat(sb.toString()).isEqualTo("NULLNULL");
-
- sb.append(FOO);
- assertThat(sb.toString()).isEqualTo("NULLNULLfoo");
-
- sb.append((String) null);
- assertThat(sb.toString()).isEqualTo("NULLNULLfooNULL");
-
- sb.append("");
- assertThat(sb.toString()).isEqualTo("NULLNULLfooNULL");
-
- sb.append("bar");
- assertThat(sb.toString()).isEqualTo("NULLNULLfooNULLbar");
-
- sb.append((StringBuffer) null);
- assertThat(sb.toString()).isEqualTo("NULLNULLfooNULLbarNULL");
-
- sb.append(new StringBuffer("baz"));
- assertThat(sb.toString()).isEqualTo("NULLNULLfooNULLbarNULLbaz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_Object() {
- final StrBuilder sb = new StrBuilder();
- sb.appendNull();
- assertThat(sb.toString()).isEqualTo("");
-
- sb.append((Object) null);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.append(FOO);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append((StringBuffer) null);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuffer("baz"));
- assertThat(sb.toString()).isEqualTo("foobaz");
-
- sb.append(new StrBuilder("yes"));
- assertThat(sb.toString()).isEqualTo("foobazyes");
-
- sb.append((CharSequence) "Seq");
- assertThat(sb.toString()).isEqualTo("foobazyesSeq");
-
- sb.append(new StringBuilder("bld")); // Check it supports StringBuilder
- assertThat(sb.toString()).isEqualTo("foobazyesSeqbld");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StringBuilder() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((String) null);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StringBuilder("foo"));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuilder(""));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuilder("bar"));
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_String() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((String) null);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append("");
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append("bar");
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_String_int_int() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((String) null, 0, 1);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append("foo", 0, 3);
- assertThat(sb.toString()).isEqualTo("foo");
-
- try {
- sb.append("bar", -1, 1);
- fail("append(char[], -1,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append("bar", 3, 1);
- fail("append(char[], 3,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append("bar", 1, -1);
- fail("append(char[],, -1) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append("bar", 1, 3);
- fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append("bar", -1, 3);
- fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append("bar", 4, 0);
- fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- sb.append("bar", 3, 0);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append("abcbardef", 3, 3);
- assertThat(sb.toString()).isEqualTo("foobar");
-
- sb.append((CharSequence) "abcbardef", 4, 3);
- assertThat(sb.toString()).isEqualTo("foobarard");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StringBuilder_int_int() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((String) null, 0, 1);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StringBuilder("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo");
-
- try {
- sb.append(new StringBuilder("bar"), -1, 1);
- fail("append(StringBuilder, -1,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuilder("bar"), 3, 1);
- fail("append(StringBuilder, 3,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuilder("bar"), 1, -1);
- fail("append(StringBuilder,, -1) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuilder("bar"), 1, 3);
- fail("append(StringBuilder, 1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuilder("bar"), -1, 3);
- fail("append(StringBuilder, -1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuilder("bar"), 4, 0);
- fail("append(StringBuilder, 4, 0) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- sb.append(new StringBuilder("bar"), 3, 0);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuilder("abcbardef"), 3, 3);
- assertThat(sb.toString()).isEqualTo("foobar");
-
- sb.append(new StringBuilder("abcbardef"), 4, 3);
- assertThat(sb.toString()).isEqualTo("foobarard");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StringBuffer() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((StringBuffer) null);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StringBuffer("foo"));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuffer(""));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuffer("bar"));
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StringBuffer_int_int() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((StringBuffer) null, 0, 1);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StringBuffer("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo");
-
- try {
- sb.append(new StringBuffer("bar"), -1, 1);
- fail("append(char[], -1,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuffer("bar"), 3, 1);
- fail("append(char[], 3,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuffer("bar"), 1, -1);
- fail("append(char[],, -1) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuffer("bar"), 1, 3);
- fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuffer("bar"), -1, 3);
- fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StringBuffer("bar"), 4, 0);
- fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- sb.append(new StringBuffer("bar"), 3, 0);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StringBuffer("abcbardef"), 3, 3);
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StrBuilder() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((StrBuilder) null);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StrBuilder("foo"));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StrBuilder(""));
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StrBuilder("bar"));
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_StrBuilder_int_int() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((StrBuilder) null, 0, 1);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new StrBuilder("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo");
-
- try {
- sb.append(new StrBuilder("bar"), -1, 1);
- fail("append(char[], -1,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StrBuilder("bar"), 3, 1);
- fail("append(char[], 3,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StrBuilder("bar"), 1, -1);
- fail("append(char[],, -1) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StrBuilder("bar"), 1, 3);
- fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StrBuilder("bar"), -1, 3);
- fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new StrBuilder("bar"), 4, 0);
- fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- sb.append(new StrBuilder("bar"), 3, 0);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new StrBuilder("abcbardef"), 3, 3);
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_CharArray() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((char[]) null);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new char[0]);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.append(new char[]{'f', 'o', 'o'});
- assertThat(sb.toString()).isEqualTo("foo");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_CharArray_int_int() {
- StrBuilder sb = new StrBuilder();
- sb.setNullText("NULL").append((char[]) null, 0, 1);
- assertThat(sb.toString()).isEqualTo("NULL");
-
- sb = new StrBuilder();
- sb.append(new char[]{'f', 'o', 'o'}, 0, 3);
- assertThat(sb.toString()).isEqualTo("foo");
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, -1, 1);
- fail("append(char[], -1,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, 3, 1);
- fail("append(char[], 3,) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, 1, -1);
- fail("append(char[],, -1) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, 1, 3);
- fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, -1, 3);
- fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- try {
- sb.append(new char[]{'b', 'a', 'r'}, 4, 0);
- fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- // expected
- }
-
- sb.append(new char[]{'b', 'a', 'r'}, 3, 0);
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.append(new char[]{'a', 'b', 'c', 'b', 'a', 'r', 'd', 'e', 'f'}, 3, 3);
- assertThat(sb.toString()).isEqualTo("foobar");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_Boolean() {
- final StrBuilder sb = new StrBuilder();
- sb.append(true);
- assertThat(sb.toString()).isEqualTo("true");
-
- sb.append(false);
- assertThat(sb.toString()).isEqualTo("truefalse");
-
- sb.append('!');
- assertThat(sb.toString()).isEqualTo("truefalse!");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_PrimitiveNumber() {
- final StrBuilder sb = new StrBuilder();
- sb.append(0);
- assertThat(sb.toString()).isEqualTo("0");
-
- sb.append(1L);
- assertThat(sb.toString()).isEqualTo("01");
-
- sb.append(2.3f);
- assertThat(sb.toString()).isEqualTo("012.3");
-
- sb.append(4.5d);
- assertThat(sb.toString()).isEqualTo("012.34.5");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_FormattedString() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final String str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln("Hello %s", "Alice");
- assertThat(sb.toString()).isEqualTo("Hello Alice" + SEP);
- assertThat(count[0]).isEqualTo(2); // appendNewLine() calls append(String)
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_Object() {
- final StrBuilder sb = new StrBuilder();
- sb.appendln((Object) null);
- assertThat(sb.toString()).isEqualTo("" + SEP);
-
- sb.appendln(FOO);
- assertThat(sb.toString()).isEqualTo(SEP + "foo" + SEP);
-
- sb.appendln(Integer.valueOf(6));
- assertThat(sb.toString()).isEqualTo(SEP + "foo" + SEP + "6" + SEP);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_String() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final String str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln("foo");
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(2); // appendNewLine() calls append(String)
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_String_int_int() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final String str, final int startIndex, final int length) {
- count[0]++;
- return super.append(str, startIndex, length);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln("foo", 0, 3);
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StringBuffer() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StringBuffer str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StringBuffer("foo"));
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StringBuilder() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StringBuilder str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StringBuilder("foo"));
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StringBuffer_int_int() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StringBuffer str, final int startIndex, final int length) {
- count[0]++;
- return super.append(str, startIndex, length);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StringBuffer("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StringBuilder_int_int() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StringBuilder str, final int startIndex, final int length) {
- count[0]++;
- return super.append(str, startIndex, length);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StringBuilder("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StrBuilder() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StrBuilder str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StrBuilder("foo"));
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_StrBuilder_int_int() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final StrBuilder str, final int startIndex, final int length) {
- count[0]++;
- return super.append(str, startIndex, length);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln(new StrBuilder("foo"), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_CharArray() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final char[] str) {
- count[0]++;
- return super.append(str);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln("foo".toCharArray());
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_CharArray_int_int() {
- final int[] count = new int[2];
- final StrBuilder sb = new StrBuilder() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public StrBuilder append(final char[] str, final int startIndex, final int length) {
- count[0]++;
- return super.append(str, startIndex, length);
- }
- @Override
- public StrBuilder appendNewLine() {
- count[1]++;
- return super.appendNewLine();
- }
- };
- sb.appendln("foo".toCharArray(), 0, 3);
- assertThat(sb.toString()).isEqualTo("foo" + SEP);
- assertThat(count[0]).isEqualTo(1);
- assertThat(count[1]).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_Boolean() {
- final StrBuilder sb = new StrBuilder();
- sb.appendln(true);
- assertThat(sb.toString()).isEqualTo("true" + SEP);
-
- sb.clear();
- sb.appendln(false);
- assertThat(sb.toString()).isEqualTo("false" + SEP);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendln_PrimitiveNumber() {
- final StrBuilder sb = new StrBuilder();
- sb.appendln(0);
- assertThat(sb.toString()).isEqualTo("0" + SEP);
-
- sb.clear();
- sb.appendln(1L);
- assertThat(sb.toString()).isEqualTo("1" + SEP);
-
- sb.clear();
- sb.appendln(2.3f);
- assertThat(sb.toString()).isEqualTo("2.3" + SEP);
-
- sb.clear();
- sb.appendln(4.5d);
- assertThat(sb.toString()).isEqualTo("4.5" + SEP);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendPadding() {
- final StrBuilder sb = new StrBuilder();
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.appendPadding(-1, '-');
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.appendPadding(0, '-');
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.appendPadding(1, '-');
- assertThat(sb.toString()).isEqualTo("foo-");
-
- sb.appendPadding(16, '-');
- assertThat(sb.length()).isEqualTo(20);
- // 12345678901234567890
- assertThat(sb.toString()).isEqualTo("foo-----------------");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendFixedWidthPadLeft() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadLeft("foo", -1, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 0, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 1, '-');
- assertThat(sb.toString()).isEqualTo("o");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 2, '-');
- assertThat(sb.toString()).isEqualTo("oo");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 3, '-');
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 4, '-');
- assertThat(sb.toString()).isEqualTo("-foo");
-
- sb.clear();
- sb.appendFixedWidthPadLeft("foo", 10, '-');
- assertThat(sb.length()).isEqualTo(10);
- // 1234567890
- assertThat(sb.toString()).isEqualTo("-------foo");
-
- sb.clear();
- sb.setNullText("null");
- sb.appendFixedWidthPadLeft(null, 5, '-');
- assertThat(sb.toString()).isEqualTo("-null");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendFixedWidthPadLeft_int() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadLeft(123, -1, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 0, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 1, '-');
- assertThat(sb.toString()).isEqualTo("3");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 2, '-');
- assertThat(sb.toString()).isEqualTo("23");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 3, '-');
- assertThat(sb.toString()).isEqualTo("123");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 4, '-');
- assertThat(sb.toString()).isEqualTo("-123");
-
- sb.clear();
- sb.appendFixedWidthPadLeft(123, 10, '-');
- assertThat(sb.length()).isEqualTo(10);
- // 1234567890
- assertThat(sb.toString()).isEqualTo("-------123");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendFixedWidthPadRight() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadRight("foo", -1, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 0, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 1, '-');
- assertThat(sb.toString()).isEqualTo("f");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 2, '-');
- assertThat(sb.toString()).isEqualTo("fo");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 3, '-');
- assertThat(sb.toString()).isEqualTo("foo");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 4, '-');
- assertThat(sb.toString()).isEqualTo("foo-");
-
- sb.clear();
- sb.appendFixedWidthPadRight("foo", 10, '-');
- assertThat(sb.length()).isEqualTo(10);
- // 1234567890
- assertThat(sb.toString()).isEqualTo("foo-------");
-
- sb.clear();
- sb.setNullText("null");
- sb.appendFixedWidthPadRight(null, 5, '-');
- assertThat(sb.toString()).isEqualTo("null-");
- }
-
- // See: http://issues.apache.org/jira/browse/LANG-299
- @Test
- public void testLang299() {
- final StrBuilder sb = new StrBuilder(1);
- sb.appendFixedWidthPadRight("foo", 1, '-');
- assertThat(sb.toString()).isEqualTo("f");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendFixedWidthPadRight_int() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadRight(123, -1, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 0, '-');
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 1, '-');
- assertThat(sb.toString()).isEqualTo("1");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 2, '-');
- assertThat(sb.toString()).isEqualTo("12");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 3, '-');
- assertThat(sb.toString()).isEqualTo("123");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 4, '-');
- assertThat(sb.toString()).isEqualTo("123-");
-
- sb.clear();
- sb.appendFixedWidthPadRight(123, 10, '-');
- assertThat(sb.length()).isEqualTo(10);
- // 1234567890
- assertThat(sb.toString()).isEqualTo("123-------");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppend_FormattedString() {
- StrBuilder sb;
-
- sb = new StrBuilder();
- sb.append("Hi", (Object[]) null);
- assertThat(sb.toString()).isEqualTo("Hi");
-
- sb = new StrBuilder();
- sb.append("Hi", "Alice");
- assertThat(sb.toString()).isEqualTo("Hi");
-
- sb = new StrBuilder();
- sb.append("Hi %s", "Alice");
- assertThat(sb.toString()).isEqualTo("Hi Alice");
-
- sb = new StrBuilder();
- sb.append("Hi %s %,d", "Alice", 5000);
- // group separator depends on system locale
- final char groupingSeparator = DecimalFormatSymbols.getInstance().getGroupingSeparator();
- final String expected = "Hi Alice 5" + groupingSeparator + "000";
- assertThat(sb.toString()).isEqualTo(expected);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendAll_Array() {
- final StrBuilder sb = new StrBuilder();
- sb.appendAll((Object[]) null);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(new Object[0]);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(new Object[]{"foo", "bar", "baz"});
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.appendAll("foo", "bar", "baz");
- assertThat(sb.toString()).isEqualTo("foobarbaz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendAll_Collection() {
- final StrBuilder sb = new StrBuilder();
- sb.appendAll((Collection>) null);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(Collections.EMPTY_LIST);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(Arrays.asList(new Object[]{"foo", "bar", "baz"}));
- assertThat(sb.toString()).isEqualTo("foobarbaz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendAll_Iterator() {
- final StrBuilder sb = new StrBuilder();
- sb.appendAll((Iterator>) null);
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(Collections.EMPTY_LIST.iterator());
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendAll(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator());
- assertThat(sb.toString()).isEqualTo("foobarbaz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendWithSeparators_Array() {
- final StrBuilder sb = new StrBuilder();
- sb.appendWithSeparators((Object[]) null, ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(new Object[0], ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, ",");
- assertThat(sb.toString()).isEqualTo("foo,bar,baz");
-
- sb.clear();
- sb.appendWithSeparators(new Object[]{"foo", "bar", "baz"}, null);
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
- assertThat(sb.toString()).isEqualTo("foo,,baz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendWithSeparators_Collection() {
- final StrBuilder sb = new StrBuilder();
- sb.appendWithSeparators((Collection>) null, ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(Collections.EMPTY_LIST, ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), ",");
- assertThat(sb.toString()).isEqualTo("foo,bar,baz");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}), null);
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
- assertThat(sb.toString()).isEqualTo("foo,,baz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendWithSeparators_Iterator() {
- final StrBuilder sb = new StrBuilder();
- sb.appendWithSeparators((Iterator>) null, ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(Collections.EMPTY_LIST.iterator(), ",");
- assertThat(sb.toString()).isEqualTo("");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), ",");
- assertThat(sb.toString()).isEqualTo("foo,bar,baz");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", "bar", "baz"}).iterator(), null);
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}).iterator(), ",");
- assertThat(sb.toString()).isEqualTo("foo,,baz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendWithSeparatorsWithNullText() {
- final StrBuilder sb = new StrBuilder();
- sb.setNullText("null");
- sb.appendWithSeparators(new Object[]{"foo", null, "baz"}, ",");
- assertThat(sb.toString()).isEqualTo("foo,null,baz");
-
- sb.clear();
- sb.appendWithSeparators(Arrays.asList(new Object[]{"foo", null, "baz"}), ",");
- assertThat(sb.toString()).isEqualTo("foo,null,baz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendSeparator_String() {
- final StrBuilder sb = new StrBuilder();
- sb.appendSeparator(","); // no effect
- assertThat(sb.toString()).isEqualTo("");
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
- sb.appendSeparator(",");
- assertThat(sb.toString()).isEqualTo("foo,");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendSeparator_String_String() {
- final StrBuilder sb = new StrBuilder();
- final String startSeparator = "order by ";
- final String standardSeparator = ",";
- final String foo = "foo";
- sb.appendSeparator(null, null);
- assertThat(sb.toString()).isEqualTo("");
- sb.appendSeparator(standardSeparator, null);
- assertThat(sb.toString()).isEqualTo("");
- sb.appendSeparator(standardSeparator, startSeparator);
- assertThat(sb.toString()).isEqualTo(startSeparator);
- sb.appendSeparator(null, null);
- assertThat(sb.toString()).isEqualTo(startSeparator);
- sb.appendSeparator(null, startSeparator);
- assertThat(sb.toString()).isEqualTo(startSeparator);
- sb.append(foo);
- assertThat(sb.toString()).isEqualTo(startSeparator + foo);
- sb.appendSeparator(standardSeparator, startSeparator);
- assertThat(sb.toString()).isEqualTo(startSeparator + foo + standardSeparator);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendSeparator_char() {
- final StrBuilder sb = new StrBuilder();
- sb.appendSeparator(','); // no effect
- assertThat(sb.toString()).isEqualTo("");
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
- sb.appendSeparator(',');
- assertThat(sb.toString()).isEqualTo("foo,");
- }
- @Test
- public void testAppendSeparator_char_char() {
- final StrBuilder sb = new StrBuilder();
- final char startSeparator = ':';
- final char standardSeparator = ',';
- final String foo = "foo";
- sb.appendSeparator(standardSeparator, startSeparator); // no effect
- assertThat(sb.toString()).isEqualTo(String.valueOf(startSeparator));
- sb.append(foo);
- assertThat(sb.toString()).isEqualTo(String.valueOf(startSeparator) + foo);
- sb.appendSeparator(standardSeparator, startSeparator);
- assertThat(sb.toString()).isEqualTo(String.valueOf(startSeparator) + foo + standardSeparator);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendSeparator_String_int() {
- final StrBuilder sb = new StrBuilder();
- sb.appendSeparator(",", 0); // no effect
- assertThat(sb.toString()).isEqualTo("");
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
- sb.appendSeparator(",", 1);
- assertThat(sb.toString()).isEqualTo("foo,");
-
- sb.appendSeparator(",", -1); // no effect
- assertThat(sb.toString()).isEqualTo("foo,");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testAppendSeparator_char_int() {
- final StrBuilder sb = new StrBuilder();
- sb.appendSeparator(',', 0); // no effect
- assertThat(sb.toString()).isEqualTo("");
- sb.append("foo");
- assertThat(sb.toString()).isEqualTo("foo");
- sb.appendSeparator(',', 1);
- assertThat(sb.toString()).isEqualTo("foo,");
-
- sb.appendSeparator(',', -1); // no effect
- assertThat(sb.toString()).isEqualTo("foo,");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testInsert() {
-
- final StrBuilder sb = new StrBuilder();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, FOO));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, FOO));
-
- sb.insert(0, (Object) null);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, FOO);
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, "foo"));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, "foo"));
-
- sb.insert(0, (String) null);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, "foo");
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, new char[]{'f', 'o', 'o'}));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, new char[]{'f', 'o', 'o'}));
-
- sb.insert(0, (char[]) null);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, new char[0]);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, new char[]{'f', 'o', 'o'});
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3));
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3));
-
- sb.insert(0, (char[]) null, 0, 0);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, new char[0], 0, 0);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3));
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3));
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1));
-
- assertThrows(IndexOutOfBoundsException.class,
- () -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10));
-
- sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 0);
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
- assertThat(sb.toString()).isEqualTo("foobarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, true));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, true));
-
- sb.insert(0, true);
- assertThat(sb.toString()).isEqualTo("truebarbaz");
-
- sb.insert(0, false);
- assertThat(sb.toString()).isEqualTo("falsetruebarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, '!'));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, '!'));
-
- sb.insert(0, '!');
- assertThat(sb.toString()).isEqualTo("!barbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, 0));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, 0));
-
- sb.insert(0, '0');
- assertThat(sb.toString()).isEqualTo("0barbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, 1L));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, 1L));
-
- sb.insert(0, 1L);
- assertThat(sb.toString()).isEqualTo("1barbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, 2.3F));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, 2.3F));
-
- sb.insert(0, 2.3F);
- assertThat(sb.toString()).isEqualTo("2.3barbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, 4.5D));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, 4.5D));
-
- sb.insert(0, 4.5D);
- assertThat(sb.toString()).isEqualTo("4.5barbaz");
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testInsertWithNullText() {
- final StrBuilder sb = new StrBuilder();
- sb.setNullText("null");
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, FOO));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, FOO));
-
- sb.insert(0, (Object) null);
- assertThat(sb.toString()).isEqualTo("nullbarbaz");
-
- sb.insert(0, FOO);
- assertThat(sb.toString()).isEqualTo("foonullbarbaz");
-
- sb.clear();
- sb.append("barbaz");
- assertThat(sb.toString()).isEqualTo("barbaz");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(-1, "foo"));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.insert(7, "foo"));
-
- sb.insert(0, (String) null);
- assertThat(sb.toString()).isEqualTo("nullbarbaz");
-
- sb.insert(0, "foo");
- assertThat(sb.toString()).isEqualTo("foonullbarbaz");
-
- sb.insert(0, (char[]) null);
- assertThat(sb.toString()).isEqualTo("nullfoonullbarbaz");
-
- sb.insert(0, (char[]) null, 0, 0);
- assertThat(sb.toString()).isEqualTo("nullnullfoonullbarbaz");
- }
-}
diff --git a/src/test/java/org/apache/commons/text/StrBuilderTest.java b/src/test/java/org/apache/commons/text/StrBuilderTest.java
deleted file mode 100644
index c17631a587..0000000000
--- a/src/test/java/org/apache/commons/text/StrBuilderTest.java
+++ /dev/null
@@ -1,2052 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import static org.assertj.core.api.Assertions.fail;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNotSame;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for {@link StrBuilder}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrBuilderTest {
-
- // -----------------------------------------------------------------------
- @Test
- public void testConstructors() {
- final StrBuilder sb0 = new StrBuilder();
- assertEquals(32, sb0.capacity());
- assertEquals(0, sb0.length());
- assertEquals(0, sb0.size());
-
- final StrBuilder sb1 = new StrBuilder(32);
- assertEquals(32, sb1.capacity());
- assertEquals(0, sb1.length());
- assertEquals(0, sb1.size());
-
- final StrBuilder sb2 = new StrBuilder(0);
- assertEquals(32, sb2.capacity());
- assertEquals(0, sb2.length());
- assertEquals(0, sb2.size());
-
- final StrBuilder sb3 = new StrBuilder(-1);
- assertEquals(32, sb3.capacity());
- assertEquals(0, sb3.length());
- assertEquals(0, sb3.size());
-
- final StrBuilder sb4 = new StrBuilder(1);
- assertEquals(1, sb4.capacity());
- assertEquals(0, sb4.length());
- assertEquals(0, sb4.size());
-
- final StrBuilder sb5 = new StrBuilder((String) null);
- assertEquals(32, sb5.capacity());
- assertEquals(0, sb5.length());
- assertEquals(0, sb5.size());
-
- final StrBuilder sb6 = new StrBuilder("");
- assertEquals(32, sb6.capacity());
- assertEquals(0, sb6.length());
- assertEquals(0, sb6.size());
-
- final StrBuilder sb7 = new StrBuilder("foo");
- assertEquals(35, sb7.capacity());
- assertEquals(3, sb7.length());
- assertEquals(3, sb7.size());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testChaining() {
- final StrBuilder sb = new StrBuilder();
- assertSame(sb, sb.setNewLineText(null));
- assertSame(sb, sb.setNullText(null));
- assertSame(sb, sb.setLength(1));
- assertSame(sb, sb.setCharAt(0, 'a'));
- assertSame(sb, sb.ensureCapacity(0));
- assertSame(sb, sb.minimizeCapacity());
- assertSame(sb, sb.clear());
- assertSame(sb, sb.reverse());
- assertSame(sb, sb.trim());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReadFromReader() throws Exception {
- String s = "";
- for (int i = 0; i < 100; ++i) {
- final StrBuilder sb = new StrBuilder();
- final int len = sb.readFrom(new StringReader(s));
-
- assertEquals(s.length(), len);
- assertEquals(s, sb.toString());
-
- s += Integer.toString(i);
- }
- }
-
- @Test
- public void testReadFromReaderAppendsToEnd() throws Exception {
- final StrBuilder sb = new StrBuilder("Test");
- sb.readFrom(new StringReader(" 123"));
- assertEquals("Test 123", sb.toString());
- }
-
- @Test
- public void testReadFromCharBuffer() throws Exception {
- String s = "";
- for (int i = 0; i < 100; ++i) {
- final StrBuilder sb = new StrBuilder();
- final int len = sb.readFrom(CharBuffer.wrap(s));
-
- assertEquals(s.length(), len);
- assertEquals(s, sb.toString());
-
- s += Integer.toString(i);
- }
- }
-
- @Test
- public void testReadFromCharBufferAppendsToEnd() throws Exception {
- final StrBuilder sb = new StrBuilder("Test");
- sb.readFrom(CharBuffer.wrap(" 123"));
- assertEquals("Test 123", sb.toString());
- }
-
- @Test
- public void testReadFromReadable() throws Exception {
- String s = "";
- for (int i = 0; i < 100; ++i) {
- final StrBuilder sb = new StrBuilder();
- final int len = sb.readFrom(new MockReadable(s));
-
- assertEquals(s.length(), len);
- assertEquals(s, sb.toString());
-
- s += Integer.toString(i);
- }
- }
-
- @Test
- public void testReadFromReadableAppendsToEnd() throws Exception {
- final StrBuilder sb = new StrBuilder("Test");
- sb.readFrom(new MockReadable(" 123"));
- assertEquals("Test 123", sb.toString());
- }
-
- private static class MockReadable implements Readable {
-
- private final CharBuffer src;
-
- MockReadable(final String src) {
- this.src = CharBuffer.wrap(src);
- }
-
- @Override
- public int read(final CharBuffer cb) throws IOException {
- return src.read(cb);
- }
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testGetSetNewLineText() {
- final StrBuilder sb = new StrBuilder();
- assertNull(sb.getNewLineText());
-
- sb.setNewLineText("#");
- assertEquals("#", sb.getNewLineText());
-
- sb.setNewLineText("");
- assertEquals("", sb.getNewLineText());
-
- sb.setNewLineText((String) null);
- assertNull(sb.getNewLineText());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testGetSetNullText() {
- final StrBuilder sb = new StrBuilder();
- assertNull(sb.getNullText());
-
- sb.setNullText("null");
- assertEquals("null", sb.getNullText());
-
- sb.setNullText("");
- assertNull(sb.getNullText());
-
- sb.setNullText("NULL");
- assertEquals("NULL", sb.getNullText());
-
- sb.setNullText((String) null);
- assertNull(sb.getNullText());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testCapacityAndLength() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(32, sb.capacity());
- assertEquals(0, sb.length());
- assertEquals(0, sb.size());
- assertTrue(sb.isEmpty());
-
- sb.minimizeCapacity();
- assertEquals(0, sb.capacity());
- assertEquals(0, sb.length());
- assertEquals(0, sb.size());
- assertTrue(sb.isEmpty());
-
- sb.ensureCapacity(32);
- assertTrue(sb.capacity() >= 32);
- assertEquals(0, sb.length());
- assertEquals(0, sb.size());
- assertTrue(sb.isEmpty());
-
- sb.append("foo");
- assertTrue(sb.capacity() >= 32);
- assertEquals(3, sb.length());
- assertEquals(3, sb.size());
- assertFalse(sb.isEmpty());
-
- sb.clear();
- assertTrue(sb.capacity() >= 32);
- assertEquals(0, sb.length());
- assertEquals(0, sb.size());
- assertTrue(sb.isEmpty());
-
- sb.append("123456789012345678901234567890123");
- assertTrue(sb.capacity() > 32);
- assertEquals(33, sb.length());
- assertEquals(33, sb.size());
- assertFalse(sb.isEmpty());
-
- sb.ensureCapacity(16);
- assertTrue(sb.capacity() > 16);
- assertEquals(33, sb.length());
- assertEquals(33, sb.size());
- assertFalse(sb.isEmpty());
-
- sb.minimizeCapacity();
- assertEquals(33, sb.capacity());
- assertEquals(33, sb.length());
- assertEquals(33, sb.size());
- assertFalse(sb.isEmpty());
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.setLength(-1));
-
- sb.setLength(33);
- assertEquals(33, sb.capacity());
- assertEquals(33, sb.length());
- assertEquals(33, sb.size());
- assertFalse(sb.isEmpty());
-
- sb.setLength(16);
- assertTrue(sb.capacity() >= 16);
- assertEquals(16, sb.length());
- assertEquals(16, sb.size());
- assertEquals("1234567890123456", sb.toString());
- assertFalse(sb.isEmpty());
-
- sb.setLength(32);
- assertTrue(sb.capacity() >= 32);
- assertEquals(32, sb.length());
- assertEquals(32, sb.size());
- assertEquals("1234567890123456\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sb.toString());
- assertFalse(sb.isEmpty());
-
- sb.setLength(0);
- assertTrue(sb.capacity() >= 32);
- assertEquals(0, sb.length());
- assertEquals(0, sb.size());
- assertTrue(sb.isEmpty());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testLength() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(0, sb.length());
-
- sb.append("Hello");
- assertEquals(5, sb.length());
- }
-
- @Test
- public void testSetLength() {
- final StrBuilder sb = new StrBuilder();
- sb.append("Hello");
- sb.setLength(2); // shorten
- assertEquals("He", sb.toString());
- sb.setLength(2); // no change
- assertEquals("He", sb.toString());
- sb.setLength(3); // lengthen
- assertEquals("He\0", sb.toString());
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.setLength(-1));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testCapacity() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(sb.buffer.length, sb.capacity());
-
- sb.append("HelloWorldHelloWorldHelloWorldHelloWorld");
- assertEquals(sb.buffer.length, sb.capacity());
- }
-
- @Test
- public void testEnsureCapacity() {
- final StrBuilder sb = new StrBuilder();
- sb.ensureCapacity(2);
- assertTrue(sb.capacity() >= 2);
-
- sb.ensureCapacity(-1);
- assertTrue(sb.capacity() >= 0);
-
- sb.append("HelloWorld");
- sb.ensureCapacity(40);
- assertTrue(sb.capacity() >= 40);
- }
-
- @Test
- public void testMinimizeCapacity() {
- final StrBuilder sb = new StrBuilder();
- sb.minimizeCapacity();
- assertEquals(0, sb.capacity());
-
- sb.append("HelloWorld");
- sb.minimizeCapacity();
- assertEquals(10, sb.capacity());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testSize() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(0, sb.size());
-
- sb.append("Hello");
- assertEquals(5, sb.size());
- }
-
- @Test
- public void testIsEmpty() {
- final StrBuilder sb = new StrBuilder();
- assertTrue(sb.isEmpty());
-
- sb.append("Hello");
- assertFalse(sb.isEmpty());
-
- sb.clear();
- assertTrue(sb.isEmpty());
- }
-
- @Test
- public void testClear() {
- final StrBuilder sb = new StrBuilder();
- sb.append("Hello");
- sb.clear();
- assertEquals(0, sb.length());
- assertTrue(sb.buffer.length >= 5);
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testCharAt() {
- final StrBuilder sb = new StrBuilder();
- assertThrows(IndexOutOfBoundsException.class, () -> sb.charAt(0));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.charAt(-1));
- sb.append("foo");
- assertEquals('f', sb.charAt(0));
- assertEquals('o', sb.charAt(1));
- assertEquals('o', sb.charAt(2));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.charAt(-1));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.charAt(3));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testSetCharAt() {
- final StrBuilder sb = new StrBuilder();
- assertThrows(IndexOutOfBoundsException.class, () -> sb.setCharAt(0, 'f'));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.setCharAt(-1, 'f'));
- sb.append("foo");
- sb.setCharAt(0, 'b');
- sb.setCharAt(1, 'a');
- sb.setCharAt(2, 'r');
- assertThrows(IndexOutOfBoundsException.class, () -> sb.setCharAt(3, '!'));
- assertEquals("bar", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testDeleteCharAt() {
- final StrBuilder sb = new StrBuilder("abc");
- sb.deleteCharAt(0);
- assertEquals("bc", sb.toString());
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.deleteCharAt(1000));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testToCharArray() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(0, sb.toCharArray().length);
-
- char[] a = sb.toCharArray();
- assertNotNull(a, "toCharArray() result is null");
- assertEquals(0, a.length, "toCharArray() result is too large");
-
- sb.append("junit");
- a = sb.toCharArray();
- assertEquals(5, a.length, "toCharArray() result incorrect length");
- assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray() result does not match");
- }
-
- @Test
- public void testToCharArrayIntInt() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(0, sb.toCharArray(0, 0).length);
-
- sb.append("junit");
- char[] a = sb.toCharArray(0, 20); // too large test
- assertEquals(5, a.length, "toCharArray(int,int) result incorrect length");
- assertTrue(Arrays.equals("junit".toCharArray(), a), "toCharArray(int,int) result does not match");
-
- a = sb.toCharArray(0, 4);
- assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
- assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
-
- a = sb.toCharArray(0, 4);
- assertEquals(4, a.length, "toCharArray(int,int) result incorrect length");
- assertTrue(Arrays.equals("juni".toCharArray(), a), "toCharArray(int,int) result does not match");
-
- a = sb.toCharArray(0, 1);
- assertNotNull(a, "toCharArray(int,int) result is null");
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.toCharArray(-1, 5));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.toCharArray(6, 5));
- }
-
- @Test
- public void testGetChars() {
- final StrBuilder sb = new StrBuilder();
-
- char[] input = new char[10];
- char[] a = sb.getChars(input);
- assertSame(input, a);
- assertTrue(Arrays.equals(new char[10], a));
-
- sb.append("junit");
- a = sb.getChars(input);
- assertSame(input, a);
- assertTrue(Arrays.equals(new char[] {'j', 'u', 'n', 'i', 't', 0, 0, 0, 0, 0 }, a));
-
- a = sb.getChars(null);
- assertNotSame(input, a);
- assertEquals(5, a.length);
- assertTrue(Arrays.equals("junit".toCharArray(), a));
-
- input = new char[5];
- a = sb.getChars(input);
- assertSame(input, a);
-
- input = new char[4];
- a = sb.getChars(input);
- assertNotSame(input, a);
- }
-
- @Test
- public void testGetCharsIntIntCharArrayInt() {
- final StrBuilder sb = new StrBuilder();
-
- sb.append("junit");
- char[] a = new char[5];
- sb.getChars(0, 5, a, 0);
- assertTrue(Arrays.equals(new char[] {'j', 'u', 'n', 'i', 't' }, a));
-
- a = new char[5];
- sb.getChars(0, 2, a, 3);
- assertTrue(Arrays.equals(new char[] {0, 0, 0, 'j', 'u' }, a));
-
- try {
- sb.getChars(-1, 0, a, 0);
- fail("no exception");
- } catch (final IndexOutOfBoundsException e) {
- }
-
- try {
- sb.getChars(0, -1, a, 0);
- fail("no exception");
- } catch (final IndexOutOfBoundsException e) {
- }
-
- try {
- sb.getChars(0, 20, a, 0);
- fail("no exception");
- } catch (final IndexOutOfBoundsException e) {
- }
-
- try {
- sb.getChars(4, 2, a, 0);
- fail("no exception");
- } catch (final IndexOutOfBoundsException e) {
- }
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testDeleteIntInt() {
- final StrBuilder sb = new StrBuilder("abc");
- sb.delete(0, 1);
- assertEquals("bc", sb.toString());
- sb.delete(1, 2);
- assertEquals("b", sb.toString());
- sb.delete(0, 1);
- assertEquals("", sb.toString());
- sb.delete(0, 1000);
- assertEquals("", sb.toString());
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.delete(1, 2));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.delete(-1, 1));
-
- assertThrows(IndexOutOfBoundsException.class, () -> new StrBuilder("anything").delete(2, 1));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testDeleteAll_char() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.deleteAll('X');
- assertEquals("abcbccba", sb.toString());
- sb.deleteAll('a');
- assertEquals("bcbccb", sb.toString());
- sb.deleteAll('c');
- assertEquals("bbb", sb.toString());
- sb.deleteAll('b');
- assertEquals("", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteAll('b');
- assertEquals("", sb.toString());
- }
-
- @Test
- public void testDeleteFirst_char() {
- StrBuilder sb = new StrBuilder("abcba");
- sb.deleteFirst('X');
- assertEquals("abcba", sb.toString());
- sb.deleteFirst('a');
- assertEquals("bcba", sb.toString());
- sb.deleteFirst('c');
- assertEquals("bba", sb.toString());
- sb.deleteFirst('b');
- assertEquals("ba", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteFirst('b');
- assertEquals("", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testDeleteAll_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.deleteAll((String) null);
- assertEquals("abcbccba", sb.toString());
- sb.deleteAll("");
- assertEquals("abcbccba", sb.toString());
-
- sb.deleteAll("X");
- assertEquals("abcbccba", sb.toString());
- sb.deleteAll("a");
- assertEquals("bcbccb", sb.toString());
- sb.deleteAll("c");
- assertEquals("bbb", sb.toString());
- sb.deleteAll("b");
- assertEquals("", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.deleteAll("bc");
- assertEquals("acba", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteAll("bc");
- assertEquals("", sb.toString());
- }
-
- @Test
- public void testDeleteFirst_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.deleteFirst((String) null);
- assertEquals("abcbccba", sb.toString());
- sb.deleteFirst("");
- assertEquals("abcbccba", sb.toString());
-
- sb.deleteFirst("X");
- assertEquals("abcbccba", sb.toString());
- sb.deleteFirst("a");
- assertEquals("bcbccba", sb.toString());
- sb.deleteFirst("c");
- assertEquals("bbccba", sb.toString());
- sb.deleteFirst("b");
- assertEquals("bccba", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.deleteFirst("bc");
- assertEquals("abccba", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteFirst("bc");
- assertEquals("", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testDeleteAll_StrMatcher() {
- StrBuilder sb = new StrBuilder("A0xA1A2yA3");
- sb.deleteAll((StrMatcher) null);
- assertEquals("A0xA1A2yA3", sb.toString());
- sb.deleteAll(A_NUMBER_MATCHER);
- assertEquals("xy", sb.toString());
-
- sb = new StrBuilder("Ax1");
- sb.deleteAll(A_NUMBER_MATCHER);
- assertEquals("Ax1", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteAll(A_NUMBER_MATCHER);
- assertEquals("", sb.toString());
- }
-
- @Test
- public void testDeleteFirst_StrMatcher() {
- StrBuilder sb = new StrBuilder("A0xA1A2yA3");
- sb.deleteFirst((StrMatcher) null);
- assertEquals("A0xA1A2yA3", sb.toString());
- sb.deleteFirst(A_NUMBER_MATCHER);
- assertEquals("xA1A2yA3", sb.toString());
-
- sb = new StrBuilder("Ax1");
- sb.deleteFirst(A_NUMBER_MATCHER);
- assertEquals("Ax1", sb.toString());
-
- sb = new StrBuilder("");
- sb.deleteFirst(A_NUMBER_MATCHER);
- assertEquals("", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplace_int_int_String() {
- StrBuilder sb = new StrBuilder("abc");
- sb.replace(0, 1, "d");
- assertEquals("dbc", sb.toString());
- sb.replace(0, 1, "aaa");
- assertEquals("aaabc", sb.toString());
- sb.replace(0, 3, "");
- assertEquals("bc", sb.toString());
- sb.replace(1, 2, (String) null);
- assertEquals("b", sb.toString());
- sb.replace(1, 1000, "text");
- assertEquals("btext", sb.toString());
- sb.replace(0, 1000, "text");
- assertEquals("text", sb.toString());
-
- sb = new StrBuilder("atext");
- sb.replace(1, 1, "ny");
- assertEquals("anytext", sb.toString());
- try {
- sb.replace(2, 1, "anything");
- fail("Expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- }
-
- sb = new StrBuilder();
- try {
- sb.replace(1, 2, "anything");
- fail("Expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- }
- try {
- sb.replace(-1, 1, "anything");
- fail("Expected IndexOutOfBoundsException");
- } catch (final IndexOutOfBoundsException e) {
- }
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplaceAll_char_char() {
- final StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceAll('x', 'y');
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll('a', 'd');
- assertEquals("dbcbccbd", sb.toString());
- sb.replaceAll('b', 'e');
- assertEquals("dececced", sb.toString());
- sb.replaceAll('c', 'f');
- assertEquals("defeffed", sb.toString());
- sb.replaceAll('d', 'd');
- assertEquals("defeffed", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplaceFirst_char_char() {
- final StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceFirst('x', 'y');
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst('a', 'd');
- assertEquals("dbcbccba", sb.toString());
- sb.replaceFirst('b', 'e');
- assertEquals("decbccba", sb.toString());
- sb.replaceFirst('c', 'f');
- assertEquals("defbccba", sb.toString());
- sb.replaceFirst('d', 'd');
- assertEquals("defbccba", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplaceAll_String_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceAll((String) null, null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll((String) null, "anything");
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll("", null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll("", "anything");
- assertEquals("abcbccba", sb.toString());
-
- sb.replaceAll("x", "y");
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll("a", "d");
- assertEquals("dbcbccbd", sb.toString());
- sb.replaceAll("d", null);
- assertEquals("bcbccb", sb.toString());
- sb.replaceAll("cb", "-");
- assertEquals("b-c-", sb.toString());
-
- sb = new StrBuilder("abcba");
- sb.replaceAll("b", "xbx");
- assertEquals("axbxcxbxa", sb.toString());
-
- sb = new StrBuilder("bb");
- sb.replaceAll("b", "xbx");
- assertEquals("xbxxbx", sb.toString());
- }
-
- @Test
- public void testReplaceFirst_String_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceFirst((String) null, null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst((String) null, "anything");
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst("", null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst("", "anything");
- assertEquals("abcbccba", sb.toString());
-
- sb.replaceFirst("x", "y");
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst("a", "d");
- assertEquals("dbcbccba", sb.toString());
- sb.replaceFirst("d", null);
- assertEquals("bcbccba", sb.toString());
- sb.replaceFirst("cb", "-");
- assertEquals("b-ccba", sb.toString());
-
- sb = new StrBuilder("abcba");
- sb.replaceFirst("b", "xbx");
- assertEquals("axbxcba", sb.toString());
-
- sb = new StrBuilder("bb");
- sb.replaceFirst("b", "xbx");
- assertEquals("xbxb", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplaceAll_StrMatcher_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceAll((StrMatcher) null, null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll((StrMatcher) null, "anything");
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll(StrMatcher.noneMatcher(), null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll(StrMatcher.noneMatcher(), "anything");
- assertEquals("abcbccba", sb.toString());
-
- sb.replaceAll(StrMatcher.charMatcher('x'), "y");
- assertEquals("abcbccba", sb.toString());
- sb.replaceAll(StrMatcher.charMatcher('a'), "d");
- assertEquals("dbcbccbd", sb.toString());
- sb.replaceAll(StrMatcher.charMatcher('d'), null);
- assertEquals("bcbccb", sb.toString());
- sb.replaceAll(StrMatcher.stringMatcher("cb"), "-");
- assertEquals("b-c-", sb.toString());
-
- sb = new StrBuilder("abcba");
- sb.replaceAll(StrMatcher.charMatcher('b'), "xbx");
- assertEquals("axbxcxbxa", sb.toString());
-
- sb = new StrBuilder("bb");
- sb.replaceAll(StrMatcher.charMatcher('b'), "xbx");
- assertEquals("xbxxbx", sb.toString());
-
- sb = new StrBuilder("A1-A2A3-A4");
- sb.replaceAll(A_NUMBER_MATCHER, "***");
- assertEquals("***-******-***", sb.toString());
-
- sb = new StrBuilder("Dear X, hello X.");
- sb.replaceAll(StrMatcher.stringMatcher("X"), "012345678901234567");
- assertEquals("Dear 012345678901234567, hello 012345678901234567.", sb.toString());
- }
-
- @Test
- public void testReplaceFirst_StrMatcher_String() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replaceFirst((StrMatcher) null, null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst((StrMatcher) null, "anything");
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst(StrMatcher.noneMatcher(), null);
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst(StrMatcher.noneMatcher(), "anything");
- assertEquals("abcbccba", sb.toString());
-
- sb.replaceFirst(StrMatcher.charMatcher('x'), "y");
- assertEquals("abcbccba", sb.toString());
- sb.replaceFirst(StrMatcher.charMatcher('a'), "d");
- assertEquals("dbcbccba", sb.toString());
- sb.replaceFirst(StrMatcher.charMatcher('d'), null);
- assertEquals("bcbccba", sb.toString());
- sb.replaceFirst(StrMatcher.stringMatcher("cb"), "-");
- assertEquals("b-ccba", sb.toString());
-
- sb = new StrBuilder("abcba");
- sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx");
- assertEquals("axbxcba", sb.toString());
-
- sb = new StrBuilder("bb");
- sb.replaceFirst(StrMatcher.charMatcher('b'), "xbx");
- assertEquals("xbxb", sb.toString());
-
- sb = new StrBuilder("A1-A2A3-A4");
- sb.replaceFirst(A_NUMBER_MATCHER, "***");
- assertEquals("***-A2A3-A4", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReplace_StrMatcher_String_int_int_int_VaryMatcher() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replace((StrMatcher) null, "x", 0, sb.length(), -1);
- assertEquals("abcbccba", sb.toString());
-
- sb.replace(StrMatcher.charMatcher('a'), "x", 0, sb.length(), -1);
- assertEquals("xbcbccbx", sb.toString());
-
- sb.replace(StrMatcher.stringMatcher("cb"), "x", 0, sb.length(), -1);
- assertEquals("xbxcxx", sb.toString());
-
- sb = new StrBuilder("A1-A2A3-A4");
- sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1);
- assertEquals("***-******-***", sb.toString());
-
- sb = new StrBuilder();
- sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1);
- assertEquals("", sb.toString());
- }
-
- @Test
- public void testReplace_StrMatcher_String_int_int_int_VaryReplace() {
- StrBuilder sb = new StrBuilder("abcbccba");
- sb.replace(StrMatcher.stringMatcher("cb"), "cb", 0, sb.length(), -1);
- assertEquals("abcbccba", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.replace(StrMatcher.stringMatcher("cb"), "-", 0, sb.length(), -1);
- assertEquals("ab-c-a", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.replace(StrMatcher.stringMatcher("cb"), "+++", 0, sb.length(), -1);
- assertEquals("ab+++c+++a", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.replace(StrMatcher.stringMatcher("cb"), "", 0, sb.length(), -1);
- assertEquals("abca", sb.toString());
-
- sb = new StrBuilder("abcbccba");
- sb.replace(StrMatcher.stringMatcher("cb"), null, 0, sb.length(), -1);
- assertEquals("abca", sb.toString());
- }
-
- @Test
- public void testReplace_StrMatcher_String_int_int_int_VaryStartIndex() {
- StrBuilder sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, sb.length(), -1);
- assertEquals("-x--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 1, sb.length(), -1);
- assertEquals("aax--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, sb.length(), -1);
- assertEquals("aax--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 3, sb.length(), -1);
- assertEquals("aax--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 4, sb.length(), -1);
- assertEquals("aaxa-ay-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 5, sb.length(), -1);
- assertEquals("aaxaa-y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 6, sb.length(), -1);
- assertEquals("aaxaaaay-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 7, sb.length(), -1);
- assertEquals("aaxaaaay-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 8, sb.length(), -1);
- assertEquals("aaxaaaay-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 9, sb.length(), -1);
- assertEquals("aaxaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 10, sb.length(), -1);
- assertEquals("aaxaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- try {
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- assertEquals("aaxaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- try {
- sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- assertEquals("aaxaaaayaa", sb.toString());
- }
-
- @Test
- public void testReplace_StrMatcher_String_int_int_int_VaryEndIndex() {
- StrBuilder sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 0, -1);
- assertEquals("aaxaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 2, -1);
- assertEquals("-xaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 3, -1);
- assertEquals("-xaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 4, -1);
- assertEquals("-xaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 5, -1);
- assertEquals("-x-aayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 6, -1);
- assertEquals("-x-aayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 7, -1);
- assertEquals("-x--yaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 8, -1);
- assertEquals("-x--yaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 9, -1);
- assertEquals("-x--yaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1);
- assertEquals("-x--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 1000, -1);
- assertEquals("-x--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- try {
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- assertEquals("aaxaaaayaa", sb.toString());
- }
-
- @Test
- public void testReplace_StrMatcher_String_int_int_int_VaryCount() {
- StrBuilder sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, -1);
- assertEquals("-x--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 0);
- assertEquals("aaxaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 1);
- assertEquals("-xaaaayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 2);
- assertEquals("-x-aayaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 3);
- assertEquals("-x--yaa", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 4);
- assertEquals("-x--y-", sb.toString());
-
- sb = new StrBuilder("aaxaaaayaa");
- sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 10, 5);
- assertEquals("-x--y-", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testReverse() {
- final StrBuilder sb = new StrBuilder();
- assertEquals("", sb.reverse().toString());
-
- sb.clear().append(true);
- assertEquals("eurt", sb.reverse().toString());
- assertEquals("true", sb.reverse().toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testTrim() {
- final StrBuilder sb = new StrBuilder();
- assertEquals("", sb.reverse().toString());
-
- sb.clear().append(" \u0000 ");
- assertEquals("", sb.trim().toString());
-
- sb.clear().append(" \u0000 a b c");
- assertEquals("a b c", sb.trim().toString());
-
- sb.clear().append("a b c \u0000 ");
- assertEquals("a b c", sb.trim().toString());
-
- sb.clear().append(" \u0000 a b c \u0000 ");
- assertEquals("a b c", sb.trim().toString());
-
- sb.clear().append("a b c");
- assertEquals("a b c", sb.trim().toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testStartsWith() {
- final StrBuilder sb = new StrBuilder();
- assertFalse(sb.startsWith("a"));
- assertFalse(sb.startsWith(null));
- assertTrue(sb.startsWith(""));
- sb.append("abc");
- assertTrue(sb.startsWith("a"));
- assertTrue(sb.startsWith("ab"));
- assertTrue(sb.startsWith("abc"));
- assertFalse(sb.startsWith("cba"));
- }
-
- @Test
- public void testEndsWith() {
- final StrBuilder sb = new StrBuilder();
- assertFalse(sb.endsWith("a"));
- assertFalse(sb.endsWith("c"));
- assertTrue(sb.endsWith(""));
- assertFalse(sb.endsWith(null));
- sb.append("abc");
- assertTrue(sb.endsWith("c"));
- assertTrue(sb.endsWith("bc"));
- assertTrue(sb.endsWith("abc"));
- assertFalse(sb.endsWith("cba"));
- assertFalse(sb.endsWith("abcd"));
- assertFalse(sb.endsWith(" abc"));
- assertFalse(sb.endsWith("abc "));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testSubSequenceIntInt() {
- final StrBuilder sb = new StrBuilder("hello goodbye");
- // Start index is negative
- assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(-1, 5));
-
- // End index is negative
- assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(2, -1));
-
- // End index greater than length()
- assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(2, sb.length() + 1));
-
- // Start index greater then end index
- assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(3, 2));
-
- // Normal cases
- assertEquals("hello", sb.subSequence(0, 5));
- assertEquals("hello goodbye".subSequence(0, 6), sb.subSequence(0, 6));
- assertEquals("goodbye", sb.subSequence(6, 13));
- assertEquals("hello goodbye".subSequence(6, 13), sb.subSequence(6, 13));
- }
-
- @Test
- public void testSubstringInt() {
- final StrBuilder sb = new StrBuilder("hello goodbye");
- assertEquals("goodbye", sb.substring(6));
- assertEquals("hello goodbye".substring(6), sb.substring(6));
- assertEquals("hello goodbye", sb.substring(0));
- assertEquals("hello goodbye".substring(0), sb.substring(0));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(-1));
- assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(15));
-
- }
-
- @Test
- public void testSubstringIntInt() {
- final StrBuilder sb = new StrBuilder("hello goodbye");
- assertEquals("hello", sb.substring(0, 5));
- assertEquals("hello goodbye".substring(0, 6), sb.substring(0, 6));
-
- assertEquals("goodbye", sb.substring(6, 13));
- assertEquals("hello goodbye".substring(6, 13), sb.substring(6, 13));
-
- assertEquals("goodbye", sb.substring(6, 20));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(-1, 5));
-
- assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(15, 20));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testMidString() {
- final StrBuilder sb = new StrBuilder("hello goodbye hello");
- assertEquals("goodbye", sb.midString(6, 7));
- assertEquals("hello", sb.midString(0, 5));
- assertEquals("hello", sb.midString(-5, 5));
- assertEquals("", sb.midString(0, -1));
- assertEquals("", sb.midString(20, 2));
- assertEquals("hello", sb.midString(14, 22));
- }
-
- @Test
- public void testRightString() {
- final StrBuilder sb = new StrBuilder("left right");
- assertEquals("right", sb.rightString(5));
- assertEquals("", sb.rightString(0));
- assertEquals("", sb.rightString(-5));
- assertEquals("left right", sb.rightString(15));
- }
-
- @Test
- public void testLeftString() {
- final StrBuilder sb = new StrBuilder("left right");
- assertEquals("left", sb.leftString(4));
- assertEquals("", sb.leftString(0));
- assertEquals("", sb.leftString(-5));
- assertEquals("left right", sb.leftString(15));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testContains_char() {
- final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
- assertTrue(sb.contains('a'));
- assertTrue(sb.contains('o'));
- assertTrue(sb.contains('z'));
- assertFalse(sb.contains('1'));
- }
-
- @Test
- public void testContains_String() {
- final StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
- assertTrue(sb.contains("a"));
- assertTrue(sb.contains("pq"));
- assertTrue(sb.contains("z"));
- assertFalse(sb.contains("zyx"));
- assertFalse(sb.contains((String) null));
- }
-
- @Test
- public void testContains_StrMatcher() {
- StrBuilder sb = new StrBuilder("abcdefghijklmnopqrstuvwxyz");
- assertTrue(sb.contains(StrMatcher.charMatcher('a')));
- assertTrue(sb.contains(StrMatcher.stringMatcher("pq")));
- assertTrue(sb.contains(StrMatcher.charMatcher('z')));
- assertFalse(sb.contains(StrMatcher.stringMatcher("zy")));
- assertFalse(sb.contains((StrMatcher) null));
-
- sb = new StrBuilder();
- assertFalse(sb.contains(A_NUMBER_MATCHER));
- sb.append("B A1 C");
- assertTrue(sb.contains(A_NUMBER_MATCHER));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testIndexOf_char() {
- final StrBuilder sb = new StrBuilder("abab");
- assertEquals(0, sb.indexOf('a'));
-
- // should work like String#indexOf
- assertEquals("abab".indexOf('a'), sb.indexOf('a'));
-
- assertEquals(1, sb.indexOf('b'));
- assertEquals("abab".indexOf('b'), sb.indexOf('b'));
-
- assertEquals(-1, sb.indexOf('z'));
- }
-
- @Test
- public void testIndexOf_char_int() {
- StrBuilder sb = new StrBuilder("abab");
- assertEquals(0, sb.indexOf('a', -1));
- assertEquals(0, sb.indexOf('a', 0));
- assertEquals(2, sb.indexOf('a', 1));
- assertEquals(-1, sb.indexOf('a', 4));
- assertEquals(-1, sb.indexOf('a', 5));
-
- // should work like String#indexOf
- assertEquals("abab".indexOf('a', 1), sb.indexOf('a', 1));
-
- assertEquals(3, sb.indexOf('b', 2));
- assertEquals("abab".indexOf('b', 2), sb.indexOf('b', 2));
-
- assertEquals(-1, sb.indexOf('z', 2));
-
- sb = new StrBuilder("xyzabc");
- assertEquals(2, sb.indexOf('z', 0));
- assertEquals(-1, sb.indexOf('z', 3));
- }
-
- @Test
- public void testLastIndexOf_char() {
- final StrBuilder sb = new StrBuilder("abab");
-
- assertEquals(2, sb.lastIndexOf('a'));
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf('a'), sb.lastIndexOf('a'));
-
- assertEquals(3, sb.lastIndexOf('b'));
- assertEquals("abab".lastIndexOf('b'), sb.lastIndexOf('b'));
-
- assertEquals(-1, sb.lastIndexOf('z'));
- }
-
- @Test
- public void testLastIndexOf_char_int() {
- StrBuilder sb = new StrBuilder("abab");
- assertEquals(-1, sb.lastIndexOf('a', -1));
- assertEquals(0, sb.lastIndexOf('a', 0));
- assertEquals(0, sb.lastIndexOf('a', 1));
-
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf('a', 1), sb.lastIndexOf('a', 1));
-
- assertEquals(1, sb.lastIndexOf('b', 2));
- assertEquals("abab".lastIndexOf('b', 2), sb.lastIndexOf('b', 2));
-
- assertEquals(-1, sb.lastIndexOf('z', 2));
-
- sb = new StrBuilder("xyzabc");
- assertEquals(2, sb.lastIndexOf('z', sb.length()));
- assertEquals(-1, sb.lastIndexOf('z', 1));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testIndexOf_String() {
- final StrBuilder sb = new StrBuilder("abab");
-
- assertEquals(0, sb.indexOf("a"));
- // should work like String#indexOf
- assertEquals("abab".indexOf("a"), sb.indexOf("a"));
-
- assertEquals(0, sb.indexOf("ab"));
- // should work like String#indexOf
- assertEquals("abab".indexOf("ab"), sb.indexOf("ab"));
-
- assertEquals(1, sb.indexOf("b"));
- assertEquals("abab".indexOf("b"), sb.indexOf("b"));
-
- assertEquals(1, sb.indexOf("ba"));
- assertEquals("abab".indexOf("ba"), sb.indexOf("ba"));
-
- assertEquals(-1, sb.indexOf("z"));
-
- assertEquals(-1, sb.indexOf((String) null));
- }
-
- @Test
- public void testIndexOf_String_int() {
- StrBuilder sb = new StrBuilder("abab");
- assertEquals(0, sb.indexOf("a", -1));
- assertEquals(0, sb.indexOf("a", 0));
- assertEquals(2, sb.indexOf("a", 1));
- assertEquals(2, sb.indexOf("a", 2));
- assertEquals(-1, sb.indexOf("a", 3));
- assertEquals(-1, sb.indexOf("a", 4));
- assertEquals(-1, sb.indexOf("a", 5));
-
- assertEquals(-1, sb.indexOf("abcdef", 0));
- assertEquals(0, sb.indexOf("", 0));
- assertEquals(1, sb.indexOf("", 1));
-
- // should work like String#indexOf
- assertEquals("abab".indexOf("a", 1), sb.indexOf("a", 1));
-
- assertEquals(2, sb.indexOf("ab", 1));
- // should work like String#indexOf
- assertEquals("abab".indexOf("ab", 1), sb.indexOf("ab", 1));
-
- assertEquals(3, sb.indexOf("b", 2));
- assertEquals("abab".indexOf("b", 2), sb.indexOf("b", 2));
-
- assertEquals(1, sb.indexOf("ba", 1));
- assertEquals("abab".indexOf("ba", 2), sb.indexOf("ba", 2));
-
- assertEquals(-1, sb.indexOf("z", 2));
-
- sb = new StrBuilder("xyzabc");
- assertEquals(2, sb.indexOf("za", 0));
- assertEquals(-1, sb.indexOf("za", 3));
-
- assertEquals(-1, sb.indexOf((String) null, 2));
- }
-
- @Test
- public void testLastIndexOf_String() {
- final StrBuilder sb = new StrBuilder("abab");
-
- assertEquals(2, sb.lastIndexOf("a"));
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf("a"), sb.lastIndexOf("a"));
-
- assertEquals(2, sb.lastIndexOf("ab"));
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf("ab"), sb.lastIndexOf("ab"));
-
- assertEquals(3, sb.lastIndexOf("b"));
- assertEquals("abab".lastIndexOf("b"), sb.lastIndexOf("b"));
-
- assertEquals(1, sb.lastIndexOf("ba"));
- assertEquals("abab".lastIndexOf("ba"), sb.lastIndexOf("ba"));
-
- assertEquals(-1, sb.lastIndexOf("z"));
-
- assertEquals(-1, sb.lastIndexOf((String) null));
- }
-
- @Test
- public void testLastIndexOf_String_int() {
- StrBuilder sb = new StrBuilder("abab");
- assertEquals(-1, sb.lastIndexOf("a", -1));
- assertEquals(0, sb.lastIndexOf("a", 0));
- assertEquals(0, sb.lastIndexOf("a", 1));
- assertEquals(2, sb.lastIndexOf("a", 2));
- assertEquals(2, sb.lastIndexOf("a", 3));
- assertEquals(2, sb.lastIndexOf("a", 4));
- assertEquals(2, sb.lastIndexOf("a", 5));
-
- assertEquals(-1, sb.lastIndexOf("abcdef", 3));
- assertEquals("abab".lastIndexOf("", 3), sb.lastIndexOf("", 3));
- assertEquals("abab".lastIndexOf("", 1), sb.lastIndexOf("", 1));
-
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf("a", 1), sb.lastIndexOf("a", 1));
-
- assertEquals(0, sb.lastIndexOf("ab", 1));
- // should work like String#lastIndexOf
- assertEquals("abab".lastIndexOf("ab", 1), sb.lastIndexOf("ab", 1));
-
- assertEquals(1, sb.lastIndexOf("b", 2));
- assertEquals("abab".lastIndexOf("b", 2), sb.lastIndexOf("b", 2));
-
- assertEquals(1, sb.lastIndexOf("ba", 2));
- assertEquals("abab".lastIndexOf("ba", 2), sb.lastIndexOf("ba", 2));
-
- assertEquals(-1, sb.lastIndexOf("z", 2));
-
- sb = new StrBuilder("xyzabc");
- assertEquals(2, sb.lastIndexOf("za", sb.length()));
- assertEquals(-1, sb.lastIndexOf("za", 1));
-
- assertEquals(-1, sb.lastIndexOf((String) null, 2));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testIndexOf_StrMatcher() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(-1, sb.indexOf((StrMatcher) null));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a')));
-
- sb.append("ab bd");
- assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a')));
- assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b')));
- assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher()));
- assertEquals(4, sb.indexOf(StrMatcher.charMatcher('d')));
- assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher()));
- assertEquals(-1, sb.indexOf((StrMatcher) null));
-
- sb.append(" A1 junction");
- assertEquals(6, sb.indexOf(A_NUMBER_MATCHER));
- }
-
- @Test
- public void testIndexOf_StrMatcher_int() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(-1, sb.indexOf((StrMatcher) null, 2));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 0));
-
- sb.append("ab bd");
- assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), -2));
- assertEquals(0, sb.indexOf(StrMatcher.charMatcher('a'), 0));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 2));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('a'), 20));
-
- assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), -1));
- assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 0));
- assertEquals(1, sb.indexOf(StrMatcher.charMatcher('b'), 1));
- assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 2));
- assertEquals(3, sb.indexOf(StrMatcher.charMatcher('b'), 3));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 4));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 5));
- assertEquals(-1, sb.indexOf(StrMatcher.charMatcher('b'), 6));
-
- assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), -2));
- assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 0));
- assertEquals(2, sb.indexOf(StrMatcher.spaceMatcher(), 2));
- assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 4));
- assertEquals(-1, sb.indexOf(StrMatcher.spaceMatcher(), 20));
-
- assertEquals(-1, sb.indexOf(StrMatcher.noneMatcher(), 0));
- assertEquals(-1, sb.indexOf((StrMatcher) null, 0));
-
- sb.append(" A1 junction with A2");
- assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 5));
- assertEquals(6, sb.indexOf(A_NUMBER_MATCHER, 6));
- assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 7));
- assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 22));
- assertEquals(23, sb.indexOf(A_NUMBER_MATCHER, 23));
- assertEquals(-1, sb.indexOf(A_NUMBER_MATCHER, 24));
- }
-
- @Test
- public void testLastIndexOf_StrMatcher() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(-1, sb.lastIndexOf((StrMatcher) null));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a')));
-
- sb.append("ab bd");
- assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a')));
- assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b')));
- assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher()));
- assertEquals(4, sb.lastIndexOf(StrMatcher.charMatcher('d')));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher()));
- assertEquals(-1, sb.lastIndexOf((StrMatcher) null));
-
- sb.append(" A1 junction");
- assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER));
- }
-
- @Test
- public void testLastIndexOf_StrMatcher_int() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 2));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -1));
-
- sb.append("ab bd");
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('a'), -2));
- assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 0));
- assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 2));
- assertEquals(0, sb.lastIndexOf(StrMatcher.charMatcher('a'), 20));
-
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), -1));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 0));
- assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 1));
- assertEquals(1, sb.lastIndexOf(StrMatcher.charMatcher('b'), 2));
- assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 3));
- assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 4));
- assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 5));
- assertEquals(3, sb.lastIndexOf(StrMatcher.charMatcher('b'), 6));
-
- assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), -2));
- assertEquals(-1, sb.lastIndexOf(StrMatcher.spaceMatcher(), 0));
- assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 2));
- assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 4));
- assertEquals(2, sb.lastIndexOf(StrMatcher.spaceMatcher(), 20));
-
- assertEquals(-1, sb.lastIndexOf(StrMatcher.noneMatcher(), 0));
- assertEquals(-1, sb.lastIndexOf((StrMatcher) null, 0));
-
- sb.append(" A1 junction with A2");
- assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 5));
- assertEquals(-1, sb.lastIndexOf(A_NUMBER_MATCHER, 6)); // A matches, 1
- // is outside
- // bounds
- assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 7));
- assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 22));
- assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER, 23)); // A matches, 2
- // is outside
- // bounds
- assertEquals(23, sb.lastIndexOf(A_NUMBER_MATCHER, 24));
- }
-
- static final StrMatcher A_NUMBER_MATCHER = new StrMatcher() {
-
- @Override
- public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
- if (buffer[pos] == 'A') {
- pos++;
- if (pos < bufferEnd && buffer[pos] >= '0' && buffer[pos] <= '9') {
- return 2;
- }
- }
- return 0;
- }
- };
-
- // -----------------------------------------------------------------------
- @Test
- public void testAsTokenizer() throws Exception {
- // from Javadoc
- final StrBuilder b = new StrBuilder();
- b.append("a b ");
- final StrTokenizer t = b.asTokenizer();
-
- final String[] tokens1 = t.getTokenArray();
- assertEquals(2, tokens1.length);
- assertEquals("a", tokens1[0]);
- assertEquals("b", tokens1[1]);
- assertEquals(2, t.size());
-
- b.append("c d ");
- final String[] tokens2 = t.getTokenArray();
- assertEquals(2, tokens2.length);
- assertEquals("a", tokens2[0]);
- assertEquals("b", tokens2[1]);
- assertEquals(2, t.size());
- assertEquals("a", t.next());
- assertEquals("b", t.next());
-
- t.reset();
- final String[] tokens3 = t.getTokenArray();
- assertEquals(4, tokens3.length);
- assertEquals("a", tokens3[0]);
- assertEquals("b", tokens3[1]);
- assertEquals("c", tokens3[2]);
- assertEquals("d", tokens3[3]);
- assertEquals(4, t.size());
- assertEquals("a", t.next());
- assertEquals("b", t.next());
- assertEquals("c", t.next());
- assertEquals("d", t.next());
-
- assertEquals("a b c d ", t.getContent());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testAsReader() throws Exception {
- final StrBuilder sb = new StrBuilder("some text");
- Reader reader = sb.asReader();
- assertTrue(reader.ready());
- final char[] buf = new char[40];
- assertEquals(9, reader.read(buf));
- assertEquals("some text", new String(buf, 0, 9));
-
- assertEquals(-1, reader.read());
- assertFalse(reader.ready());
- assertEquals(0, reader.skip(2));
- assertEquals(0, reader.skip(-1));
-
- assertTrue(reader.markSupported());
- reader = sb.asReader();
- assertEquals('s', reader.read());
- reader.mark(-1);
- char[] array = new char[3];
- assertEquals(3, reader.read(array, 0, 3));
- assertEquals('o', array[0]);
- assertEquals('m', array[1]);
- assertEquals('e', array[2]);
- reader.reset();
- assertEquals(1, reader.read(array, 1, 1));
- assertEquals('o', array[0]);
- assertEquals('o', array[1]);
- assertEquals('e', array[2]);
- assertEquals(2, reader.skip(2));
- assertEquals(' ', reader.read());
-
- assertTrue(reader.ready());
- reader.close();
- assertTrue(reader.ready());
-
- reader = sb.asReader();
- array = new char[3];
- try {
- reader.read(array, -1, 0);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- try {
- reader.read(array, 0, -1);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- try {
- reader.read(array, 100, 1);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- try {
- reader.read(array, 0, 100);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
- try {
- reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE);
- fail("Exception expected!");
- } catch (final IndexOutOfBoundsException ex) {
- }
-
- assertEquals(0, reader.read(array, 0, 0));
- assertEquals(0, array[0]);
- assertEquals(0, array[1]);
- assertEquals(0, array[2]);
-
- reader.skip(9);
- assertEquals(-1, reader.read(array, 0, 1));
-
- reader.reset();
- array = new char[30];
- assertEquals(9, reader.read(array, 0, 30));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testAsWriter() throws Exception {
- final StrBuilder sb = new StrBuilder("base");
- final Writer writer = sb.asWriter();
-
- writer.write('l');
- assertEquals("basel", sb.toString());
-
- writer.write(new char[] {'i', 'n' });
- assertEquals("baselin", sb.toString());
-
- writer.write(new char[] {'n', 'e', 'r' }, 1, 2);
- assertEquals("baseliner", sb.toString());
-
- writer.write(" rout");
- assertEquals("baseliner rout", sb.toString());
-
- writer.write("ping that server", 1, 3);
- assertEquals("baseliner routing", sb.toString());
-
- writer.flush(); // no effect
- assertEquals("baseliner routing", sb.toString());
-
- writer.close(); // no effect
- assertEquals("baseliner routing", sb.toString());
-
- writer.write(" hi"); // works after close
- assertEquals("baseliner routing hi", sb.toString());
-
- sb.setLength(4); // mix and match
- writer.write('d');
- assertEquals("based", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testEqualsIgnoreCase() {
- final StrBuilder sb1 = new StrBuilder();
- final StrBuilder sb2 = new StrBuilder();
- assertTrue(sb1.equalsIgnoreCase(sb1));
- assertTrue(sb1.equalsIgnoreCase(sb2));
- assertTrue(sb2.equalsIgnoreCase(sb2));
-
- sb1.append("abc");
- assertFalse(sb1.equalsIgnoreCase(sb2));
-
- sb2.append("ABC");
- assertTrue(sb1.equalsIgnoreCase(sb2));
-
- sb2.clear().append("abc");
- assertTrue(sb1.equalsIgnoreCase(sb2));
- assertTrue(sb1.equalsIgnoreCase(sb1));
- assertTrue(sb2.equalsIgnoreCase(sb2));
-
- sb2.clear().append("aBc");
- assertTrue(sb1.equalsIgnoreCase(sb2));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testEquals() {
- final StrBuilder sb1 = new StrBuilder();
- final StrBuilder sb2 = new StrBuilder();
- assertTrue(sb1.equals(sb2));
- assertTrue(sb1.equals(sb1));
- assertTrue(sb2.equals(sb2));
- assertTrue(sb1.equals((Object) sb2));
-
- sb1.append("abc");
- assertFalse(sb1.equals(sb2));
- assertFalse(sb1.equals((Object) sb2));
-
- sb2.append("ABC");
- assertFalse(sb1.equals(sb2));
- assertFalse(sb1.equals((Object) sb2));
-
- sb2.clear().append("abc");
- assertTrue(sb1.equals(sb2));
- assertTrue(sb1.equals((Object) sb2));
-
- assertFalse(sb1.equals(Integer.valueOf(1)));
- assertFalse(sb1.equals("abc"));
- }
-
- @Test
- public void test_LANG_1131_EqualsWithNullStrBuilder() throws Exception {
- final StrBuilder sb = new StrBuilder();
- final StrBuilder other = null;
- assertFalse(sb.equals(other));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testHashCode() {
- final StrBuilder sb = new StrBuilder();
- final int hc1a = sb.hashCode();
- final int hc1b = sb.hashCode();
- assertEquals(0, hc1a);
- assertEquals(hc1a, hc1b);
-
- sb.append("abc");
- final int hc2a = sb.hashCode();
- final int hc2b = sb.hashCode();
- assertTrue(hc2a != 0);
- assertEquals(hc2a, hc2b);
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testToString() {
- final StrBuilder sb = new StrBuilder("abc");
- assertEquals("abc", sb.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testToStringBuffer() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(new StringBuffer().toString(), sb.toStringBuffer().toString());
-
- sb.append("junit");
- assertEquals(new StringBuffer("junit").toString(), sb.toStringBuffer().toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testToStringBuilder() {
- final StrBuilder sb = new StrBuilder();
- assertEquals(new StringBuilder().toString(), sb.toStringBuilder().toString());
-
- sb.append("junit");
- assertEquals(new StringBuilder("junit").toString(), sb.toStringBuilder().toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testLang294() {
- final StrBuilder sb = new StrBuilder("\n%BLAH%\nDo more stuff\neven more stuff\n%BLAH%\n");
- sb.deleteAll("\n%BLAH%");
- assertEquals("\nDo more stuff\neven more stuff\n", sb.toString());
- }
-
- @Test
- public void testIndexOfLang294() {
- final StrBuilder sb = new StrBuilder("onetwothree");
- sb.deleteFirst("three");
- assertEquals(-1, sb.indexOf("three"));
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testLang295() {
- final StrBuilder sb = new StrBuilder("onetwothree");
- sb.deleteFirst("three");
- assertFalse(sb.contains('h'), "The contains(char) method is looking beyond the end of the string");
- assertEquals(-1, sb.indexOf('h'), "The indexOf(char) method is looking beyond the end of the string");
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testLang412Right() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadRight(null, 10, '*');
- assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadRight correctly");
- }
-
- @Test
- public void testLang412Left() {
- final StrBuilder sb = new StrBuilder();
- sb.appendFixedWidthPadLeft(null, 10, '*');
- assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadLeft correctly");
- }
-
- @Test
- public void testAsBuilder() {
- final StrBuilder sb = new StrBuilder().appendAll("Lorem", " ", "ipsum", " ", "dolor");
- assertEquals(sb.toString(), sb.build());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testAppendCharBuffer() {
- final StrBuilder sb1 = new StrBuilder();
- final CharBuffer buf = CharBuffer.allocate(10);
- buf.append("0123456789");
- buf.flip();
- sb1.append(buf);
- assertEquals("0123456789", sb1.toString());
-
- final StrBuilder sb2 = new StrBuilder();
- sb2.append(buf, 1, 8);
- assertEquals("12345678", sb2.toString());
- }
-
- // -----------------------------------------------------------------------
- @Test
- public void testAppendToWriter() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final StringWriter writer = new StringWriter();
- writer.append("Test ");
-
- sb.appendTo(writer);
-
- assertEquals("Test 1234567890", writer.toString());
- }
-
- @Test
- public void testAppendToStringBuilder() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final StringBuilder builder = new StringBuilder("Test ");
-
- sb.appendTo(builder);
-
- assertEquals("Test 1234567890", builder.toString());
- }
-
- @Test
- public void testAppendToStringBuffer() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final StringBuffer buffer = new StringBuffer("Test ");
-
- sb.appendTo(buffer);
-
- assertEquals("Test 1234567890", buffer.toString());
- }
-
- @Test
- public void testAppendToCharBuffer() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final String text = "Test ";
- final CharBuffer buffer = CharBuffer.allocate(sb.size() + text.length());
- buffer.put(text);
-
- sb.appendTo(buffer);
-
- buffer.flip();
- assertEquals("Test 1234567890", buffer.toString());
- }
-
- @Test
- public void testAppendCharBufferNull() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final CharBuffer buffer = null;
- sb.append(buffer);
- assertEquals("1234567890", sb.toString());
-
- final StrBuilder sb1 = new StrBuilder("1234567890");
- final CharBuffer buffer1 = null;
- sb.append(buffer1, 0, 0);
- assertEquals("1234567890", sb1.toString());
- }
-
- @Test
- public void testAppendCharBufferException() throws Exception {
- final StrBuilder sb = new StrBuilder("1234567890");
- final String text = "Test";
- final CharBuffer buffer = CharBuffer.allocate(sb.size() + text.length());
- buffer.put(text);
- buffer.flip();
- try {
- sb.append(buffer, -1, 12);
- } catch (final StringIndexOutOfBoundsException e) {
- assertEquals("startIndex must be valid", e.getMessage());
- }
-
- try {
- sb.append(buffer, 0, -1);
- } catch (final StringIndexOutOfBoundsException e) {
- assertEquals("length must be valid", e.getMessage());
- }
-
- sb.append(buffer);
- assertEquals("1234567890Test", sb.toString());
- }
-
- @Test
- public void testAppendCharSequence() {
- final CharSequence obj0 = null;
- final CharSequence obj1 = new StrBuilder("test1");
- final CharSequence obj2 = new StringBuilder("test2");
- final CharSequence obj3 = new StringBuffer("test3");
- final CharBuffer obj4 = CharBuffer.wrap("test4".toCharArray());
-
- final StrBuilder sb0 = new StrBuilder();
- assertEquals("", sb0.append(obj0).toString());
-
- final StrBuilder sb1 = new StrBuilder();
- assertEquals("test1", sb1.append(obj1).toString());
-
- final StrBuilder sb2 = new StrBuilder();
- assertEquals("test2", sb2.append(obj2).toString());
-
- final StrBuilder sb3 = new StrBuilder();
- assertEquals("test3", sb3.append(obj3).toString());
-
- final StrBuilder sb4 = new StrBuilder();
- assertEquals("test4", sb4.append(obj4).toString());
-
- final StrBuilder sb5 = new StrBuilder();
- assertEquals("", sb5.append(obj0, 0, 0).toString());
- }
-
- @Test
- public void testAppendStringBuilderNull() {
- final StrBuilder sb1 = new StrBuilder();
- final StringBuilder b = null;
- assertEquals("", sb1.append(b).toString());
-
- final StrBuilder sb2 = new StrBuilder();
- assertEquals("", sb2.append(b, 0, 0).toString());
- }
-
- @Test
- public void testAppendln() {
- final StrBuilder sb1 = new StrBuilder();
- final char ch = 'c';
- assertEquals("c" + System.lineSeparator(), sb1.appendln(ch).toString());
- }
-
- @Test
- public void testAppendTakingTwoIntsWithZeroThrowsStringIndexOutOfBoundsException() {
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("end < start");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
-
- new StrBuilder(630).append(charBuffer, 0, 630);
- });
- }
-
- @Test
- public void testAppendTakingTwoIntsWithIndexOutOfBoundsThrowsStringIndexOutOfBoundsExceptionTwo() {
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
- final Charset charset = Charset.defaultCharset();
- final ByteBuffer byteBuffer = charset.encode("asdf");
- final CharBuffer charBuffer = charset.decode(byteBuffer);
-
- new StrBuilder().append(charBuffer, 933, 654);
- });
- }
-
- @Test
- public void testDeleteCharAtWithNegative() {
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> {
- new StrBuilder().deleteCharAt((-1258));
- });
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/StrLookupTest.java b/src/test/java/org/apache/commons/text/StrLookupTest.java
deleted file mode 100644
index 876bfc4196..0000000000
--- a/src/test/java/org/apache/commons/text/StrLookupTest.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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;
-
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-import java.util.ResourceBundle;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Test class for {@link StrLookup}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrLookupTest {
-
- //-----------------------------------------------------------------------
- @Test
- public void testNoneLookup() {
- assertNull(StrLookup.noneLookup().lookup(null));
- assertNull(StrLookup.noneLookup().lookup(""));
- assertNull(StrLookup.noneLookup().lookup("any"));
- }
-
- @Test
- public void testSystemProperiesLookup() {
- assertEquals(System.getProperty("os.name"), StrLookup.systemPropertiesLookup().lookup("os.name"));
- assertNull(StrLookup.systemPropertiesLookup().lookup(""));
- assertNull(StrLookup.systemPropertiesLookup().lookup("other"));
- assertThrows(NullPointerException.class, () -> StrLookup.systemPropertiesLookup().lookup(null));
- }
-
- /**
- * Tests that a lookup object for system properties can deal with a full
- * replacement of the system properties object. This test is related to
- * LANG-1055.
- */
- @Test
- public void testSystemPropertiesLookupReplacedProperties() {
- final Properties oldProperties = System.getProperties();
- final String osName = "os.name";
- final String newOsName = oldProperties.getProperty(osName) + "_changed";
-
- final StrLookup sysLookup = StrLookup.systemPropertiesLookup();
- final Properties newProps = new Properties();
- newProps.setProperty(osName, newOsName);
- System.setProperties(newProps);
- try {
- assertEquals(newOsName, sysLookup.lookup(osName), "Changed properties not detected");
- } finally {
- System.setProperties(oldProperties);
- }
- }
-
- /**
- * Tests that a lookup object for system properties sees changes on system
- * properties. This test is related to LANG-1141.
- */
- @Test
- public void testSystemPropertiesLookupUpdatedProperty() {
- final String osName = "os.name";
- final String oldOs = System.getProperty(osName);
- final String newOsName = oldOs + "_changed";
-
- final StrLookup sysLookup = StrLookup.systemPropertiesLookup();
- System.setProperty(osName, newOsName);
- try {
- assertEquals(newOsName, sysLookup.lookup(osName), "Changed properties not detected");
- } finally {
- System.setProperty(osName, oldOs);
- }
- }
-
- @Test
- public void testMapLookup() {
- final Map map = new HashMap<>();
- map.put("key", "value");
- map.put("number", 2);
- assertEquals("value", StrLookup.mapLookup(map).lookup("key"));
- assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
- assertNull(StrLookup.mapLookup(map).lookup(null));
- assertNull(StrLookup.mapLookup(map).lookup(""));
- assertNull(StrLookup.mapLookup(map).lookup("other"));
- }
-
- @Test
- public void testResourceBundleLookup() {
- final ResourceBundle map = ResourceBundle.getBundle("testResourceBundleLookup");
- assertEquals("value", StrLookup.resourceBundleLookup(map).lookup("key"));
- assertEquals("2", StrLookup.resourceBundleLookup(map).lookup("number"));
- assertNull(StrLookup.resourceBundleLookup(map).lookup(null));
- assertNull(StrLookup.resourceBundleLookup(map).lookup(""));
- assertNull(StrLookup.resourceBundleLookup(map).lookup("other"));
- }
-
- @Test
- public void testResourceBundleLookup_nullMap() {
- final ResourceBundle resourceBundle = null;
- assertNull(StrLookup.resourceBundleLookup(resourceBundle).lookup(null));
- assertNull(StrLookup.resourceBundleLookup(resourceBundle).lookup(""));
- assertNull(StrLookup.resourceBundleLookup(resourceBundle).lookup("any"));
- }
-
- @Test
- public void testMapLookup_nullMap() {
- final Map map = null;
- assertNull(StrLookup.mapLookup(map).lookup(null));
- assertNull(StrLookup.mapLookup(map).lookup(""));
- assertNull(StrLookup.mapLookup(map).lookup("any"));
- }
-
-
-}
diff --git a/src/test/java/org/apache/commons/text/StrMatcherTest.java b/src/test/java/org/apache/commons/text/StrMatcherTest.java
deleted file mode 100644
index f35647fa5e..0000000000
--- a/src/test/java/org/apache/commons/text/StrMatcherTest.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import org.junit.jupiter.api.Test;
-
-/**
- * Unit tests for {@link StrMatcher}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrMatcherTest {
-
- private static final char[] BUFFER1 = "0,1\t2 3\n\r\f\u0000'\"".toCharArray();
-
- private static final char[] BUFFER2 = "abcdef".toCharArray();
-
-
- //-----------------------------------------------------------------------
- @Test
- public void testCommaMatcher() {
- final StrMatcher matcher = StrMatcher.commaMatcher();
- assertThat(StrMatcher.commaMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 0)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 1)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 2)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testTabMatcher() {
- final StrMatcher matcher = StrMatcher.tabMatcher();
- assertThat(StrMatcher.tabMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 2)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 3)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 4)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testSpaceMatcher() {
- final StrMatcher matcher = StrMatcher.spaceMatcher();
- assertThat(StrMatcher.spaceMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 5)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 6)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testSplitMatcher() {
- final StrMatcher matcher = StrMatcher.splitMatcher();
- assertThat(StrMatcher.splitMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 2)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 3)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 5)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 6)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 7)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 8)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 9)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 10)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testTrimMatcher() {
- final StrMatcher matcher = StrMatcher.trimMatcher();
- assertThat(StrMatcher.trimMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 2)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 3)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 5)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 6)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 7)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 8)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 9)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 10)).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testSingleQuoteMatcher() {
- final StrMatcher matcher = StrMatcher.singleQuoteMatcher();
- assertThat(StrMatcher.singleQuoteMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 10)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 11)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 12)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testDoubleQuoteMatcher() {
- final StrMatcher matcher = StrMatcher.doubleQuoteMatcher();
- assertThat(StrMatcher.doubleQuoteMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 11)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 12)).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testQuoteMatcher() {
- final StrMatcher matcher = StrMatcher.quoteMatcher();
- assertThat(StrMatcher.quoteMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 10)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 11)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER1, 12)).isEqualTo(1);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testNoneMatcher() {
- final StrMatcher matcher = StrMatcher.noneMatcher();
- assertThat(StrMatcher.noneMatcher()).isSameAs(matcher);
- assertThat(matcher.isMatch(BUFFER1, 0)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 1)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 2)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 3)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 5)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 6)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 7)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 8)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 9)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 10)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 11)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER1, 12)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testCharMatcher_char() {
- final StrMatcher matcher = StrMatcher.charMatcher('c');
- assertThat(matcher.isMatch(BUFFER2, 0)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 1)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 2)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 3)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 5)).isEqualTo(0);
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testCharSetMatcher_String() {
- final StrMatcher matcher = StrMatcher.charSetMatcher("ace");
- assertThat(matcher.isMatch(BUFFER2, 0)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 1)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 2)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 3)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 4)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 5)).isEqualTo(0);
- assertThat(StrMatcher.charSetMatcher("")).isSameAs(StrMatcher.noneMatcher());
- assertThat(StrMatcher.charSetMatcher((String) null)).isSameAs(StrMatcher.noneMatcher());
- assertThat(StrMatcher.charSetMatcher("a") instanceof StrMatcher.CharMatcher).isTrue();
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testCharSetMatcher_charArray() {
- final StrMatcher matcher = StrMatcher.charSetMatcher("ace".toCharArray());
- assertThat(matcher.isMatch(BUFFER2, 0)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 1)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 2)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 3)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 4)).isEqualTo(1);
- assertThat(matcher.isMatch(BUFFER2, 5)).isEqualTo(0);
- assertThat(StrMatcher.charSetMatcher(new char[0])).isSameAs(StrMatcher.noneMatcher());
- assertThat(StrMatcher.charSetMatcher((char[]) null)).isSameAs(StrMatcher.noneMatcher());
- assertThat(StrMatcher.charSetMatcher("a".toCharArray()) instanceof StrMatcher.CharMatcher).isTrue();
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testStringMatcher_String() {
- final StrMatcher matcher = StrMatcher.stringMatcher("bc");
- assertThat(matcher.isMatch(BUFFER2, 0)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 1)).isEqualTo(2);
- assertThat(matcher.isMatch(BUFFER2, 2)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 3)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 4)).isEqualTo(0);
- assertThat(matcher.isMatch(BUFFER2, 5)).isEqualTo(0);
- assertThat(StrMatcher.stringMatcher("")).isSameAs(StrMatcher.noneMatcher());
- assertThat(StrMatcher.stringMatcher((String) null)).isSameAs(StrMatcher.noneMatcher());
- }
-
- //-----------------------------------------------------------------------
- @Test
- public void testMatcherIndices() {
- // remember that the API contract is tight for the isMatch() method
- // all the onus is on the caller, so invalid inputs are not
- // the concern of StrMatcher, and are not bugs
- final StrMatcher matcher = StrMatcher.stringMatcher("bc");
- assertThat(matcher.isMatch(BUFFER2, 1, 1, BUFFER2.length)).isEqualTo(2);
- assertThat(matcher.isMatch(BUFFER2, 1, 0, 3)).isEqualTo(2);
- assertThat(matcher.isMatch(BUFFER2, 1, 0, 2)).isEqualTo(0);
- }
-
-}
diff --git a/src/test/java/org/apache/commons/text/StrSubstitutorTest.java b/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
deleted file mode 100644
index 760e6fccf2..0000000000
--- a/src/test/java/org/apache/commons/text/StrSubstitutorTest.java
+++ /dev/null
@@ -1,799 +0,0 @@
-/*
- * 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;
-
-import static org.assertj.core.api.Assertions.assertThatNullPointerException;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertSame;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.lang3.mutable.MutableObject;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-
-/**
- * Test class for {@link StrSubstitutor}.
- *
- * @deprecated This class will be removed in 2.0.
- */
-@Deprecated
-public class StrSubstitutorTest {
-
- private Map values;
-
- @BeforeEach
- public void setUp() throws Exception {
- values = new HashMap<>();
- values.put("animal", "quick brown fox");
- values.put("target", "lazy dog");
- }
-
- @AfterEach
- public void tearDown() throws Exception {
- values = null;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplaceSimple() {
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplaceSolo() {
- doTestReplace("quick brown fox", "${animal}", false);
- }
-
- /**
- * Tests replace with no variables.
- */
- @Test
- public void testReplaceNoVariables() {
- doTestNoReplace("The balloon arrived.");
- }
-
- /**
- * Tests replace with null.
- */
- @Test
- public void testReplaceNull() {
- doTestNoReplace(null);
- }
-
- /**
- * Tests replace with null.
- */
- @Test
- public void testReplaceEmpty() {
- doTestNoReplace("");
- }
-
- /**
- * Tests key replace changing map after initialization (not recommended).
- */
- @Test
- public void testReplaceChangedMap() {
- final StrSubstitutor sub = new StrSubstitutor(values);
- values.put("target", "moon");
- assertEquals("The quick brown fox jumps over the moon.",
- sub.replace("The ${animal} jumps over the ${target}."));
- }
-
- /**
- * Tests unknown key replace.
- */
- @Test
- public void testReplaceUnknownKey() {
- doTestReplace("The ${person} jumps over the lazy dog.", "The ${person} jumps over the ${target}.", true);
- doTestReplace("The ${person} jumps over the lazy dog. 1234567890.",
- "The ${person} jumps over the ${target}. ${undefined.number:-1234567890}.", true);
- }
-
- /**
- * Tests adjacent keys.
- */
- @Test
- public void testReplaceAdjacentAtStart() {
- values.put("code", "GBP");
- values.put("amount", "12.50");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged"));
- }
-
- /**
- * Tests adjacent keys.
- */
- @Test
- public void testReplaceAdjacentAtEnd() {
- values.put("code", "GBP");
- values.put("amount", "12.50");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}"));
- }
-
- /**
- * Tests simple recursive replace.
- */
- @Test
- public void testReplaceRecursive() {
- values.put("animal", "${critter}");
- values.put("target", "${pet}");
- values.put("pet", "${petCharacteristic} dog");
- values.put("petCharacteristic", "lazy");
- values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- values.put("critterSpeed", "quick");
- values.put("critterColor", "brown");
- values.put("critterType", "fox");
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
-
- values.put("pet", "${petCharacteristicUnknown:-lazy} dog");
- doTestReplace("The quick brown fox jumps over the lazy dog.", "The ${animal} jumps over the ${target}.", true);
- }
-
- @Test
- public void testDisableSubstitutionInValues() {
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setDisableSubstitutionInValues(true);
- values.put("animal", "${critter}");
- values.put("target", "${pet}");
- values.put("pet", "${petCharacteristic} dog");
- values.put("petCharacteristic", "lazy");
- values.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- values.put("critterSpeed", "quick");
- values.put("critterColor", "brown");
- values.put("critterType", "fox");
- doTestReplace(sub, "The ${critter} jumps over the ${pet}.", "The ${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests escaping.
- */
- @Test
- public void testReplaceEscaping() {
- doTestReplace("The ${animal} jumps over the lazy dog.", "The $${animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests escaping.
- */
- @Test
- public void testReplaceSoloEscaping() {
- doTestReplace("${animal}", "$${animal}", false);
- }
-
- /**
- * Tests complex escaping.
- */
- @Test
- public void testReplaceComplexEscaping() {
- doTestReplace("The ${quick brown fox} jumps over the lazy dog.",
- "The $${${animal}} jumps over the ${target}.", true);
- doTestReplace("The ${quick brown fox} jumps over the lazy dog. ${1234567890}.",
- "The $${${animal}} jumps over the ${target}. $${${undefined.number:-1234567890}}.", true);
- }
-
- /**
- * Tests when no prefix or suffix.
- */
- @Test
- public void testReplaceNoPrefixNoSuffix() {
- doTestReplace("The animal jumps over the lazy dog.", "The animal jumps over the ${target}.", true);
- }
-
- /**
- * Tests when no incomplete prefix.
- */
- @Test
- public void testReplaceIncompletePrefix() {
- doTestReplace("The {animal} jumps over the lazy dog.", "The {animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests when prefix but no suffix.
- */
- @Test
- public void testReplacePrefixNoSuffix() {
- doTestReplace("The ${animal jumps over the ${target} lazy dog.",
- "The ${animal jumps over the ${target} ${target}.", true);
- }
-
- /**
- * Tests when suffix but no prefix.
- */
- @Test
- public void testReplaceNoPrefixSuffix() {
- doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests when no variable name.
- */
- @Test
- public void testReplaceEmptyKeys() {
- doTestReplace("The ${} jumps over the lazy dog.", "The ${} jumps over the ${target}.", true);
- doTestReplace("The animal jumps over the lazy dog.", "The ${:-animal} jumps over the ${target}.", true);
- }
-
- /**
- * Tests replace creates output same as input.
- */
- @Test
- public void testReplaceToIdentical() {
- values.put("animal", "$${${thing}}");
- values.put("thing", "animal");
- doTestReplace("The ${animal} jumps.", "The ${animal} jumps.", true);
- }
-
- /**
- * Tests a cyclic replace operation.
- * The cycle should be detected and cause an exception to be thrown.
- */
- @Test
- public void testCyclicReplacement() {
- final Map map = new HashMap<>();
- map.put("animal", "${critter}");
- map.put("target", "${pet}");
- map.put("pet", "${petCharacteristic} dog");
- map.put("petCharacteristic", "lazy");
- map.put("critter", "${critterSpeed} ${critterColor} ${critterType}");
- map.put("critterSpeed", "quick");
- map.put("critterColor", "brown");
- map.put("critterType", "${animal}");
- StrSubstitutor sub = new StrSubstitutor(map);
- assertThrows(IllegalStateException.class, () -> sub.replace("The ${animal} jumps over the ${target}."));
-
- // also check even when default value is set.
- map.put("critterType", "${animal:-fox}");
- assertThrows(IllegalStateException.class,
- () -> new StrSubstitutor(map).replace("The ${animal} jumps over the ${target}."));
- }
-
- /**
- * Tests interpolation with weird boundary patterns.
- */
- @Test
- public void testReplaceWeirdPattens() {
- doTestNoReplace("");
- doTestNoReplace("${}");
- doTestNoReplace("${ }");
- doTestNoReplace("${\t}");
- doTestNoReplace("${\n}");
- doTestNoReplace("${\b}");
- doTestNoReplace("${");
- doTestNoReplace("$}");
- doTestNoReplace("}");
- doTestNoReplace("${}$");
- doTestNoReplace("${${");
- doTestNoReplace("${${}}");
- doTestNoReplace("${$${}}");
- doTestNoReplace("${$$${}}");
- doTestNoReplace("${$$${$}}");
- doTestNoReplace("${${}}");
- doTestNoReplace("${${ }}");
- }
-
- /**
- * Tests simple key replace.
- */
- @Test
- public void testReplacePartialString_noReplace() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15));
- }
-
- /**
- * Tests whether a variable can be replaced in a variable name.
- */
- @Test
- public void testReplaceInVariable() {
- values.put("animal.1", "fox");
- values.put("animal.2", "mouse");
- values.put("species", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setEnableSubstitutionInVariables(true);
- assertEquals(
- "The mouse jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- values.put("species", "1");
- assertEquals(
- "The fox jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals(
- "The fox jumps over the lazy dog.",
- sub.replace("The ${unknown.animal.${unknown.species:-1}:-fox} "
- + "jumps over the ${unknow.target:-lazy dog}."));
- }
-
- /**
- * Tests whether substitution in variable names is disabled per default.
- */
- @Test
- public void testReplaceInVariableDisabled() {
- values.put("animal.1", "fox");
- values.put("animal.2", "mouse");
- values.put("species", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- assertEquals(
- "The ${animal.${species}} jumps over the lazy dog.",
- sub.replace("The ${animal.${species}} jumps over the ${target}."));
- assertEquals(
- "The ${animal.${species:-1}} jumps over the lazy dog.",
- sub.replace("The ${animal.${species:-1}} jumps over the ${target}."));
- }
-
- /**
- * Tests complex and recursive substitution in variable names.
- */
- @Test
- public void testReplaceInVariableRecursive() {
- values.put("animal.2", "brown fox");
- values.put("animal.1", "white mouse");
- values.put("color", "white");
- values.put("species.white", "1");
- values.put("species.brown", "2");
- final StrSubstitutor sub = new StrSubstitutor(values);
- sub.setEnableSubstitutionInVariables(true);
- assertEquals(
- "The white mouse jumps over the lazy dog.",
- sub.replace("The ${animal.${species.${color}}} jumps over the ${target}."));
- assertEquals(
- "The brown fox jumps over the lazy dog.",
- sub.replace("The ${animal.${species.${unknownColor:-brown}}} jumps over the ${target}."));
- }
-
- @Test
- public void testDefaultValueDelimiters() {
- final Map map = new HashMap<>();
- map.put("animal", "fox");
- map.put("target", "dog");
-
- StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number:-1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "?:");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number?:1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "||");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number||1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "!");
- assertEquals("The fox jumps over the lazy dog. 1234567890.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$', "");
- sub.setValueDelimiterMatcher(null);
- assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
-
- sub = new StrSubstitutor(map, "${", "}", '$');
- sub.setValueDelimiterMatcher(null);
- assertEquals("The fox jumps over the lazy dog. ${undefined.number!1234567890}.",
- sub.replace("The ${animal} jumps over the lazy ${target}. ${undefined.number!1234567890}."));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests protected.
- */
- @Test
- public void testResolveVariable() {
- final StrBuilder builder = new StrBuilder("Hi ${name}!");
- final Map map = new HashMap<>();
- map.put("name", "commons");
- final StrSubstitutor sub = new StrSubstitutor(map) {
- @Override
- protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos,
- final int endPos) {
- assertEquals("name", variableName);
- assertSame(builder, buf);
- assertEquals(3, startPos);
- assertEquals(10, endPos);
- return "jakarta";
- }
- };
- sub.replaceIn(builder);
- assertEquals("Hi jakarta!", builder.toString());
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorNoArgs() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals("Hi ${name}", sub.replace("Hi ${name}"));
- }
-
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorMapPrefixSuffix() {
- final Map map = new HashMap<>();
- map.put("name", "commons");
- final StrSubstitutor sub = new StrSubstitutor(map, "<", ">");
- assertEquals("Hi < commons", sub.replace("Hi $< "));
- }
-
- /**
- * Tests constructor.
- */
- @Test
- public void testConstructorMapFull() {
- final Map map = new HashMap<>();
- map.put("name", "commons");
- StrSubstitutor sub = new StrSubstitutor(map, "<", ">", '!');
- assertEquals("Hi < commons", sub.replace("Hi !< "));
- sub = new StrSubstitutor(map, "<", ">", '!', "||");
- assertEquals("Hi < commons", sub.replace("Hi !< "));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetEscape() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertEquals('$', sub.getEscapeChar());
- sub.setEscapeChar('<');
- assertEquals('<', sub.getEscapeChar());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetPrefix() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
- sub.setVariablePrefix('<');
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setVariablePrefix("<<");
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
- assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefix((String) null));
- assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setVariablePrefixMatcher(matcher);
- assertSame(matcher, sub.getVariablePrefixMatcher());
- assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefixMatcher((StrMatcher) null));
- assertSame(matcher, sub.getVariablePrefixMatcher());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetSuffix() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
- sub.setVariableSuffix('<');
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setVariableSuffix("<<");
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
- assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffix((String) null));
- assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setVariableSuffixMatcher(matcher);
- assertSame(matcher, sub.getVariableSuffixMatcher());
- assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffixMatcher((StrMatcher) null));
- assertSame(matcher, sub.getVariableSuffixMatcher());
- }
-
- /**
- * Tests get set.
- */
- @Test
- public void testGetSetValueDelimiter() {
- final StrSubstitutor sub = new StrSubstitutor();
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
- sub.setValueDelimiter(':');
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.CharMatcher);
-
- sub.setValueDelimiter("||");
- assertTrue(sub.getValueDelimiterMatcher() instanceof StrMatcher.StringMatcher);
- sub.setValueDelimiter((String) null);
- assertNull(sub.getValueDelimiterMatcher());
-
- final StrMatcher matcher = StrMatcher.commaMatcher();
- sub.setValueDelimiterMatcher(matcher);
- assertSame(matcher, sub.getValueDelimiterMatcher());
- sub.setValueDelimiterMatcher((StrMatcher) null);
- assertNull(sub.getValueDelimiterMatcher());
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests static.
- */
- @Test
- public void testStaticReplace() {
- final Map map = new HashMap<>();
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map));
- }
-
- /**
- * Tests static.
- */
- @Test
- public void testStaticReplacePrefixSuffix() {
- final Map map = new HashMap<>();
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi !", map, "<", ">"));
- }
-
- /**
- * Tests interpolation with system properties.
- */
- @Test
- public void testStaticReplaceSystemProperties() {
- final StrBuilder buf = new StrBuilder();
- buf.append("Hi ").append(System.getProperty("user.name"));
- buf.append(", you are working with ");
- buf.append(System.getProperty("os.name"));
- buf.append(", your home directory is ");
- buf.append(System.getProperty("user.home")).append('.');
- assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are "
- + "working with ${os.name}, your home "
- + "directory is ${user.home}."));
- }
-
- /**
- * Test for LANG-1055: StrSubstitutor.replaceSystemProperties does not work consistently
- */
- @Test
- public void testLANG1055() {
- System.setProperty("test_key", "test_value");
-
- final String expected = StrSubstitutor.replace("test_key=${test_key}", System.getProperties());
- final String actual = StrSubstitutor.replaceSystemProperties("test_key=${test_key}");
- assertEquals(expected, actual);
- }
-
- /**
- * Test the replace of a properties object
- */
- @Test
- public void testSubstituteDefaultProperties() {
- final String org = "${doesnotwork}";
- System.setProperty("doesnotwork", "It works!");
-
- // create a new Properties object with the System.getProperties as default
- final Properties props = new Properties(System.getProperties());
-
- assertEquals("It works!", StrSubstitutor.replace(org, props));
- }
-
- @Test
- public void testSamePrefixAndSuffix() {
- final Map map = new HashMap<>();
- map.put("greeting", "Hello");
- map.put(" there ", "XXX");
- map.put("name", "commons");
- assertEquals("Hi commons!", StrSubstitutor.replace("Hi @name@!", map, "@", "@"));
- assertEquals("Hello there commons!", StrSubstitutor.replace("@greeting@ there @name@!", map, "@", "@"));
- }
-
- @Test
- public void testSubstitutePreserveEscape() {
- final String org = "${not-escaped} $${escaped}";
- final Map map = new HashMap<>();
- map.put("not-escaped", "value");
-
- final StrSubstitutor sub = new StrSubstitutor(map, "${", "}", '$');
- assertFalse(sub.isPreserveEscapes());
- assertEquals("value ${escaped}", sub.replace(org));
-
- sub.setPreserveEscapes(true);
- assertTrue(sub.isPreserveEscapes());
- assertEquals("value $${escaped}", sub.replace(org));
- }
-
- private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) {
- final StrSubstitutor sub = new StrSubstitutor(values);
- doTestReplace(sub, expectedResult, replaceTemplate, substring);
- }
-
- //-----------------------------------------------------------------------
- private void doTestReplace(final StrSubstitutor sub, final String expectedResult, final String replaceTemplate,
- final boolean substring) {
- final String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);
-
- // replace using String
- assertEquals(expectedResult, sub.replace(replaceTemplate));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(replaceTemplate, 1, replaceTemplate.length() - 2));
- }
-
- // replace using char[]
- final char[] chars = replaceTemplate.toCharArray();
- assertEquals(expectedResult, sub.replace(chars));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(chars, 1, chars.length - 2));
- }
-
- // replace using StringBuffer
- StringBuffer buf = new StringBuffer(replaceTemplate);
- assertEquals(expectedResult, sub.replace(buf));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(buf, 1, buf.length() - 2));
- }
-
- // replace using StringBuilder
- StringBuilder builder = new StringBuilder(replaceTemplate);
- assertEquals(expectedResult, sub.replace(builder));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(builder, 1, builder.length() - 2));
- }
-
- // replace using StrBuilder
- StrBuilder bld = new StrBuilder(replaceTemplate);
- assertEquals(expectedResult, sub.replace(bld));
- if (substring) {
- assertEquals(expectedShortResult, sub.replace(bld, 1, bld.length() - 2));
- }
-
- // replace using object
- final MutableObject obj = new MutableObject<>(replaceTemplate); // toString returns template
- assertEquals(expectedResult, sub.replace(obj));
-
- // replace in StringBuffer
- buf = new StringBuffer(replaceTemplate);
- assertTrue(sub.replaceIn(buf));
- assertEquals(expectedResult, buf.toString());
- if (substring) {
- buf = new StringBuffer(replaceTemplate);
- assertTrue(sub.replaceIn(buf, 1, buf.length() - 2));
- assertEquals(expectedResult, buf.toString()); // expect full result as remainder is untouched
- }
-
- // replace in StringBuilder
- builder = new StringBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(builder));
- assertEquals(expectedResult, builder.toString());
- if (substring) {
- builder = new StringBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(builder, 1, builder.length() - 2));
- assertEquals(expectedResult, builder.toString()); // expect full result as remainder is untouched
- }
-
- // replace in StrBuilder
- bld = new StrBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(bld));
- assertEquals(expectedResult, bld.toString());
- if (substring) {
- bld = new StrBuilder(replaceTemplate);
- assertTrue(sub.replaceIn(bld, 1, bld.length() - 2));
- assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched
- }
- }
-
- private void doTestNoReplace(final String replaceTemplate) {
- final StrSubstitutor sub = new StrSubstitutor(values);
-
- if (replaceTemplate == null) {
- assertNull(sub.replace((String) null));
- assertNull(sub.replace((String) null, 0, 100));
- assertNull(sub.replace((char[]) null));
- assertNull(sub.replace((char[]) null, 0, 100));
- assertNull(sub.replace((StringBuffer) null));
- assertNull(sub.replace((StringBuffer) null, 0, 100));
- assertNull(sub.replace((StrBuilder) null));
- assertNull(sub.replace((StrBuilder) null, 0, 100));
- assertNull(sub.replace((Object) null));
- assertFalse(sub.replaceIn((StringBuffer) null));
- assertFalse(sub.replaceIn((StringBuffer) null, 0, 100));
- assertFalse(sub.replaceIn((StrBuilder) null));
- assertFalse(sub.replaceIn((StrBuilder) null, 0, 100));
- } else {
- assertEquals(replaceTemplate, sub.replace(replaceTemplate));
- final StrBuilder bld = new StrBuilder(replaceTemplate);
- assertFalse(sub.replaceIn(bld));
- assertEquals(replaceTemplate, bld.toString());
- }
- }
-
- @Test
- public void testReplaceInTakingTwoAndThreeIntsReturningFalse() {
- final Map hashMap = new HashMap<>();
- final StrLookup.MapStrLookup