From 3685702e130590f2ec33a8e967989a041257d554 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Tue, 4 Dec 2018 23:41:33 +0200 Subject: [PATCH 01/13] Update for the custom built items --- pom.xml | 37 ++++++++++++--------------------- src/jre11/java/module-info.java | 8 +++++++ 2 files changed, 21 insertions(+), 24 deletions(-) create mode 100644 src/jre11/java/module-info.java diff --git a/pom.xml b/pom.xml index 3957a1dd9f..d529614b30 100644 --- a/pom.xml +++ b/pom.xml @@ -15,15 +15,16 @@ See the License for the specific language governing permissions and limitations under the License. --> + 4.0.0 - - org.apache.commons - commons-parent - 47 - + + com.jwebmp + jwebmp-parent + 0.0.0_0-SNAPSHOT + commons-text - 1.7-SNAPSHOT + Apache Commons Text Apache Commons Text is a library focused on algorithms working on strings. http://commons.apache.org/proper/commons-text @@ -31,8 +32,6 @@ ISO-8859-1 UTF-8 - 1.8 - 1.8 text org.apache.commons.text @@ -53,7 +52,7 @@ 8.14 3.1.8 - + 0.8.2 @@ -85,9 +84,9 @@ - org.apache.commons + com.jwebmp commons-lang3 - 3.8.1 + ${project.version} @@ -108,7 +107,6 @@ org.assertj assertj-core - 3.11.1 test @@ -444,27 +442,18 @@ - java9+ + jdk11 [9,) true + true - java11+ - - [11,) - - - - true - - - - java12+ + jdk12 [12,) diff --git a/src/jre11/java/module-info.java b/src/jre11/java/module-info.java new file mode 100644 index 0000000000..260efdce30 --- /dev/null +++ b/src/jre11/java/module-info.java @@ -0,0 +1,8 @@ +module org.apache.commons.text { + exports org.apache.commons.text; + requires org.apache.commons.lang3; + + requires static java.xml; + requires static java.scripting; + +} From 59876066250a3649a3fa51b5c6f63fa84ae77e9c Mon Sep 17 00:00:00 2001 From: GedMarc Date: Mon, 10 Dec 2018 13:38:05 +0200 Subject: [PATCH 02/13] Build updates for guice and faster xml --- pom.xml | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/pom.xml b/pom.xml index d529614b30..8ea73a1d80 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 4.0.0 com.jwebmp - jwebmp-parent + jwebmp-builder 0.0.0_0-SNAPSHOT commons-text @@ -193,15 +193,6 @@ - - org.apache.maven.plugins - maven-scm-publish-plugin - - - javadocs - - - From c0bb0f25f6620b93990ef45f6936ba0f8eb6af40 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Tue, 11 Dec 2018 22:40:46 +0200 Subject: [PATCH 03/13] Switch to compiler maven builds for OSGi --- pom.xml | 41 ----------------------------------------- 1 file changed, 41 deletions(-) diff --git a/pom.xml b/pom.xml index 8ea73a1d80..d7ba9ed02d 100644 --- a/pom.xml +++ b/pom.xml @@ -391,47 +391,6 @@ - - setup-checkout - - - site-content - - - - - - org.apache.maven.plugins - maven-antrun-plugin - - - prepare-checkout - - run - - pre-site - - - - - - - - - - - - - - - - - - - - - - jdk11 From 95701761fbf89c22670f2df02ef8e9dd276c3164 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 23 Dec 2018 03:29:38 +0200 Subject: [PATCH 04/13] Remove tests from third party libraries --- .../commons/text/AlphabetConverterTest.java | 316 --- .../apache/commons/text/CaseUtilsTest.java | 79 - .../commons/text/CharacterPredicatesTest.java | 113 - .../commons/text/CompositeFormatTest.java | 87 - .../text/ExtendedMessageFormatTest.java | 579 ----- .../commons/text/FormattableUtilsTest.java | 171 -- .../text/RandomStringGeneratorTest.java | 301 --- .../text/StrBuilderAppendInsertTest.java | 1477 ------------ .../apache/commons/text/StrBuilderTest.java | 2052 ---------------- .../apache/commons/text/StrLookupTest.java | 134 -- .../apache/commons/text/StrMatcherTest.java | 215 -- .../commons/text/StrSubstitutorTest.java | 799 ------- .../apache/commons/text/StrTokenizerTest.java | 935 -------- .../commons/text/StringEscapeUtilsTest.java | 639 ----- .../commons/text/StringSubstitutorTest.java | 677 ------ ...tutorWithInterpolatorStringLookupTest.java | 101 - .../commons/text/StringTokenizerTest.java | 934 -------- .../TextStringBuilderAppendInsertTest.java | 1502 ------------ .../commons/text/TextStringBuilderTest.java | 2053 ----------------- .../apache/commons/text/WordUtilsTest.java | 542 ----- .../text/diff/ReplacementsFinderTest.java | 98 - .../text/diff/StringsComparatorTest.java | 132 -- .../lookup/Base64DecoderStringLookupTest.java | 38 - .../lookup/Base64EncoderStringLookupTest.java | 38 - .../lookup/ConstantStringLookupBasicTest.java | 61 - .../text/lookup/ConstantStringLookupTest.java | 142 -- .../text/lookup/DateStringLookupTest.java | 53 - .../text/lookup/DefaultStringLookupTest.java | 70 - .../EnvironmentVariableStringLookupTest.java | 45 - .../text/lookup/FileStringLookupTest.java | 60 - .../lookup/InterpolatorStringLookupTest.java | 112 - .../lookup/JavaPlatformStringLookupTest.java | 55 - .../lookup/LocalHostStringLookupTest.java | 54 - .../text/lookup/MapStringLookupTest.java | 51 - .../text/lookup/NullStringLookupTest.java | 33 - .../lookup/PropertiesStringLookupTest.java | 89 - .../ResourceBundleStringLookupTest.java | 82 - .../text/lookup/ScriptStringLookupTest.java | 61 - .../text/lookup/StringLookupFactoryTest.java | 87 - .../SystemPropertyStringLookupTest.java | 39 - .../lookup/UrlDecoderStringLookupTest.java | 48 - .../lookup/UrlEncoderStringLookupTest.java | 39 - .../text/lookup/UrlStringLookupTest.java | 70 - .../text/lookup/XmlStringLookupTest.java | 40 - .../text/matcher/StringMatcherTest.java | 219 -- .../matcher/StringSubstitutorGetSetTest.java | 99 - .../text/similarity/CosineDistanceTest.java | 71 - .../text/similarity/CosineSimilarityTest.java | 67 - .../text/similarity/FuzzyScoreTest.java | 81 - .../text/similarity/HammingDistanceTest.java | 63 - .../text/similarity/JaccardDistanceTest.java | 76 - .../similarity/JaccardSimilarityTest.java | 76 - .../similarity/JaroWinklerDistanceTest.java | 73 - .../LevenshteinDetailedDistanceTest.java | 462 ---- .../similarity/LevenshteinDistanceTest.java | 144 -- .../similarity/LevenshteinResultsTest.java | 71 - .../LongestCommonSubsequenceDistanceTest.java | 69 - .../LongestCommonSubsequenceTest.java | 140 -- .../ParameterizedEditDistanceFromTest.java | 69 - .../ParameterizedLevenshteinDistanceTest.java | 104 - .../ParameterizedSimilarityScoreFromTest.java | 60 - .../similarity/SimilarityScoreFromTest.java | 41 - .../text/similarity/StringMetricFromTest.java | 66 - .../translate/AggregateTranslatorTest.java | 66 - .../translate/CodePointTranslatorTest.java | 40 - .../text/translate/CsvTranslatorsTest.java | 130 -- .../text/translate/EntityArraysTest.java | 132 -- .../translate/JavaUnicodeEscaperTest.java | 69 - .../text/translate/LookupTranslatorTest.java | 64 - .../translate/NumericEntityEscaperTest.java | 68 - .../translate/NumericEntityUnescaperTest.java | 98 - .../text/translate/OctalUnescaperTest.java | 83 - .../translate/SinglePassTranslatorTest.java | 64 - .../text/translate/UnicodeEscaperTest.java | 58 - .../text/translate/UnicodeUnescaperTest.java | 55 - .../UnicodeUnpairedSurrogateRemoverTest.java | 47 - 76 files changed, 18328 deletions(-) delete mode 100644 src/test/java/org/apache/commons/text/AlphabetConverterTest.java delete mode 100644 src/test/java/org/apache/commons/text/CaseUtilsTest.java delete mode 100644 src/test/java/org/apache/commons/text/CharacterPredicatesTest.java delete mode 100644 src/test/java/org/apache/commons/text/CompositeFormatTest.java delete mode 100644 src/test/java/org/apache/commons/text/ExtendedMessageFormatTest.java delete mode 100644 src/test/java/org/apache/commons/text/FormattableUtilsTest.java delete mode 100644 src/test/java/org/apache/commons/text/RandomStringGeneratorTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrBuilderAppendInsertTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrBuilderTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrMatcherTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrSubstitutorTest.java delete mode 100644 src/test/java/org/apache/commons/text/StrTokenizerTest.java delete mode 100644 src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java delete mode 100644 src/test/java/org/apache/commons/text/StringSubstitutorTest.java delete mode 100644 src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/StringTokenizerTest.java delete mode 100644 src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java delete mode 100644 src/test/java/org/apache/commons/text/TextStringBuilderTest.java delete mode 100644 src/test/java/org/apache/commons/text/WordUtilsTest.java delete mode 100644 src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java delete mode 100644 src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/Base64DecoderStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/Base64EncoderStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/ConstantStringLookupBasicTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/ConstantStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/DefaultStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/FileStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/PropertiesStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/ScriptStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/StringLookupFactoryTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/UrlDecoderStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/UrlEncoderStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/UrlStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/lookup/XmlStringLookupTest.java delete mode 100644 src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java delete mode 100644 src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java delete mode 100644 src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/EntityArraysTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java delete mode 100644 src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java 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 strLookupMapStrLookup = new StrLookup.MapStrLookup<>(hashMap); - final StrMatcher strMatcher = StrMatcher.tabMatcher(); - final StrSubstitutor strSubstitutor = - new StrSubstitutor(strLookupMapStrLookup, strMatcher, strMatcher, 'b', strMatcher); - - assertFalse(strSubstitutor.replaceIn((StringBuilder) null, 1315, (-1369))); - assertEquals('b', strSubstitutor.getEscapeChar()); - assertFalse(strSubstitutor.isPreserveEscapes()); - } - - @Test - public void testReplaceInTakingStringBuilderWithNonNull() { - final StrLookup strLookup = StrLookup.systemPropertiesLookup(); - final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookup, "b(), "WV@i#y?N*[", "WV@i#y?N*[", '*'); - - assertFalse(strSubstitutor.isPreserveEscapes()); - assertFalse(strSubstitutor.replaceIn(new StringBuffer("WV@i#y?N*["))); - assertEquals('*', strSubstitutor.getEscapeChar()); - } - - @Test - public void testCreatesStrSubstitutorTakingStrLookupAndCallsReplaceTakingTwoAndThreeInts() { - final Map map = new HashMap<>(); - final StrLookup.MapStrLookup strLookupMapStrLookup = new StrLookup.MapStrLookup<>(map); - final StrSubstitutor strSubstitutor = new StrSubstitutor(strLookupMapStrLookup); - - assertNull(strSubstitutor.replace((CharSequence) null, 0, 0)); - assertEquals('$', strSubstitutor.getEscapeChar()); - } - - @Test - public void testReplaceTakingCharSequenceReturningNull() { - final StrSubstitutor strSubstitutor = new StrSubstitutor((StrLookup) null); - - assertNull(strSubstitutor.replace((CharSequence) null)); - assertFalse(strSubstitutor.isPreserveEscapes()); - assertEquals('$', strSubstitutor.getEscapeChar()); - } - - @Test - public void testReplaceTakingThreeArgumentsThrowsNullPointerException() { - assertThatNullPointerException().isThrownBy(() -> StrSubstitutor.replace(null, (Properties) null)); - } - - @Test - public void testReplaceInTakingStringBuilderWithNull() { - final Map map = new HashMap<>(); - final StrSubstitutor strSubstitutor = new StrSubstitutor(map, "", "", 'T', "K+<'f"); - - assertFalse(strSubstitutor.replaceIn((StringBuilder) null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/StrTokenizerTest.java b/src/test/java/org/apache/commons/text/StrTokenizerTest.java deleted file mode 100644 index cf40b00b70..0000000000 --- a/src/test/java/org/apache/commons/text/StrTokenizerTest.java +++ /dev/null @@ -1,935 +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.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; - -import org.junit.jupiter.api.Test; - -/** - * Unit test for {@link StrTokenizer}. - * - * @deprecated This class will be removed in 2.0. - */ -@Deprecated -public class StrTokenizerTest { - - private static final String CSV_SIMPLE_FIXTURE = "A,b,c"; - - private static final String TSV_SIMPLE_FIXTURE = "A\tb\tc"; - - private void checkClone(final StrTokenizer tokenizer) { - assertFalse(StrTokenizer.getCSVInstance() == tokenizer); - assertFalse(StrTokenizer.getTSVInstance() == tokenizer); - } - - // ----------------------------------------------------------------------- - @Test - public void test1() { - - final String input = "a;b;c;\"d;\"\"e\";f; ; ; "; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f", "", "", ""}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test2() { - - final String input = "a;b;c ;\"d;\"\"e\";f; ; ;"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c ", "d;\"e", "f", " ", " ", ""}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test3() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", " c", "d;\"e", "f", " ", " ", ""}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test4() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f"}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test5() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f", null, null, null}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test6() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - // tok.setTreatingEmptyAsNull(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", " c", "d;\"e", "f", null, null, null}; - - int nextCount = 0; - while (tok.hasNext()) { - tok.next(); - nextCount++; - } - - int prevCount = 0; - while (tok.hasPrevious()) { - tok.previous(); - prevCount++; - } - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - assertTrue(nextCount == expected.length, - "could not cycle through entire token list using the 'hasNext' and 'next' methods"); - assertTrue(prevCount == expected.length, - "could not cycle through entire token list using the 'hasPrevious' and 'previous' methods"); - } - - @Test - public void test7() { - - final String input = "a b c \"d e\" f "; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterMatcher(StrMatcher.spaceMatcher()); - tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); - tok.setIgnoredMatcher(StrMatcher.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "", "", "b", "c", "d e", "f", ""}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test8() { - - final String input = "a b c \"d e\" f "; - final StrTokenizer tok = new StrTokenizer(input); - tok.setDelimiterMatcher(StrMatcher.spaceMatcher()); - tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher()); - tok.setIgnoredMatcher(StrMatcher.noneMatcher()); - tok.setIgnoreEmptyTokens(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d e", "f"}; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void testBasic1() { - final String input = "a b c"; - final StrTokenizer tok = new StrTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic2() { - final String input = "a \nb\fc"; - final StrTokenizer tok = new StrTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic3() { - final String input = "a \nb\u0001\fc"; - final StrTokenizer tok = new StrTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b\u0001", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic4() { - final String input = "a \"b\" c"; - final StrTokenizer tok = new StrTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("\"b\"", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic5() { - final String input = "a:b':c"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - assertEquals("a", tok.next()); - assertEquals("b'", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicDelim1() { - final String input = "a:b:c"; - final StrTokenizer tok = new StrTokenizer(input, ':'); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicDelim2() { - final String input = "a:b:c"; - final StrTokenizer tok = new StrTokenizer(input, ','); - assertEquals("a:b:c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimString() { - final String input = "a##b##c"; - final StrTokenizer tok = new StrTokenizer(input, "##"); - - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimMatcher() { - final String input = "a/b\\c"; - final StrMatcher delimMatcher = new StrMatcher.CharSetMatcher(new char[] {'/', '\\'}); - - final StrTokenizer tok = new StrTokenizer(input, delimMatcher); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimMatcherQuoteMatcher() { - final String input = "`a`;`b`;`c`"; - final StrMatcher delimMatcher = new StrMatcher.CharSetMatcher(new char[] {';'}); - final StrMatcher quoteMatcher = new StrMatcher.CharSetMatcher(new char[] {'`'}); - - final StrTokenizer tok = new StrTokenizer(input, delimMatcher, quoteMatcher); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicEmpty1() { - final String input = "a b c"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setIgnoreEmptyTokens(false); - assertEquals("a", tok.next()); - assertEquals("", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicEmpty2() { - final String input = "a b c"; - final StrTokenizer tok = new StrTokenizer(input); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertNull(tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted1() { - final String input = "a 'b' c"; - final StrTokenizer tok = new StrTokenizer(input, ' ', '\''); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted2() { - final String input = "a:'b':"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted3() { - final String input = "a:'b''c'"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b'c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted4() { - final String input = "a: 'b' 'c' :d"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b c", tok.next()); - assertEquals("d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted5() { - final String input = "a: 'b'x'c' :d"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bxc", tok.next()); - assertEquals("d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted6() { - final String input = "a:'b'\"c':d"; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setQuoteMatcher(StrMatcher.quoteMatcher()); - assertEquals("a", tok.next()); - assertEquals("b\"c:d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted7() { - final String input = "a:\"There's a reason here\":b"; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setQuoteMatcher(StrMatcher.quoteMatcher()); - assertEquals("a", tok.next()); - assertEquals("There's a reason here", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuotedTrimmed1() { - final String input = "a: 'b' :"; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicTrimmed1() { - final String input = "a: b : "; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicTrimmed2() { - final String input = "a: b :"; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setTrimmerMatcher(StrMatcher.stringMatcher(" ")); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed1() { - final String input = "a: bIGNOREc : "; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bc", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed2() { - final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bc", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed3() { - final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; - final StrTokenizer tok = new StrTokenizer(input, ':'); - tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals(" bc ", tok.next()); - assertEquals(" ", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed4() { - final String input = "IGNOREaIGNORE: IGNORE 'bIGNOREc'IGNORE'd' IGNORE : IGNORE "; - final StrTokenizer tok = new StrTokenizer(input, ':', '\''); - tok.setIgnoredMatcher(StrMatcher.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StrMatcher.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bIGNOREcd", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testListArray() { - final String input = "a b c"; - final StrTokenizer tok = new StrTokenizer(input); - final String[] array = tok.getTokenArray(); - final List list = tok.getTokenList(); - - assertEquals(Arrays.asList(array), list); - assertEquals(3, list.size()); - } - - // ----------------------------------------------------------------------- - private void testCSV(final String data) { - this.testXSVAbc(StrTokenizer.getCSVInstance(data)); - this.testXSVAbc(StrTokenizer.getCSVInstance(data.toCharArray())); - } - - @Test - public void testCSVEmpty() { - this.testEmpty(StrTokenizer.getCSVInstance()); - this.testEmpty(StrTokenizer.getCSVInstance("")); - } - - @Test - public void testCSVSimple() { - this.testCSV(CSV_SIMPLE_FIXTURE); - } - - @Test - public void testCSVSimpleNeedsTrim() { - this.testCSV(" " + CSV_SIMPLE_FIXTURE); - this.testCSV(" \n\t " + CSV_SIMPLE_FIXTURE); - this.testCSV(" \n " + CSV_SIMPLE_FIXTURE + "\n\n\r"); - } - - void testEmpty(final StrTokenizer tokenizer) { - this.checkClone(tokenizer); - assertFalse(tokenizer.hasNext()); - assertFalse(tokenizer.hasPrevious()); - assertNull(tokenizer.nextToken()); - assertEquals(0, tokenizer.size()); - assertThrows(NoSuchElementException.class, () -> tokenizer.next()); - } - - @Test - public void testGetContent() { - final String input = "a b c \"d e\" f "; - StrTokenizer tok = new StrTokenizer(input); - assertEquals(input, tok.getContent()); - - tok = new StrTokenizer(input.toCharArray()); - assertEquals(input, tok.getContent()); - - tok = new StrTokenizer(); - assertNull(tok.getContent()); - } - - // ----------------------------------------------------------------------- - @Test - public void testChaining() { - final StrTokenizer tok = new StrTokenizer(); - assertEquals(tok, tok.reset()); - assertEquals(tok, tok.reset("")); - assertEquals(tok, tok.reset(new char[0])); - assertEquals(tok, tok.setDelimiterChar(' ')); - assertEquals(tok, tok.setDelimiterString(" ")); - assertEquals(tok, tok.setDelimiterMatcher(null)); - assertEquals(tok, tok.setQuoteChar(' ')); - assertEquals(tok, tok.setQuoteMatcher(null)); - assertEquals(tok, tok.setIgnoredChar(' ')); - assertEquals(tok, tok.setIgnoredMatcher(null)); - assertEquals(tok, tok.setTrimmerMatcher(null)); - assertEquals(tok, tok.setEmptyTokenAsNull(false)); - assertEquals(tok, tok.setIgnoreEmptyTokens(false)); - } - - /** - * Tests that the {@link StrTokenizer#clone()} clone method catches - * {@link CloneNotSupportedException} and returns null. - */ - @Test - public void testCloneNotSupportedException() { - final Object notCloned = new StrTokenizer() { - - @Override - Object cloneReset() throws CloneNotSupportedException { - throw new CloneNotSupportedException("test"); - } - }.clone(); - assertNull(notCloned); - } - - @Test - public void testCloneNull() { - final StrTokenizer tokenizer = new StrTokenizer((char[]) null); - // Start sanity check - assertNull(tokenizer.nextToken()); - tokenizer.reset(); - assertNull(tokenizer.nextToken()); - // End sanity check - final StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone(); - tokenizer.reset(); - assertNull(tokenizer.nextToken()); - assertNull(clonedTokenizer.nextToken()); - } - - @Test - public void testCloneReset() { - final char[] input = new char[] {'a'}; - final StrTokenizer tokenizer = new StrTokenizer(input); - // Start sanity check - assertEquals("a", tokenizer.nextToken()); - tokenizer.reset(input); - assertEquals("a", tokenizer.nextToken()); - // End sanity check - final StrTokenizer clonedTokenizer = (StrTokenizer) tokenizer.clone(); - input[0] = 'b'; - tokenizer.reset(input); - assertEquals("b", tokenizer.nextToken()); - assertEquals("a", clonedTokenizer.nextToken()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String() { - StrTokenizer tok = new StrTokenizer("a b"); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer(""); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((String) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String_char() { - StrTokenizer tok = new StrTokenizer("a b", ' '); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer("", ' '); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((String) null, ' '); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String_char_char() { - StrTokenizer tok = new StrTokenizer("a b", ' ', '"'); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer("", ' ', '"'); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((String) null, ' ', '"'); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray() { - StrTokenizer tok = new StrTokenizer("a b".toCharArray()); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer(new char[0]); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((char[]) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray_char() { - StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' '); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer(new char[0], ' '); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((char[]) null, ' '); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray_char_char() { - StrTokenizer tok = new StrTokenizer("a b".toCharArray(), ' ', '"'); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer(new char[0], ' ', '"'); - assertFalse(tok.hasNext()); - - tok = new StrTokenizer((char[]) null, ' ', '"'); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset() { - final StrTokenizer tok = new StrTokenizer("a b c"); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset(); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset_String() { - final StrTokenizer tok = new StrTokenizer("x x x"); - tok.reset("d e"); - assertEquals("d", tok.next()); - assertEquals("e", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset((String) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset_charArray() { - final StrTokenizer tok = new StrTokenizer("x x x"); - - final char[] array = new char[] {'a', 'b', 'c'}; - tok.reset(array); - assertEquals("abc", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset((char[]) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTSV() { - this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE)); - this.testXSVAbc(StrTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE.toCharArray())); - } - - @Test - public void testTSVEmpty() { - this.testEmpty(StrTokenizer.getTSVInstance()); - this.testEmpty(StrTokenizer.getTSVInstance("")); - } - - void testXSVAbc(final StrTokenizer tokenizer) { - this.checkClone(tokenizer); - assertEquals(-1, tokenizer.previousIndex()); - assertEquals(0, tokenizer.nextIndex()); - assertNull(tokenizer.previousToken()); - assertEquals("A", tokenizer.nextToken()); - assertEquals(1, tokenizer.nextIndex()); - assertEquals("b", tokenizer.nextToken()); - assertEquals(2, tokenizer.nextIndex()); - assertEquals("c", tokenizer.nextToken()); - assertEquals(3, tokenizer.nextIndex()); - assertNull(tokenizer.nextToken()); - assertEquals(3, tokenizer.nextIndex()); - assertEquals("c", tokenizer.previousToken()); - assertEquals(2, tokenizer.nextIndex()); - assertEquals("b", tokenizer.previousToken()); - assertEquals(1, tokenizer.nextIndex()); - assertEquals("A", tokenizer.previousToken()); - assertEquals(0, tokenizer.nextIndex()); - assertNull(tokenizer.previousToken()); - assertEquals(0, tokenizer.nextIndex()); - assertEquals(-1, tokenizer.previousIndex()); - assertEquals(3, tokenizer.size()); - } - - @Test - public void testIteration() { - final StrTokenizer tkn = new StrTokenizer("a b c"); - assertFalse(tkn.hasPrevious()); - assertThrows(NoSuchElementException.class, () -> tkn.previous()); - assertTrue(tkn.hasNext()); - - assertEquals("a", tkn.next()); - assertThrows(UnsupportedOperationException.class, () -> tkn.remove()); - assertThrows(UnsupportedOperationException.class, () -> tkn.set("x")); - assertThrows(UnsupportedOperationException.class, () -> tkn.add("y")); - assertTrue(tkn.hasPrevious()); - assertTrue(tkn.hasNext()); - - assertEquals("b", tkn.next()); - assertTrue(tkn.hasPrevious()); - assertTrue(tkn.hasNext()); - - assertEquals("c", tkn.next()); - assertTrue(tkn.hasPrevious()); - assertFalse(tkn.hasNext()); - - assertThrows(NoSuchElementException.class, () -> tkn.next()); - assertTrue(tkn.hasPrevious()); - assertFalse(tkn.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTokenizeSubclassInputChange() { - final StrTokenizer tkn = new StrTokenizer("a b c d e") { - - @Override - protected List tokenize(final char[] chars, final int offset, final int count) { - return super.tokenize("w x y z".toCharArray(), 2, 5); - } - }; - assertEquals("x", tkn.next()); - assertEquals("y", tkn.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTokenizeSubclassOutputChange() { - final StrTokenizer tkn = new StrTokenizer("a b c") { - - @Override - protected List tokenize(final char[] chars, final int offset, final int count) { - final List list = super.tokenize(chars, offset, count); - Collections.reverse(list); - return list; - } - }; - assertEquals("c", tkn.next()); - assertEquals("b", tkn.next()); - assertEquals("a", tkn.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testToString() { - final StrTokenizer tkn = new StrTokenizer("a b c d e"); - assertEquals("StrTokenizer[not tokenized yet]", tkn.toString()); - tkn.next(); - assertEquals("StrTokenizer[a, b, c, d, e]", tkn.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerStringMatcher() { - final char[] chars = {'a', 'b', 'c', 'd'}; - final StrTokenizer tokens = new StrTokenizer(chars, "bc"); - assertEquals("a", tokens.next()); - assertEquals("d", tokens.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerStrMatcher() { - final char[] chars = {'a', ',', 'c'}; - final StrTokenizer tokens = new StrTokenizer(chars, StrMatcher.commaMatcher()); - assertEquals("a", tokens.next()); - assertEquals("c", tokens.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerQuoteMatcher() { - final char[] chars = {'\'', 'a', 'c', '\'', 'd'}; - final StrTokenizer tokens = new StrTokenizer(chars, StrMatcher.commaMatcher(), StrMatcher.quoteMatcher()); - assertEquals("acd", tokens.next()); - } - - @Test - public void testPreviousTokenAndSetEmptyTokenAsNull() { - final StrTokenizer strTokenizer = StrTokenizer.getTSVInstance(" \t\n\r\f"); - strTokenizer.setEmptyTokenAsNull(true); - - assertNull(strTokenizer.previousToken()); - } -} diff --git a/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java b/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java deleted file mode 100644 index 16209f283f..0000000000 --- a/src/test/java/org/apache/commons/text/StringEscapeUtilsTest.java +++ /dev/null @@ -1,639 +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.apache.commons.text.StringEscapeUtils.escapeXSI; -import static org.apache.commons.text.StringEscapeUtils.unescapeXSI; -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.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - -import java.io.IOException; -import java.io.StringWriter; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link StringEscapeUtils}. - * - *

- * This code has been adapted from Apache Commons Lang 3.5. - *

- * - */ -public class StringEscapeUtilsTest { - private static final String FOO = "foo"; - - @Test - public void testConstructor() { - assertNotNull(new StringEscapeUtils()); - final Constructor[] cons = StringEscapeUtils.class.getDeclaredConstructors(); - assertEquals(1, cons.length); - assertTrue(Modifier.isPublic(cons[0].getModifiers())); - assertTrue(Modifier.isPublic(StringEscapeUtils.class.getModifiers())); - assertFalse(Modifier.isFinal(StringEscapeUtils.class.getModifiers())); - } - - @Test - public void testEscapeJava() throws IOException { - assertNull(StringEscapeUtils.escapeJava(null)); - try { - StringEscapeUtils.ESCAPE_JAVA.translate(null, null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - try { - StringEscapeUtils.ESCAPE_JAVA.translate("", null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - - assertEscapeJava("", "", "empty string"); - assertEscapeJava(FOO, FOO); - assertEscapeJava("\\t", "\t", "tab"); - assertEscapeJava("\\\\", "\\", "backslash"); - assertEscapeJava("'", "'", "single quote should not be escaped"); - assertEscapeJava("\\\\\\b\\t\\r", "\\\b\t\r"); - assertEscapeJava("\\u1234", "\u1234"); - assertEscapeJava("\\u0234", "\u0234"); - assertEscapeJava("\\u00EF", "\u00ef"); - assertEscapeJava("\\u0001", "\u0001"); - assertEscapeJava("\\uABCD", "\uabcd", "Should use capitalized Unicode hex"); - - assertEscapeJava("He didn't say, \\\"stop!\\\"", - "He didn't say, \"stop!\""); - assertEscapeJava("This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0", - "non-breaking space"); - assertEscapeJava("\\uABCD\\u1234\\u012C", - "\uABCD\u1234\u012C"); - } - - /** - * Tests https://issues.apache.org/jira/browse/LANG-421 - */ - @Test - public void testEscapeJavaWithSlash() { - final String input = "String with a slash (/) in it"; - - final String expected = input; - final String actual = StringEscapeUtils.escapeJava(input); - - /** - * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character - * to escape in a Java string. - */ - assertEquals(expected, actual); - } - - private void assertEscapeJava(final String escaped, final String original) throws IOException { - assertEscapeJava(escaped, original, null); - } - - private void assertEscapeJava(final String expected, final String original, String message) throws IOException { - final String converted = StringEscapeUtils.escapeJava(original); - message = "escapeJava(String) failed" + (message == null ? "" : (": " + message)); - assertEquals(expected, converted, message); - - final StringWriter writer = new StringWriter(); - StringEscapeUtils.ESCAPE_JAVA.translate(original, writer); - assertEquals(expected, writer.toString()); - } - - @Test - public void testUnescapeJava() throws IOException { - assertNull(StringEscapeUtils.unescapeJava(null)); - try { - StringEscapeUtils.UNESCAPE_JAVA.translate(null, null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - try { - StringEscapeUtils.UNESCAPE_JAVA.translate("", null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - assertThrows(RuntimeException.class, () -> StringEscapeUtils.unescapeJava("\\u02-3")); - - assertUnescapeJava("", ""); - assertUnescapeJava("test", "test"); - assertUnescapeJava("\ntest\b", "\\ntest\\b"); - assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); - assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); - assertUnescapeJava("", "\\"); - //foo - assertUnescapeJava("\uABCDx", "\\uabcdx", "lowercase Unicode"); - assertUnescapeJava("\uABCDx", "\\uABCDx", "uppercase Unicode"); - assertUnescapeJava("\uABCD", "\\uabcd", "Unicode as final character"); - } - - private void assertUnescapeJava(final String unescaped, final String original) throws IOException { - assertUnescapeJava(unescaped, original, null); - } - - private void assertUnescapeJava(final String unescaped, final String original, final String message) - throws IOException { - final String expected = unescaped; - final String actual = StringEscapeUtils.unescapeJava(original); - - assertEquals(expected, actual, "unescape(String) failed" - + (message == null ? "" : (": " + message)) - + ": expected '" + StringEscapeUtils.escapeJava(expected) - // we escape this so we can see it in the error message - + "' actual '" + StringEscapeUtils.escapeJava(actual) + "'"); - - final StringWriter writer = new StringWriter(); - StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer); - assertEquals(unescaped, writer.toString()); - } - - @Test - public void testEscapeEcmaScript() { - assertNull(StringEscapeUtils.escapeEcmaScript(null)); - try { - StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - try { - StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - - assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\"")); - assertEquals("document.getElementById(\\\"test\\\").value = \\'';")); - } - - - // HTML and XML - //-------------------------------------------------------------- - - private static final String[][] HTML_ESCAPES = { - {"no escaping", "plain text", "plain text"}, - {"no escaping", "plain text", "plain text"}, - {"empty string", "", ""}, - {"null", null, null}, - {"ampersand", "bread & butter", "bread & butter"}, - {"quotes", ""bread" & butter", "\"bread\" & butter"}, - {"final character only", "greater than >", "greater than >"}, - {"first character only", "< less than", "< less than"}, - {"apostrophe", "Huntington's chorea", "Huntington's chorea"}, - {"languages", "English,Français,\u65E5\u672C\u8A9E (nihongo)", - "English,Fran\u00E7ais,\u65E5\u672C\u8A9E (nihongo)"}, - {"8-bit ascii shouldn't number-escape", "\u0080\u009F", "\u0080\u009F"}, - }; - - @Test - public void testEscapeHtml3() { - for (final String[] element : HTML_ESCAPES) { - final String message = element[0]; - final String expected = element[1]; - final String original = element[2]; - assertEquals(expected, StringEscapeUtils.escapeHtml4(original), message); - final StringWriter sw = new StringWriter(); - try { - StringEscapeUtils.ESCAPE_HTML3.translate(original, sw); - } catch (final IOException e) { - } - final String actual = original == null ? null : sw.toString(); - assertEquals(expected, actual, message); - } - } - - @Test - public void testUnescapeHtml3() { - for (final String[] element : HTML_ESCAPES) { - final String message = element[0]; - final String expected = element[2]; - final String original = element[1]; - assertEquals(expected, StringEscapeUtils.unescapeHtml3(original), message); - - final StringWriter sw = new StringWriter(); - try { - StringEscapeUtils.UNESCAPE_HTML3.translate(original, sw); - } catch (final IOException e) { - } - final String actual = original == null ? null : sw.toString(); - assertEquals(expected, actual, message); - } - // \u00E7 is a cedilla (c with wiggle under) - // note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly - // on some locales - assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml3("Fran\u00E7ais"), "funny chars pass through OK"); - - assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml3("Hello&;World")); - assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml3("Hello&#;World")); - assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml3("Hello&# ;World")); - assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml3("Hello&##;World")); - } - -@Test - public void testEscapeHtml4() { - for (final String[] element : HTML_ESCAPES) { - final String message = element[0]; - final String expected = element[1]; - final String original = element[2]; - assertEquals(expected, StringEscapeUtils.escapeHtml4(original), message); - final StringWriter sw = new StringWriter(); - try { - StringEscapeUtils.ESCAPE_HTML4.translate(original, sw); - } catch (final IOException e) { - } - final String actual = original == null ? null : sw.toString(); - assertEquals(expected, actual, message); - } - } - - @Test - public void testUnescapeHtml4() { - for (final String[] element : HTML_ESCAPES) { - final String message = element[0]; - final String expected = element[2]; - final String original = element[1]; - assertEquals(expected, StringEscapeUtils.unescapeHtml4(original), message); - - final StringWriter sw = new StringWriter(); - try { - StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw); - } catch (final IOException e) { - } - final String actual = original == null ? null : sw.toString(); - assertEquals(expected, actual, message); - } - // \u00E7 is a cedilla (c with wiggle under) - // note that the test string must be 7-bit-clean (Unicode escaped) or else it will compile incorrectly - // on some locales - assertEquals("Fran\u00E7ais", StringEscapeUtils.unescapeHtml4("Fran\u00E7ais"), "funny chars pass through OK"); - - assertEquals("Hello&;World", StringEscapeUtils.unescapeHtml4("Hello&;World")); - assertEquals("Hello&#;World", StringEscapeUtils.unescapeHtml4("Hello&#;World")); - assertEquals("Hello&# ;World", StringEscapeUtils.unescapeHtml4("Hello&# ;World")); - assertEquals("Hello&##;World", StringEscapeUtils.unescapeHtml4("Hello&##;World")); - } - - @Test - public void testUnescapeHexCharsHtml() { - // Simple easy to grok test - assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape"); - assertEquals("\u0080\u009F", StringEscapeUtils.unescapeHtml4("€Ÿ"), "hex number unescape"); - // Test all Character values: - for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { - final Character c1 = i; - final Character c2 = (char) (i + 1); - final String expected = c1.toString() + c2.toString(); - final String escapedC1 = "&#x" + Integer.toHexString(c1) + ";"; - final String escapedC2 = "&#x" + Integer.toHexString(c2) + ";"; - assertEquals(expected, StringEscapeUtils.unescapeHtml4(escapedC1 + escapedC2), - "hex number unescape index " + i); - } - } - - @Test - public void testUnescapeUnknownEntity() { - assertEquals("&zzzz;", StringEscapeUtils.unescapeHtml4("&zzzz;")); - } - - @Test - public void testEscapeHtmlVersions() { - assertEquals("Β", StringEscapeUtils.escapeHtml4("\u0392")); - assertEquals("\u0392", StringEscapeUtils.unescapeHtml4("Β")); - - // TODO: refine API for escaping/unescaping specific HTML versions - } - - - - @Test - public void testEscapeXml10() { - assertEquals("a<b>c"d'e&f", StringEscapeUtils.escapeXml10("ac\"d'e&f")); - assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml10("a\tb\rc\nd"), - "XML 1.0 should not escape \t \n \r"); - assertEquals("ab", StringEscapeUtils.escapeXml10("a\u0000\u0001\u0008\u000b\u000c\u000e\u001fb"), - "XML 1.0 should omit most #x0-x8 | #xb | #xc | #xe-#x19"); - assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml10("a\ud7ff\ud800 \udfff \ue000b"), - "XML 1.0 should omit #xd800-#xdfff"); - assertEquals("a\ufffdb", StringEscapeUtils.escapeXml10("a\ufffd\ufffe\uffffb"), - "XML 1.0 should omit #xfffe | #xffff"); - assertEquals("a\u007e„\u0085†Ÿ\u00a0b", - StringEscapeUtils.escapeXml10("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"), - "XML 1.0 should escape #x7f-#x84 | #x86 - #x9f, for XML 1.1 compatibility"); - } - - @Test - public void testEscapeXml11() { - assertEquals("a<b>c"d'e&f", StringEscapeUtils.escapeXml11("ac\"d'e&f")); - assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml11("a\tb\rc\nd"), - "XML 1.1 should not escape \t \n \r"); - assertEquals("ab", StringEscapeUtils.escapeXml11("a\u0000b"), - "XML 1.1 should omit #x0"); - assertEquals("a b", - StringEscapeUtils.escapeXml11("a\u0001\u0008\u000b\u000c\u000e\u001fb"), - "XML 1.1 should escape #x1-x8 | #xb | #xc | #xe-#x19"); - assertEquals("a\u007e„\u0085†Ÿ\u00a0b", - StringEscapeUtils.escapeXml11("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"), - "XML 1.1 should escape #x7F-#x84 | #x86-#x9F"); - assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml11("a\ud7ff\ud800 \udfff \ue000b"), - "XML 1.1 should omit #xd800-#xdfff"); - assertEquals("a\ufffdb", StringEscapeUtils.escapeXml11("a\ufffd\ufffe\uffffb"), - "XML 1.1 should omit #xfffe | #xffff"); - } - - /** - * Reverse of the above. - * - * @see LANG-729 - */ - @Test - public void testUnescapeXmlSupplementaryCharacters() { - assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("𣎴"), - "Supplementary character must be represented using a single escape"); - - assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c 𣎴"), - "Supplementary characters mixed with basic characters should be decoded correctly"); - } - - // Tests issue #38569 - // http://issues.apache.org/bugzilla/show_bug.cgi?id=38569 - @Test - public void testStandaloneAmphersand() { - assertEquals("", StringEscapeUtils.unescapeHtml4("<P&O>")); - assertEquals("test & <", StringEscapeUtils.unescapeHtml4("test & <")); - assertEquals("", StringEscapeUtils.unescapeXml("<P&O>")); - assertEquals("test & <", StringEscapeUtils.unescapeXml("test & <")); - } - - @Test - public void testLang313() { - assertEquals("& &", StringEscapeUtils.unescapeHtml4("& &")); - } - - @Test - public void testEscapeCsvString() { - assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); - assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); - assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); - assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); - assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); - assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.escapeCsv("foo\uD84C\uDFB4bar")); - assertEquals("", StringEscapeUtils.escapeCsv("")); - assertNull(StringEscapeUtils.escapeCsv(null)); - } - - @Test - public void testEscapeCsvWriter() { - checkCsvEscapeWriter("foo.bar", "foo.bar"); - checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); - checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); - checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); - checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); - checkCsvEscapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar"); - checkCsvEscapeWriter("", null); - checkCsvEscapeWriter("", ""); - } - - private void checkCsvEscapeWriter(final String expected, final String value) { - try { - final StringWriter writer = new StringWriter(); - StringEscapeUtils.ESCAPE_CSV.translate(value, writer); - assertEquals(expected, writer.toString()); - } catch (final IOException e) { - fail("Threw: " + e); - } - } - - @Test - public void testUnescapeCsvString() { - assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); - assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); - assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); - assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); - assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); - assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.unescapeCsv("foo\uD84C\uDFB4bar")); - assertEquals("", StringEscapeUtils.unescapeCsv("")); - assertNull(StringEscapeUtils.unescapeCsv(null)); - - assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); - } - - @Test - public void testUnescapeCsvWriter() { - checkCsvUnescapeWriter("foo.bar", "foo.bar"); - checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); - checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); - checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); - checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); - checkCsvUnescapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar"); - checkCsvUnescapeWriter("", null); - checkCsvUnescapeWriter("", ""); - - checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); - } - - private void checkCsvUnescapeWriter(final String expected, final String value) { - try { - final StringWriter writer = new StringWriter(); - StringEscapeUtils.UNESCAPE_CSV.translate(value, writer); - assertEquals(expected, writer.toString()); - } catch (final IOException e) { - fail("Threw: " + e); - } - } - - /** - * Tests // https://issues.apache.org/jira/browse/LANG-480 - */ - @Test - public void testEscapeHtmlHighUnicode() { - // this is the utf8 representation of the character: - // COUNTING ROD UNIT DIGIT THREE - // in Unicode - // codepoint: U+1D362 - final byte[] data = {(byte) 0xF0, (byte) 0x9D, (byte) 0x8D, (byte) 0xA2}; - - final String original = new String(data, Charset.forName("UTF8")); - - final String escaped = StringEscapeUtils.escapeHtml4(original); - assertEquals(original, escaped, "High Unicode should not have been escaped"); - - final String unescaped = StringEscapeUtils.unescapeHtml4(escaped); - assertEquals(original, unescaped, "High Unicode should have been unchanged"); - - // TODO: I think this should hold, needs further investigation - // String unescapedFromEntity = StringEscapeUtils.unescapeHtml4("𝍢"); - // assertEquals("High Unicode should have been unescaped", original, unescapedFromEntity); - } - - /** - * Tests https://issues.apache.org/jira/browse/LANG-339 - */ - @Test - public void testEscapeHiragana() { - // Some random Japanese Unicode characters - final String original = "\u304B\u304C\u3068"; - final String escaped = StringEscapeUtils.escapeHtml4(original); - assertEquals(original, escaped, - "Hiragana character Unicode behaviour should not be being escaped by escapeHtml4"); - - final String unescaped = StringEscapeUtils.unescapeHtml4(escaped); - - assertEquals(escaped, unescaped, "Hiragana character Unicode behaviour has changed - expected no unescaping"); - } - - /** - * Tests https://issues.apache.org/jira/browse/LANG-708 - * - * @throws IOException - * if an I/O error occurs - */ - @Test - public void testLang708() throws IOException { - final byte[] inputBytes = Files.readAllBytes(Paths.get("src/test/resources/stringEscapeUtilsTestData.txt")); - final String input = new String(inputBytes, StandardCharsets.UTF_8); - final String escaped = StringEscapeUtils.escapeEcmaScript(input); - // just the end: - assertTrue(escaped.endsWith("}]"), escaped); - // a little more: - assertTrue(escaped.endsWith("\"valueCode\\\":\\\"\\\"}]"), escaped); - } - - /** - * Tests https://issues.apache.org/jira/browse/LANG-911 - */ - @Test - public void testLang911() { - final String bellsTest = "\ud83d\udc80\ud83d\udd14"; - final String value = StringEscapeUtils.escapeJava(bellsTest); - final String valueTest = StringEscapeUtils.unescapeJava(value); - assertEquals(bellsTest, valueTest); - } - - @Test - public void testEscapeJson() { - assertNull(StringEscapeUtils.escapeJson(null)); - try { - StringEscapeUtils.ESCAPE_JSON.translate(null, null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - try { - StringEscapeUtils.ESCAPE_JSON.translate("", null); - fail("Exception expected!"); - } catch (final IOException ex) { - fail("Exception expected!"); - } catch (final IllegalArgumentException ex) { - } - - assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\"")); - - final String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/"; - final String input = "\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/"; - - assertEquals(expected, StringEscapeUtils.escapeJson(input)); - } - - @Test - public void testBuilder() { - final String result = - StringEscapeUtils.builder(StringEscapeUtils.ESCAPE_XML10).escape("<").append(">").toString(); - assertEquals("<>", result); - } - - @Test - public void testEscapeXSI() { - assertNull(null, escapeXSI(null)); - assertEquals("He\\ didn\\'t\\ say,\\ \\\"Stop!\\\"", escapeXSI("He didn't say, \"Stop!\"")); - assertEquals("\\\\", escapeXSI("\\")); - assertEquals("", escapeXSI("\n")); - } - - @Test - public void testUnscapeXSI() { - assertNull(null, unescapeXSI(null)); - assertEquals("\"", unescapeXSI("\\\"")); - assertEquals("He didn't say, \"Stop!\"", unescapeXSI("He\\ didn\\'t\\ say,\\ \\\"Stop!\\\"")); - assertEquals("\\", unescapeXSI("\\\\")); - assertEquals("", unescapeXSI("\\")); - } - - @Test - public void testUnescapeEcmaScript() { - assertNull(StringEscapeUtils.unescapeEcmaScript(null)); - assertEquals("8lvc1u+6B#-I", StringEscapeUtils.unescapeEcmaScript("8lvc1u+6B#-I")); - assertEquals("", - StringEscapeUtils.unescapeEcmaScript("")); - assertEquals(">", - StringEscapeUtils.unescapeEcmaScript(">")); - } - - @Test - public void testEscapeHtmlThree() { - assertNull(StringEscapeUtils.escapeHtml3(null)); - assertEquals("a", StringEscapeUtils.escapeHtml3("a")); - assertEquals("<b>a", StringEscapeUtils.escapeHtml3("a")); - } - - @Test - public void testUnescapeJson() { - final String jsonString = - "{\"age\":100,\"name\":\"kyong.com\n\",\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"]}"; - - assertEquals("", StringEscapeUtils.unescapeJson("")); - assertEquals(" ", StringEscapeUtils.unescapeJson(" ")); - assertEquals("a:b", StringEscapeUtils.unescapeJson("a:b")); - assertEquals(jsonString, StringEscapeUtils.unescapeJson(jsonString)); - } - - @Test // TEXT-120 - public void testUnescapeJsonDoubleQuoteAndForwardSlash() { - final String escapedJsonString = "double quote: \\\" and a forward slash: \\/"; - final String jsonString = "double quote: \" and a forward slash: /"; - - assertEquals(jsonString, StringEscapeUtils.unescapeJson(escapedJsonString)); - } - - @Test - public void testDeleteCharacter() { - final String deleteString = "Delete: \u007F"; - assertEquals("Delete: \\u007F", StringEscapeUtils.escapeJson(deleteString)); - } -} diff --git a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java b/src/test/java/org/apache/commons/text/StringSubstitutorTest.java deleted file mode 100644 index b4390d808b..0000000000 --- a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java +++ /dev/null @@ -1,677 +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.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.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.apache.commons.text.lookup.StringLookup; -import org.apache.commons.text.lookup.StringLookupFactory; -import org.apache.commons.text.matcher.StringMatcher; -import org.apache.commons.text.matcher.StringMatcherFactory; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Test class for {@link StringSubstitutor}. - */ -public class StringSubstitutorTest { - - private Map values; - - private void doTestNoReplace(final String replaceTemplate) { - final StringSubstitutor sub = new StringSubstitutor(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((TextStringBuilder) null)); - assertNull(sub.replace((TextStringBuilder) null, 0, 100)); - assertNull(sub.replace((Object) null)); - assertFalse(sub.replaceIn((StringBuffer) null)); - assertFalse(sub.replaceIn((StringBuffer) null, 0, 100)); - assertFalse(sub.replaceIn((TextStringBuilder) null)); - assertFalse(sub.replaceIn((TextStringBuilder) null, 0, 100)); - } else { - assertEquals(replaceTemplate, sub.replace(replaceTemplate)); - final TextStringBuilder bld = new TextStringBuilder(replaceTemplate); - assertFalse(sub.replaceIn(bld)); - assertEquals(replaceTemplate, bld.toString()); - } - } - - private void doTestReplace(final String expectedResult, final String replaceTemplate, final boolean substring) { - final StringSubstitutor sub = new StringSubstitutor(values); - doTestReplace(sub, expectedResult, replaceTemplate, substring); - } - - // ----------------------------------------------------------------------- - private void doTestReplace(final StringSubstitutor 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 TextStringBuilder - TextStringBuilder bld = new TextStringBuilder(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 TextStringBuilder - bld = new TextStringBuilder(replaceTemplate); - assertTrue(sub.replaceIn(bld)); - assertEquals(expectedResult, bld.toString()); - if (substring) { - bld = new TextStringBuilder(replaceTemplate); - assertTrue(sub.replaceIn(bld, 1, bld.length() - 2)); - assertEquals(expectedResult, bld.toString()); // expect full result as remainder is untouched - } - } - - @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 get set. - */ - @Test - public void testGetSetEscape() { - final StringSubstitutor sub = new StringSubstitutor(); - assertEquals('$', sub.getEscapeChar()); - sub.setEscapeChar('<'); - assertEquals('<', sub.getEscapeChar()); - } - - /** - * Test for LANG-1055: StringSubstitutor.replaceSystemProperties does not work consistently - */ - @Test - public void testLANG1055() { - System.setProperty("test_key", "test_value"); - - final String expected = StringSubstitutor.replace("test_key=${test_key}", System.getProperties()); - final String actual = StringSubstitutor.replaceSystemProperties("test_key=${test_key}"); - assertEquals(expected, actual); - } - - /** - * Tests adjacent keys. - */ - @Test - public void testReplaceAdjacentAtEnd() { - values.put("code", "GBP"); - values.put("amount", "12.50"); - final StringSubstitutor sub = new StringSubstitutor(values); - assertEquals("Amount is GBP12.50", sub.replace("Amount is ${code}${amount}")); - } - - /** - * Tests adjacent keys. - */ - @Test - public void testReplaceAdjacentAtStart() { - values.put("code", "GBP"); - values.put("amount", "12.50"); - final StringSubstitutor sub = new StringSubstitutor(values); - assertEquals("GBP12.50 charged", sub.replace("${code}${amount} charged")); - } - - /** - * Tests key replace changing map after initialization (not recommended). - */ - @Test - public void testReplaceChangedMap() { - final StringSubstitutor sub = new StringSubstitutor(values); - values.put("target", "moon"); - assertEquals("The quick brown fox jumps over the moon.", - sub.replace("The ${animal} jumps over the ${target}.")); - } - - /** - * 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 replace with null. - */ - @Test - public void testReplaceEmpty() { - doTestNoReplace(""); - } - - /** - * 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 escaping. - */ - @Test - public void testReplaceEscaping() { - 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); - } - - @Test - public void testReplaceInTakingStringBufferWithNonNull() { - final StringSubstitutor strSubstitutor = new StringSubstitutor(new HashMap(), "WV@i#y?N*[", - "WV@i#y?N*[", '*'); - - assertFalse(strSubstitutor.isPreserveEscapes()); - assertFalse(strSubstitutor.replaceIn(new StringBuffer("WV@i#y?N*["))); - assertEquals('*', strSubstitutor.getEscapeChar()); - } - - @Test - public void testReplaceInTakingStringBuilderWithNonNull() { - final StringLookup strLookup = StringLookupFactory.INSTANCE.systemPropertyStringLookup(); - final StringSubstitutor strSubstitutor = new StringSubstitutor(strLookup, "b map = new HashMap<>(); - final StringSubstitutor strSubstitutor = new StringSubstitutor(map, "", "", 'T', "K+<'f"); - - assertFalse(strSubstitutor.replaceIn((StringBuilder) null)); - } - - @Test - public void testReplaceInTakingTwoAndThreeIntsReturningFalse() { - final Map hashMap = new HashMap<>(); - final StringLookup mapStringLookup = StringLookupFactory.INSTANCE.mapStringLookup(hashMap); - final StringMatcher strMatcher = StringMatcherFactory.INSTANCE.tabMatcher(); - final StringSubstitutor strSubstitutor = new StringSubstitutor(mapStringLookup, strMatcher, strMatcher, 'b', - strMatcher); - - assertFalse(strSubstitutor.replaceIn((StringBuilder) null, 1315, -1369)); - assertEquals('b', strSubstitutor.getEscapeChar()); - assertFalse(strSubstitutor.isPreserveEscapes()); - } - - /** - * 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 StringSubstitutor sub = new StringSubstitutor(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 StringSubstitutor sub = new StringSubstitutor(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 replace with fail on undefined variable. - */ - @Test - public void testReplaceFailOnUndefinedVariable() { - values.put("animal.1", "fox"); - values.put("animal.2", "mouse"); - values.put("species", "2"); - final StringSubstitutor sub = new StringSubstitutor(values); - sub.setEnableUndefinedVariableException(true); - - assertThatIllegalArgumentException().isThrownBy(() -> - sub.replace("The ${animal.${species}} jumps over the ${target}.")). - withMessage("Cannot resolve variable 'animal.${species' (enableSubstitutionInVariables=false)."); - - assertThatIllegalArgumentException().isThrownBy(() -> - sub.replace("The ${animal.${species:-1}} jumps over the ${target}.")). - withMessage("Cannot resolve variable 'animal.${species:-1' (enableSubstitutionInVariables=false)."); - - assertThatIllegalArgumentException().isThrownBy(() -> - sub.replace("The ${test:-statement} is a sample for missing ${unknown}.")). - withMessage("Cannot resolve variable 'unknown' (enableSubstitutionInVariables=false)."); - - //if default value is available, exception will not be thrown - assertEquals("The statement is a sample for missing variable.", - sub.replace("The ${test:-statement} is a sample for missing ${unknown:-variable}.")); - - assertEquals("The fox jumps over the lazy dog.", - sub.replace("The ${animal.1} jumps over the ${target}.")); - } - - /** - * Tests whether replace with fail on undefined variable with - * substitution in variable names enabled. - */ - @Test - public void testReplaceFailOnUndefinedVariableWithReplaceInVariable() { - values.put("animal.1", "fox"); - values.put("animal.2", "mouse"); - values.put("species", "2"); - values.put("statement.1", "2"); - values.put("recursive", "1"); - values.put("word", "variable"); - values.put("testok.2", "statement"); - final StringSubstitutor sub = new StringSubstitutor(values); - sub.setEnableUndefinedVariableException(true); - 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}.")); - - //exception is thrown here because variable with name test.1 is missing - assertThatIllegalArgumentException().isThrownBy(() -> - sub.replace("The ${test.${statement}} is a sample for missing ${word}.")). - withMessage("Cannot resolve variable 'statement' (enableSubstitutionInVariables=true)."); - - //exception is thrown here because variable with name test.2 is missing - assertThatIllegalArgumentException().isThrownBy(() -> - sub.replace("The ${test.${statement.${recursive}}} is a sample for missing ${word}.")). - withMessage("Cannot resolve variable 'test.2' (enableSubstitutionInVariables=true)."); - - assertEquals("The statement is a sample for missing variable.", - sub.replace("The ${testok.${statement.${recursive}}} is a sample for missing ${word}.")); - } - - /** - * 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 StringSubstitutor sub = new StringSubstitutor(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}.")); - } - - /** - * 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 suffix but no prefix. - */ - @Test - public void testReplaceNoPrefixSuffix() { - doTestReplace("The animal} jumps over the lazy dog.", "The animal} jumps over the ${target}.", true); - } - - /** - * Tests replace with no variables. - */ - @Test - public void testReplaceNoVariables() { - doTestNoReplace("The balloon arrived."); - } - - /** - * Tests replace with null. - */ - @Test - public void testReplaceNull() { - doTestNoReplace(null); - } - - /** - * Tests simple key replace. - */ - @Test - public void testReplacePartialString_noReplace() { - final StringSubstitutor sub = new StringSubstitutor(); - assertEquals("${animal} jumps", sub.replace("The ${animal} jumps over the ${target}.", 4, 15)); - } - - /** - * 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 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); - } - - // ----------------------------------------------------------------------- - /** - * 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 escaping. - */ - @Test - public void testReplaceSoloEscaping() { - doTestReplace("${animal}", "$${animal}", false); - } - - @Test - public void testReplaceTakingCharSequenceReturningNull() { - final StringSubstitutor strSubstitutor = new StringSubstitutor((StringLookup) null); - - assertNull(strSubstitutor.replace((CharSequence) null)); - assertFalse(strSubstitutor.isPreserveEscapes()); - assertEquals('$', strSubstitutor.getEscapeChar()); - } - - @Test - public void testReplaceTakingThreeArgumentsThrowsNullPointerException() { - assertThatNullPointerException().isThrownBy(() -> StringSubstitutor.replace(null, (Properties) null)); - } - - /** - * 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 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 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 protected. - */ - @Test - public void testResolveVariable() { - final TextStringBuilder builder = new TextStringBuilder("Hi ${name}!"); - final Map map = new HashMap<>(); - map.put("name", "commons"); - final StringSubstitutor sub = new StringSubstitutor(map) { - @Override - protected String resolveVariable(final String variableName, final TextStringBuilder 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()); - } - - @Test - public void testSamePrefixAndSuffix() { - final Map map = new HashMap<>(); - map.put("greeting", "Hello"); - map.put(" there ", "XXX"); - map.put("name", "commons"); - assertEquals("Hi commons!", StringSubstitutor.replace("Hi @name@!", map, "@", "@")); - assertEquals("Hello there commons!", StringSubstitutor.replace("@greeting@ there @name@!", map, "@", "@")); - } - - // ----------------------------------------------------------------------- - /** - * Tests static. - */ - @Test - public void testStaticReplace() { - final Map map = new HashMap<>(); - map.put("name", "commons"); - assertEquals("Hi commons!", StringSubstitutor.replace("Hi ${name}!", map)); - } - - /** - * Tests static. - */ - @Test - public void testStaticReplacePrefixSuffix() { - final Map map = new HashMap<>(); - map.put("name", "commons"); - assertEquals("Hi commons!", StringSubstitutor.replace("Hi !", map, "<", ">")); - } - - /** - * Tests interpolation with system properties. - */ - @Test - public void testStaticReplaceSystemProperties() { - final TextStringBuilder buf = new TextStringBuilder(); - 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(), StringSubstitutor.replaceSystemProperties( - "Hi ${user.name}, you are " + "working with ${os.name}, your home " + "directory is ${user.home}.")); - } - - /** - * 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!", StringSubstitutor.replace(org, props)); - } - - @Test - public void testSubstitutePreserveEscape() { - final String org = "${not-escaped} $${escaped}"; - final Map map = new HashMap<>(); - map.put("not-escaped", "value"); - - final StringSubstitutor sub = new StringSubstitutor(map, "${", "}", '$'); - assertFalse(sub.isPreserveEscapes()); - assertEquals("value ${escaped}", sub.replace(org)); - - sub.setPreserveEscapes(true); - assertTrue(sub.isPreserveEscapes()); - assertEquals("value $${escaped}", sub.replace(org)); - } - -} diff --git a/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java b/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java deleted file mode 100644 index 33157b7467..0000000000 --- a/src/test/java/org/apache/commons/text/StringSubstitutorWithInterpolatorStringLookupTest.java +++ /dev/null @@ -1,101 +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.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.text.lookup.StringLookup; -import org.apache.commons.text.lookup.StringLookupFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class StringSubstitutorWithInterpolatorStringLookupTest { - - @Test - public void testCustomMapWithDefaults() { - testCustomMapWithDefaults(true); - } - - private void testCustomMapWithDefaults(final boolean addDefaultLookups) { - final String key = "key"; - final String value = "value"; - final Map map = new HashMap<>(); - map.put(key, value); - final StringLookup mapStringLookup = StringLookupFactory.INSTANCE.mapStringLookup(map); - final Map stringLookupMap = new HashMap<>(); - stringLookupMap.put("customLookup", mapStringLookup); - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup(stringLookupMap, null, addDefaultLookups)); - if (addDefaultLookups) { - final String spKey = "user.name"; - Assertions.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}")); - } - Assertions.assertEquals("value", strSubst.replace("${customLookup:key}")); - } - - @Test - public void testCustomMapWithoutDefaults() { - testCustomMapWithDefaults(false); - } - - @Test - public void testLocalHostLookup_Address() throws UnknownHostException { - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - Assertions.assertEquals(InetAddress.getLocalHost().getHostAddress(), strSubst.replace("${localhost:address}")); - } - - @Test - public void testLocalHostLookup_CanonicalName() throws UnknownHostException { - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - Assertions.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(), - strSubst.replace("${localhost:canonical-name}")); - } - - @Test - public void testLocalHostLookup_Name() throws UnknownHostException { - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - Assertions.assertEquals(InetAddress.getLocalHost().getHostName(), strSubst.replace("${localhost:name}")); - } - - @Test - public void testMapAndSystemProperty() { - final String key = "key"; - final String value = "value"; - final Map map = new HashMap<>(); - map.put(key, value); - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup(map)); - final String spKey = "user.name"; - Assertions.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}")); - Assertions.assertEquals(value, strSubst.replace("${" + key + "}")); - } - - @Test - public void testSystemProperty() { - final StringSubstitutor strSubst = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - final String spKey = "user.name"; - Assertions.assertEquals(System.getProperty(spKey), strSubst.replace("${sys:" + spKey + "}")); - } -} diff --git a/src/test/java/org/apache/commons/text/StringTokenizerTest.java b/src/test/java/org/apache/commons/text/StringTokenizerTest.java deleted file mode 100644 index 2cbbf6b171..0000000000 --- a/src/test/java/org/apache/commons/text/StringTokenizerTest.java +++ /dev/null @@ -1,934 +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 static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.assertThrows; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.NoSuchElementException; - -import org.apache.commons.text.matcher.StringMatcher; -import org.apache.commons.text.matcher.StringMatcherFactory; -import org.junit.jupiter.api.Test; - -/** - * Unit test for {@link StringTokenizer}. - */ -public class StringTokenizerTest { - - private static final String CSV_SIMPLE_FIXTURE = "A,b,c"; - - private static final String TSV_SIMPLE_FIXTURE = "A\tb\tc"; - - private void checkClone(final StringTokenizer tokenizer) { - assertFalse(StringTokenizer.getCSVInstance() == tokenizer); - assertFalse(StringTokenizer.getTSVInstance() == tokenizer); - } - - // ----------------------------------------------------------------------- - @Test - public void test1() { - - final String input = "a;b;c;\"d;\"\"e\";f; ; ; "; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f", "", "", "" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test2() { - - final String input = "a;b;c ;\"d;\"\"e\";f; ; ;"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c ", "d;\"e", "f", " ", " ", "" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test3() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", " c", "d;\"e", "f", " ", " ", "" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test4() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test5() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d;\"e", "f", null, null, null }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test6() { - - final String input = "a;b; c;\"d;\"\"e\";f; ; ;"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterChar(';'); - tok.setQuoteChar('"'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - // tok.setTreatingEmptyAsNull(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", " c", "d;\"e", "f", null, null, null }; - - int nextCount = 0; - while (tok.hasNext()) { - tok.next(); - nextCount++; - } - - int prevCount = 0; - while (tok.hasPrevious()) { - tok.previous(); - prevCount++; - } - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - assertTrue(nextCount == expected.length, - "could not cycle through entire token list using the 'hasNext' and 'next' methods"); - assertTrue(prevCount == expected.length, - "could not cycle through entire token list using the 'hasPrevious' and 'previous' methods"); - } - - @Test - public void test7() { - - final String input = "a b c \"d e\" f "; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterMatcher(StringMatcherFactory.INSTANCE.spaceMatcher()); - tok.setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher()); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()); - tok.setIgnoreEmptyTokens(false); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "", "", "b", "c", "d e", "f", "" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void test8() { - - final String input = "a b c \"d e\" f "; - final StringTokenizer tok = new StringTokenizer(input); - tok.setDelimiterMatcher(StringMatcherFactory.INSTANCE.spaceMatcher()); - tok.setQuoteMatcher(StringMatcherFactory.INSTANCE.doubleQuoteMatcher()); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.noneMatcher()); - tok.setIgnoreEmptyTokens(true); - final String[] tokens = tok.getTokenArray(); - - final String[] expected = {"a", "b", "c", "d e", "f" }; - - assertEquals(expected.length, tokens.length, Arrays.toString(tokens)); - for (int i = 0; i < expected.length; i++) { - assertEquals(expected[i], tokens[i], - "token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'"); - } - - } - - @Test - public void testBasic1() { - final String input = "a b c"; - final StringTokenizer tok = new StringTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic2() { - final String input = "a \nb\fc"; - final StringTokenizer tok = new StringTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic3() { - final String input = "a \nb\u0001\fc"; - final StringTokenizer tok = new StringTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("b\u0001", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic4() { - final String input = "a \"b\" c"; - final StringTokenizer tok = new StringTokenizer(input); - assertEquals("a", tok.next()); - assertEquals("\"b\"", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasic5() { - final String input = "a:b':c"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - assertEquals("a", tok.next()); - assertEquals("b'", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicDelim1() { - final String input = "a:b:c"; - final StringTokenizer tok = new StringTokenizer(input, ':'); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicDelim2() { - final String input = "a:b:c"; - final StringTokenizer tok = new StringTokenizer(input, ','); - assertEquals("a:b:c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimString() { - final String input = "a##b##c"; - final StringTokenizer tok = new StringTokenizer(input, "##"); - - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimMatcher() { - final String input = "a/b\\c"; - final StringMatcher delimMatcher = StringMatcherFactory.INSTANCE.charSetMatcher(new char[] {'/', '\\' }); - - final StringTokenizer tok = new StringTokenizer(input, delimMatcher); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testDelimMatcherQuoteMatcher() { - final String input = "`a`;`b`;`c`"; - final StringMatcher delimMatcher = StringMatcherFactory.INSTANCE.charSetMatcher(new char[] {';' }); - final StringMatcher quoteMatcher = StringMatcherFactory.INSTANCE.charSetMatcher(new char[] {'`' }); - - final StringTokenizer tok = new StringTokenizer(input, delimMatcher, quoteMatcher); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicEmpty1() { - final String input = "a b c"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setIgnoreEmptyTokens(false); - assertEquals("a", tok.next()); - assertEquals("", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicEmpty2() { - final String input = "a b c"; - final StringTokenizer tok = new StringTokenizer(input); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertNull(tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted1() { - final String input = "a 'b' c"; - final StringTokenizer tok = new StringTokenizer(input, ' ', '\''); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted2() { - final String input = "a:'b':"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted3() { - final String input = "a:'b''c'"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b'c", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted4() { - final String input = "a: 'b' 'c' :d"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b c", tok.next()); - assertEquals("d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted5() { - final String input = "a: 'b'x'c' :d"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bxc", tok.next()); - assertEquals("d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted6() { - final String input = "a:'b'\"c':d"; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setQuoteMatcher(StringMatcherFactory.INSTANCE.quoteMatcher()); - assertEquals("a", tok.next()); - assertEquals("b\"c:d", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuoted7() { - final String input = "a:\"There's a reason here\":b"; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setQuoteMatcher(StringMatcherFactory.INSTANCE.quoteMatcher()); - assertEquals("a", tok.next()); - assertEquals("There's a reason here", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicQuotedTrimmed1() { - final String input = "a: 'b' :"; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicTrimmed1() { - final String input = "a: b : "; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicTrimmed2() { - final String input = "a: b :"; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.stringMatcher(" ")); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed1() { - final String input = "a: bIGNOREc : "; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bc", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed2() { - final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bc", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed3() { - final String input = "IGNOREaIGNORE: IGNORE bIGNOREc IGNORE : IGNORE "; - final StringTokenizer tok = new StringTokenizer(input, ':'); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.stringMatcher("IGNORE")); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals(" bc ", tok.next()); - assertEquals(" ", tok.next()); - assertFalse(tok.hasNext()); - } - - @Test - public void testBasicIgnoreTrimmed4() { - final String input = "IGNOREaIGNORE: IGNORE 'bIGNOREc'IGNORE'd' IGNORE : IGNORE "; - final StringTokenizer tok = new StringTokenizer(input, ':', '\''); - tok.setIgnoredMatcher(StringMatcherFactory.INSTANCE.stringMatcher("IGNORE")); - tok.setTrimmerMatcher(StringMatcherFactory.INSTANCE.trimMatcher()); - tok.setIgnoreEmptyTokens(false); - tok.setEmptyTokenAsNull(true); - assertEquals("a", tok.next()); - assertEquals("bIGNOREcd", tok.next()); - assertNull(tok.next()); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testListArray() { - final String input = "a b c"; - final StringTokenizer tok = new StringTokenizer(input); - final String[] array = tok.getTokenArray(); - final List list = tok.getTokenList(); - - assertEquals(Arrays.asList(array), list); - assertEquals(3, list.size()); - } - - // ----------------------------------------------------------------------- - private void testCSV(final String data) { - this.testXSVAbc(StringTokenizer.getCSVInstance(data)); - this.testXSVAbc(StringTokenizer.getCSVInstance(data.toCharArray())); - } - - @Test - public void testCSVEmpty() { - this.testEmpty(StringTokenizer.getCSVInstance()); - this.testEmpty(StringTokenizer.getCSVInstance("")); - } - - @Test - public void testCSVSimple() { - this.testCSV(CSV_SIMPLE_FIXTURE); - } - - @Test - public void testCSVSimpleNeedsTrim() { - this.testCSV(" " + CSV_SIMPLE_FIXTURE); - this.testCSV(" \n\t " + CSV_SIMPLE_FIXTURE); - this.testCSV(" \n " + CSV_SIMPLE_FIXTURE + "\n\n\r"); - } - - void testEmpty(final StringTokenizer tokenizer) { - this.checkClone(tokenizer); - assertFalse(tokenizer.hasNext()); - assertFalse(tokenizer.hasPrevious()); - assertNull(tokenizer.nextToken()); - assertEquals(0, tokenizer.size()); - assertThrows(NoSuchElementException.class, () -> tokenizer.next()); - } - - @Test - public void testGetContent() { - final String input = "a b c \"d e\" f "; - StringTokenizer tok = new StringTokenizer(input); - assertEquals(input, tok.getContent()); - - tok = new StringTokenizer(input.toCharArray()); - assertEquals(input, tok.getContent()); - - tok = new StringTokenizer(); - assertNull(tok.getContent()); - } - - // ----------------------------------------------------------------------- - @Test - public void testChaining() { - final StringTokenizer tok = new StringTokenizer(); - assertEquals(tok, tok.reset()); - assertEquals(tok, tok.reset("")); - assertEquals(tok, tok.reset(new char[0])); - assertEquals(tok, tok.setDelimiterChar(' ')); - assertEquals(tok, tok.setDelimiterString(" ")); - assertEquals(tok, tok.setDelimiterMatcher(null)); - assertEquals(tok, tok.setQuoteChar(' ')); - assertEquals(tok, tok.setQuoteMatcher(null)); - assertEquals(tok, tok.setIgnoredChar(' ')); - assertEquals(tok, tok.setIgnoredMatcher(null)); - assertEquals(tok, tok.setTrimmerMatcher(null)); - assertEquals(tok, tok.setEmptyTokenAsNull(false)); - assertEquals(tok, tok.setIgnoreEmptyTokens(false)); - } - - /** - * Tests that the {@link StringTokenizer#clone()} clone method catches {@link CloneNotSupportedException} and - * returns null. - */ - @Test - public void testCloneNotSupportedException() { - final Object notCloned = new StringTokenizer() { - - @Override - Object cloneReset() throws CloneNotSupportedException { - throw new CloneNotSupportedException("test"); - } - }.clone(); - assertNull(notCloned); - } - - @Test - public void testCloneNull() { - final StringTokenizer tokenizer = new StringTokenizer((char[]) null); - // Start sanity check - assertNull(tokenizer.nextToken()); - tokenizer.reset(); - assertNull(tokenizer.nextToken()); - // End sanity check - final StringTokenizer clonedTokenizer = (StringTokenizer) tokenizer.clone(); - tokenizer.reset(); - assertNull(tokenizer.nextToken()); - assertNull(clonedTokenizer.nextToken()); - } - - @Test - public void testCloneReset() { - final char[] input = new char[] {'a' }; - final StringTokenizer tokenizer = new StringTokenizer(input); - // Start sanity check - assertEquals("a", tokenizer.nextToken()); - tokenizer.reset(input); - assertEquals("a", tokenizer.nextToken()); - // End sanity check - final StringTokenizer clonedTokenizer = (StringTokenizer) tokenizer.clone(); - input[0] = 'b'; - tokenizer.reset(input); - assertEquals("b", tokenizer.nextToken()); - assertEquals("a", clonedTokenizer.nextToken()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String() { - StringTokenizer tok = new StringTokenizer("a b"); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer(""); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((String) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String_char() { - StringTokenizer tok = new StringTokenizer("a b", ' '); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer("", ' '); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((String) null, ' '); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_String_char_char() { - StringTokenizer tok = new StringTokenizer("a b", ' ', '"'); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer("", ' ', '"'); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((String) null, ' ', '"'); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray() { - StringTokenizer tok = new StringTokenizer("a b".toCharArray()); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer(new char[0]); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((char[]) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray_char() { - StringTokenizer tok = new StringTokenizer("a b".toCharArray(), ' '); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer(new char[0], ' '); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((char[]) null, ' '); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testConstructor_charArray_char_char() { - StringTokenizer tok = new StringTokenizer("a b".toCharArray(), ' ', '"'); - assertEquals(1, tok.getDelimiterMatcher().isMatch(" ".toCharArray(), 0, 0, 1)); - assertEquals(1, tok.getQuoteMatcher().isMatch("\"".toCharArray(), 0, 0, 1)); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer(new char[0], ' ', '"'); - assertFalse(tok.hasNext()); - - tok = new StringTokenizer((char[]) null, ' ', '"'); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset() { - final StringTokenizer tok = new StringTokenizer("a b c"); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset(); - assertEquals("a", tok.next()); - assertEquals("b", tok.next()); - assertEquals("c", tok.next()); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset_String() { - final StringTokenizer tok = new StringTokenizer("x x x"); - tok.reset("d e"); - assertEquals("d", tok.next()); - assertEquals("e", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset((String) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReset_charArray() { - final StringTokenizer tok = new StringTokenizer("x x x"); - - final char[] array = new char[] {'a', 'b', 'c' }; - tok.reset(array); - assertEquals("abc", tok.next()); - assertFalse(tok.hasNext()); - - tok.reset((char[]) null); - assertFalse(tok.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTSV() { - this.testXSVAbc(StringTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE)); - this.testXSVAbc(StringTokenizer.getTSVInstance(TSV_SIMPLE_FIXTURE.toCharArray())); - } - - @Test - public void testTSVEmpty() { - this.testEmpty(StringTokenizer.getTSVInstance()); - this.testEmpty(StringTokenizer.getTSVInstance("")); - } - - void testXSVAbc(final StringTokenizer tokenizer) { - this.checkClone(tokenizer); - assertEquals(-1, tokenizer.previousIndex()); - assertEquals(0, tokenizer.nextIndex()); - assertNull(tokenizer.previousToken()); - assertEquals("A", tokenizer.nextToken()); - assertEquals(1, tokenizer.nextIndex()); - assertEquals("b", tokenizer.nextToken()); - assertEquals(2, tokenizer.nextIndex()); - assertEquals("c", tokenizer.nextToken()); - assertEquals(3, tokenizer.nextIndex()); - assertNull(tokenizer.nextToken()); - assertEquals(3, tokenizer.nextIndex()); - assertEquals("c", tokenizer.previousToken()); - assertEquals(2, tokenizer.nextIndex()); - assertEquals("b", tokenizer.previousToken()); - assertEquals(1, tokenizer.nextIndex()); - assertEquals("A", tokenizer.previousToken()); - assertEquals(0, tokenizer.nextIndex()); - assertNull(tokenizer.previousToken()); - assertEquals(0, tokenizer.nextIndex()); - assertEquals(-1, tokenizer.previousIndex()); - assertEquals(3, tokenizer.size()); - } - - @Test - public void testIteration() { - final StringTokenizer tkn = new StringTokenizer("a b c"); - assertFalse(tkn.hasPrevious()); - assertThrows(NoSuchElementException.class, () -> tkn.previous()); - assertTrue(tkn.hasNext()); - - assertEquals("a", tkn.next()); - assertThrows(UnsupportedOperationException.class, () -> tkn.remove()); - assertThrows(UnsupportedOperationException.class, () -> tkn.set("x")); - assertThrows(UnsupportedOperationException.class, () -> tkn.add("y")); - assertTrue(tkn.hasPrevious()); - assertTrue(tkn.hasNext()); - - assertEquals("b", tkn.next()); - assertTrue(tkn.hasPrevious()); - assertTrue(tkn.hasNext()); - - assertEquals("c", tkn.next()); - assertTrue(tkn.hasPrevious()); - assertFalse(tkn.hasNext()); - - assertThrows(NoSuchElementException.class, () -> tkn.next()); - assertTrue(tkn.hasPrevious()); - assertFalse(tkn.hasNext()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTokenizeSubclassInputChange() { - final StringTokenizer tkn = new StringTokenizer("a b c d e") { - - @Override - protected List tokenize(final char[] chars, final int offset, final int count) { - return super.tokenize("w x y z".toCharArray(), 2, 5); - } - }; - assertEquals("x", tkn.next()); - assertEquals("y", tkn.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTokenizeSubclassOutputChange() { - final StringTokenizer tkn = new StringTokenizer("a b c") { - - @Override - protected List tokenize(final char[] chars, final int offset, final int count) { - final List list = super.tokenize(chars, offset, count); - Collections.reverse(list); - return list; - } - }; - assertEquals("c", tkn.next()); - assertEquals("b", tkn.next()); - assertEquals("a", tkn.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testToString() { - final StringTokenizer tkn = new StringTokenizer("a b c d e"); - assertEquals("StringTokenizer[not tokenized yet]", tkn.toString()); - tkn.next(); - assertEquals("StringTokenizer[a, b, c, d, e]", tkn.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerStringMatcher() { - final char[] chars = {'a', 'b', 'c', 'd' }; - final StringTokenizer tokens = new StringTokenizer(chars, "bc"); - assertEquals("a", tokens.next()); - assertEquals("d", tokens.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerStrMatcher() { - final char[] chars = {'a', ',', 'c' }; - final StringTokenizer tokens = new StringTokenizer(chars, StringMatcherFactory.INSTANCE.commaMatcher()); - assertEquals("a", tokens.next()); - assertEquals("c", tokens.next()); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringTokenizerQuoteMatcher() { - final char[] chars = {'\'', 'a', 'c', '\'', 'd' }; - final StringTokenizer tokens = new StringTokenizer(chars, StringMatcherFactory.INSTANCE.commaMatcher(), - StringMatcherFactory.INSTANCE.quoteMatcher()); - assertEquals("acd", tokens.next()); - } - - @Test - public void testPreviousTokenAndSetEmptyTokenAsNull() { - final StringTokenizer strTokenizer = StringTokenizer.getTSVInstance(" \t\n\r\f"); - strTokenizer.setEmptyTokenAsNull(true); - - assertNull(strTokenizer.previousToken()); - } -} diff --git a/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java b/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java deleted file mode 100644 index f51bdb5119..0000000000 --- a/src/test/java/org/apache/commons/text/TextStringBuilderAppendInsertTest.java +++ /dev/null @@ -1,1502 +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 TextStringBuilder}. - */ -public class TextStringBuilderAppendInsertTest { - - /** 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() { - TextStringBuilder sb = new TextStringBuilder("---"); - sb.appendNewLine().append("+++"); - assertThat(sb.toString()).isEqualTo("---" + SEP + "+++"); - - sb = new TextStringBuilder("---"); - sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine(); - assertThat(sb.toString()).isEqualTo("---#" + SEP); - } - - //----------------------------------------------------------------------- - @Test - public void testAppendWithNullText() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((String) null); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((String) null); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((String) null, 0, 1); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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 - } - - try { - sb.append((CharSequence) "bar", 2, 1); - fail("append(char[], 2, 1) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append((CharSequence) "bar", 2, 2); - fail("append(char[], 2, 2) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append((CharSequence) "bar", 2, -2); - fail("append(char[], 2, -2) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append((CharSequence) "bar", 2, 0); - fail("append(char[], 2, 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, 7); - assertThat(sb.toString()).isEqualTo("foobarard"); - } - - //----------------------------------------------------------------------- - @Test - public void testAppend_StringBuilder_int_int() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((String) null, 0, 1); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((StringBuffer) null); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((StringBuffer) null, 0, 1); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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_TextStringBuilder() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((TextStringBuilder) null); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - sb.append(new TextStringBuilder("foo")); - assertThat(sb.toString()).isEqualTo("foo"); - - sb.append(new TextStringBuilder("")); - assertThat(sb.toString()).isEqualTo("foo"); - - sb.append(new TextStringBuilder("bar")); - assertThat(sb.toString()).isEqualTo("foobar"); - } - - //----------------------------------------------------------------------- - @Test - public void testAppend_TextStringBuilder_int_int() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((TextStringBuilder) null, 0, 1); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - sb.append(new TextStringBuilder("foo"), 0, 3); - assertThat(sb.toString()).isEqualTo("foo"); - - try { - sb.append(new TextStringBuilder("bar"), -1, 1); - fail("append(char[], -1,) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append(new TextStringBuilder("bar"), 3, 1); - fail("append(char[], 3,) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append(new TextStringBuilder("bar"), 1, -1); - fail("append(char[],, -1) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append(new TextStringBuilder("bar"), 1, 3); - fail("append(char[], 1, 3) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append(new TextStringBuilder("bar"), -1, 3); - fail("append(char[], -1, 3) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - try { - sb.append(new TextStringBuilder("bar"), 4, 0); - fail("append(char[], 4, 0) expected IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // expected - } - - sb.append(new TextStringBuilder("bar"), 3, 0); - assertThat(sb.toString()).isEqualTo("foo"); - - sb.append(new TextStringBuilder("abcbardef"), 3, 3); - assertThat(sb.toString()).isEqualTo("foobar"); - } - - //----------------------------------------------------------------------- - @Test - public void testAppend_CharArray() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((char[]) null); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb = new TextStringBuilder(); - sb.setNullText("NULL").append((char[]) null, 0, 1); - assertThat(sb.toString()).isEqualTo("NULL"); - - sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final String str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final String str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final String str, final int startIndex, final int length) { - count[0]++; - return super.append(str, startIndex, length); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final StringBuffer str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final StringBuilder str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final StringBuffer str, final int startIndex, final int length) { - count[0]++; - return super.append(str, startIndex, length); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final StringBuilder str, final int startIndex, final int length) { - count[0]++; - return super.append(str, startIndex, length); - } - @Override - public TextStringBuilder 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_TextStringBuilder() { - final int[] count = new int[2]; - final TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final TextStringBuilder str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder appendNewLine() { - count[1]++; - return super.appendNewLine(); - } - }; - sb.appendln(new TextStringBuilder("foo")); - assertThat(sb.toString()).isEqualTo("foo" + SEP); - assertThat(count[0]).isEqualTo(1); - assertThat(count[1]).isEqualTo(1); - } - - //----------------------------------------------------------------------- - @Test - public void testAppendln_TextStringBuilder_int_int() { - final int[] count = new int[2]; - final TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final TextStringBuilder str, final int startIndex, final int length) { - count[0]++; - return super.append(str, startIndex, length); - } - @Override - public TextStringBuilder appendNewLine() { - count[1]++; - return super.appendNewLine(); - } - }; - sb.appendln(new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final char[] str) { - count[0]++; - return super.append(str); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder() { - private static final long serialVersionUID = 1L; - - @Override - public TextStringBuilder append(final char[] str, final int startIndex, final int length) { - count[0]++; - return super.append(str, startIndex, length); - } - @Override - public TextStringBuilder 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(1); - sb.appendFixedWidthPadRight("foo", 1, '-'); - assertThat(sb.toString()).isEqualTo("f"); - } - - //----------------------------------------------------------------------- - @Test - public void testAppendFixedWidthPadRight_int() { - final TextStringBuilder sb = new TextStringBuilder(); - 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() { - TextStringBuilder sb; - - sb = new TextStringBuilder(); - sb.append("Hi", (Object[]) null); - assertThat(sb.toString()).isEqualTo("Hi"); - - sb = new TextStringBuilder(); - sb.append("Hi", "Alice"); - assertThat(sb.toString()).isEqualTo("Hi"); - - sb = new TextStringBuilder(); - sb.append("Hi %s", "Alice"); - assertThat(sb.toString()).isEqualTo("Hi Alice"); - - sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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/TextStringBuilderTest.java b/src/test/java/org/apache/commons/text/TextStringBuilderTest.java deleted file mode 100644 index 8edcbd76d9..0000000000 --- a/src/test/java/org/apache/commons/text/TextStringBuilderTest.java +++ /dev/null @@ -1,2053 +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.apache.commons.text.matcher.StringMatcher; -import org.apache.commons.text.matcher.StringMatcherFactory; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link TextStringBuilder}. - */ -public class TextStringBuilderTest { - - // ----------------------------------------------------------------------- - @Test - public void testConstructors() { - final TextStringBuilder sb0 = new TextStringBuilder(); - assertEquals(32, sb0.capacity()); - assertEquals(0, sb0.length()); - assertEquals(0, sb0.size()); - - final TextStringBuilder sb1 = new TextStringBuilder(32); - assertEquals(32, sb1.capacity()); - assertEquals(0, sb1.length()); - assertEquals(0, sb1.size()); - - final TextStringBuilder sb2 = new TextStringBuilder(0); - assertEquals(32, sb2.capacity()); - assertEquals(0, sb2.length()); - assertEquals(0, sb2.size()); - - final TextStringBuilder sb3 = new TextStringBuilder(-1); - assertEquals(32, sb3.capacity()); - assertEquals(0, sb3.length()); - assertEquals(0, sb3.size()); - - final TextStringBuilder sb4 = new TextStringBuilder(1); - assertEquals(1, sb4.capacity()); - assertEquals(0, sb4.length()); - assertEquals(0, sb4.size()); - - final TextStringBuilder sb5 = new TextStringBuilder((String) null); - assertEquals(32, sb5.capacity()); - assertEquals(0, sb5.length()); - assertEquals(0, sb5.size()); - - final TextStringBuilder sb6 = new TextStringBuilder(""); - assertEquals(32, sb6.capacity()); - assertEquals(0, sb6.length()); - assertEquals(0, sb6.size()); - - final TextStringBuilder sb7 = new TextStringBuilder("foo"); - assertEquals(35, sb7.capacity()); - assertEquals(3, sb7.length()); - assertEquals(3, sb7.size()); - } - - // ----------------------------------------------------------------------- - @Test - public void testChaining() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - assertEquals(0, sb.length()); - - sb.append("Hello"); - assertEquals(5, sb.length()); - } - - @Test - public void testSetLength() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - assertEquals(sb.buffer.length, sb.capacity()); - - sb.append("HelloWorldHelloWorldHelloWorldHelloWorld"); - assertEquals(sb.buffer.length, sb.capacity()); - } - - @Test - public void testEnsureCapacity() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - sb.minimizeCapacity(); - assertEquals(0, sb.capacity()); - - sb.append("HelloWorld"); - sb.minimizeCapacity(); - assertEquals(10, sb.capacity()); - } - - // ----------------------------------------------------------------------- - @Test - public void testSize() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(0, sb.size()); - - sb.append("Hello"); - assertEquals(5, sb.size()); - } - - @Test - public void testIsEmpty() { - final TextStringBuilder sb = new TextStringBuilder(); - assertTrue(sb.isEmpty()); - - sb.append("Hello"); - assertFalse(sb.isEmpty()); - - sb.clear(); - assertTrue(sb.isEmpty()); - } - - @Test - public void testClear() { - final TextStringBuilder sb = new TextStringBuilder(); - sb.append("Hello"); - sb.clear(); - assertEquals(0, sb.length()); - assertTrue(sb.buffer.length >= 5); - } - - // ----------------------------------------------------------------------- - @Test - public void testCharAt() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("abc"); - sb.deleteCharAt(0); - assertEquals("bc", sb.toString()); - - assertThrows(IndexOutOfBoundsException.class, () -> sb.deleteCharAt(1000)); - } - - // ----------------------------------------------------------------------- - @Test - public void testToCharArray() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - - 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 TextStringBuilder sb = new TextStringBuilder(); - - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("anything").delete(2, 1)); - } - - // ----------------------------------------------------------------------- - @Test - public void testDeleteAll_char() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder(""); - sb.deleteAll('b'); - assertEquals("", sb.toString()); - } - - @Test - public void testDeleteFirst_char() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder(""); - sb.deleteFirst('b'); - assertEquals("", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testDeleteAll_String() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("abcbccba"); - sb.deleteAll("bc"); - assertEquals("acba", sb.toString()); - - sb = new TextStringBuilder(""); - sb.deleteAll("bc"); - assertEquals("", sb.toString()); - } - - @Test - public void testDeleteFirst_String() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("abcbccba"); - sb.deleteFirst("bc"); - assertEquals("abccba", sb.toString()); - - sb = new TextStringBuilder(""); - sb.deleteFirst("bc"); - assertEquals("", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testDeleteAll_StringMatcher() { - TextStringBuilder sb = new TextStringBuilder("A0xA1A2yA3"); - sb.deleteAll((StringMatcher) null); - assertEquals("A0xA1A2yA3", sb.toString()); - sb.deleteAll(A_NUMBER_MATCHER); - assertEquals("xy", sb.toString()); - - sb = new TextStringBuilder("Ax1"); - sb.deleteAll(A_NUMBER_MATCHER); - assertEquals("Ax1", sb.toString()); - - sb = new TextStringBuilder(""); - sb.deleteAll(A_NUMBER_MATCHER); - assertEquals("", sb.toString()); - } - - @Test - public void testDeleteFirst_StringMatcher() { - TextStringBuilder sb = new TextStringBuilder("A0xA1A2yA3"); - sb.deleteFirst((StringMatcher) null); - assertEquals("A0xA1A2yA3", sb.toString()); - sb.deleteFirst(A_NUMBER_MATCHER); - assertEquals("xA1A2yA3", sb.toString()); - - sb = new TextStringBuilder("Ax1"); - sb.deleteFirst(A_NUMBER_MATCHER); - assertEquals("Ax1", sb.toString()); - - sb = new TextStringBuilder(""); - sb.deleteFirst(A_NUMBER_MATCHER); - assertEquals("", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReplace_int_int_String() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("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 TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("abcba"); - sb.replaceAll("b", "xbx"); - assertEquals("axbxcxbxa", sb.toString()); - - sb = new TextStringBuilder("bb"); - sb.replaceAll("b", "xbx"); - assertEquals("xbxxbx", sb.toString()); - } - - @Test - public void testReplaceFirst_String_String() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("abcba"); - sb.replaceFirst("b", "xbx"); - assertEquals("axbxcba", sb.toString()); - - sb = new TextStringBuilder("bb"); - sb.replaceFirst("b", "xbx"); - assertEquals("xbxb", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReplaceAll_StringMatcher_String() { - TextStringBuilder sb = new TextStringBuilder("abcbccba"); - sb.replaceAll((StringMatcher) null, null); - assertEquals("abcbccba", sb.toString()); - sb.replaceAll((StringMatcher) null, "anything"); - assertEquals("abcbccba", sb.toString()); - sb.replaceAll(StringMatcherFactory.INSTANCE.noneMatcher(), null); - assertEquals("abcbccba", sb.toString()); - sb.replaceAll(StringMatcherFactory.INSTANCE.noneMatcher(), "anything"); - assertEquals("abcbccba", sb.toString()); - - sb.replaceAll(StringMatcherFactory.INSTANCE.charMatcher('x'), "y"); - assertEquals("abcbccba", sb.toString()); - sb.replaceAll(StringMatcherFactory.INSTANCE.charMatcher('a'), "d"); - assertEquals("dbcbccbd", sb.toString()); - sb.replaceAll(StringMatcherFactory.INSTANCE.charMatcher('d'), null); - assertEquals("bcbccb", sb.toString()); - sb.replaceAll(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "-"); - assertEquals("b-c-", sb.toString()); - - sb = new TextStringBuilder("abcba"); - sb.replaceAll(StringMatcherFactory.INSTANCE.charMatcher('b'), "xbx"); - assertEquals("axbxcxbxa", sb.toString()); - - sb = new TextStringBuilder("bb"); - sb.replaceAll(StringMatcherFactory.INSTANCE.charMatcher('b'), "xbx"); - assertEquals("xbxxbx", sb.toString()); - - sb = new TextStringBuilder("A1-A2A3-A4"); - sb.replaceAll(A_NUMBER_MATCHER, "***"); - assertEquals("***-******-***", sb.toString()); - - sb = new TextStringBuilder("Dear X, hello X."); - sb.replaceAll(StringMatcherFactory.INSTANCE.stringMatcher("X"), "012345678901234567"); - assertEquals("Dear 012345678901234567, hello 012345678901234567.", sb.toString()); - } - - @Test - public void testReplaceFirst_StringMatcher_String() { - TextStringBuilder sb = new TextStringBuilder("abcbccba"); - sb.replaceFirst((StringMatcher) null, null); - assertEquals("abcbccba", sb.toString()); - sb.replaceFirst((StringMatcher) null, "anything"); - assertEquals("abcbccba", sb.toString()); - sb.replaceFirst(StringMatcherFactory.INSTANCE.noneMatcher(), null); - assertEquals("abcbccba", sb.toString()); - sb.replaceFirst(StringMatcherFactory.INSTANCE.noneMatcher(), "anything"); - assertEquals("abcbccba", sb.toString()); - - sb.replaceFirst(StringMatcherFactory.INSTANCE.charMatcher('x'), "y"); - assertEquals("abcbccba", sb.toString()); - sb.replaceFirst(StringMatcherFactory.INSTANCE.charMatcher('a'), "d"); - assertEquals("dbcbccba", sb.toString()); - sb.replaceFirst(StringMatcherFactory.INSTANCE.charMatcher('d'), null); - assertEquals("bcbccba", sb.toString()); - sb.replaceFirst(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "-"); - assertEquals("b-ccba", sb.toString()); - - sb = new TextStringBuilder("abcba"); - sb.replaceFirst(StringMatcherFactory.INSTANCE.charMatcher('b'), "xbx"); - assertEquals("axbxcba", sb.toString()); - - sb = new TextStringBuilder("bb"); - sb.replaceFirst(StringMatcherFactory.INSTANCE.charMatcher('b'), "xbx"); - assertEquals("xbxb", sb.toString()); - - sb = new TextStringBuilder("A1-A2A3-A4"); - sb.replaceFirst(A_NUMBER_MATCHER, "***"); - assertEquals("***-A2A3-A4", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReplace_StringMatcher_String_int_int_int_VaryMatcher() { - TextStringBuilder sb = new TextStringBuilder("abcbccba"); - sb.replace((StringMatcher) null, "x", 0, sb.length(), -1); - assertEquals("abcbccba", sb.toString()); - - sb.replace(StringMatcherFactory.INSTANCE.charMatcher('a'), "x", 0, sb.length(), -1); - assertEquals("xbcbccbx", sb.toString()); - - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "x", 0, sb.length(), -1); - assertEquals("xbxcxx", sb.toString()); - - sb = new TextStringBuilder("A1-A2A3-A4"); - sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); - assertEquals("***-******-***", sb.toString()); - - sb = new TextStringBuilder(); - sb.replace(A_NUMBER_MATCHER, "***", 0, sb.length(), -1); - assertEquals("", sb.toString()); - } - - @Test - public void testReplace_StringMatcher_String_int_int_int_VaryReplace() { - TextStringBuilder sb = new TextStringBuilder("abcbccba"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "cb", 0, sb.length(), -1); - assertEquals("abcbccba", sb.toString()); - - sb = new TextStringBuilder("abcbccba"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "-", 0, sb.length(), -1); - assertEquals("ab-c-a", sb.toString()); - - sb = new TextStringBuilder("abcbccba"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "+++", 0, sb.length(), -1); - assertEquals("ab+++c+++a", sb.toString()); - - sb = new TextStringBuilder("abcbccba"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), "", 0, sb.length(), -1); - assertEquals("abca", sb.toString()); - - sb = new TextStringBuilder("abcbccba"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("cb"), null, 0, sb.length(), -1); - assertEquals("abca", sb.toString()); - } - - @Test - public void testReplace_StringMatcher_String_int_int_int_VaryStartIndex() { - TextStringBuilder sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, sb.length(), -1); - assertEquals("-x--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 1, sb.length(), -1); - assertEquals("aax--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 2, sb.length(), -1); - assertEquals("aax--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 3, sb.length(), -1); - assertEquals("aax--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 4, sb.length(), -1); - assertEquals("aaxa-ay-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 5, sb.length(), -1); - assertEquals("aaxaa-y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 6, sb.length(), -1); - assertEquals("aaxaaaay-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 7, sb.length(), -1); - assertEquals("aaxaaaay-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 8, sb.length(), -1); - assertEquals("aaxaaaay-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 9, sb.length(), -1); - assertEquals("aaxaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 10, sb.length(), -1); - assertEquals("aaxaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - try { - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 11, sb.length(), -1); - fail("Exception expected!"); - } catch (final IndexOutOfBoundsException ex) { - } - assertEquals("aaxaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - try { - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", -1, sb.length(), -1); - fail("Exception expected!"); - } catch (final IndexOutOfBoundsException ex) { - } - assertEquals("aaxaaaayaa", sb.toString()); - } - - @Test - public void testReplace_StringMatcher_String_int_int_int_VaryEndIndex() { - TextStringBuilder sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 0, -1); - assertEquals("aaxaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 2, -1); - assertEquals("-xaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 3, -1); - assertEquals("-xaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 4, -1); - assertEquals("-xaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 5, -1); - assertEquals("-x-aayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 6, -1); - assertEquals("-x-aayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 7, -1); - assertEquals("-x--yaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 8, -1); - assertEquals("-x--yaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 9, -1); - assertEquals("-x--yaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, -1); - assertEquals("-x--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 1000, -1); - assertEquals("-x--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - try { - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 2, 1, -1); - fail("Exception expected!"); - } catch (final IndexOutOfBoundsException ex) { - } - assertEquals("aaxaaaayaa", sb.toString()); - } - - @Test - public void testReplace_StringMatcher_String_int_int_int_VaryCount() { - TextStringBuilder sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, -1); - assertEquals("-x--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 0); - assertEquals("aaxaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 1); - assertEquals("-xaaaayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 2); - assertEquals("-x-aayaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 3); - assertEquals("-x--yaa", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 4); - assertEquals("-x--y-", sb.toString()); - - sb = new TextStringBuilder("aaxaaaayaa"); - sb.replace(StringMatcherFactory.INSTANCE.stringMatcher("aa"), "-", 0, 10, 5); - assertEquals("-x--y-", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testReverse() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals("", sb.reverse().toString()); - - sb.clear().append(true); - assertEquals("eurt", sb.reverse().toString()); - assertEquals("true", sb.reverse().toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testTrim() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("abcdefghijklmnopqrstuvwxyz"); - assertTrue(sb.contains('a')); - assertTrue(sb.contains('o')); - assertTrue(sb.contains('z')); - assertFalse(sb.contains('1')); - } - - @Test - public void testContains_String() { - final TextStringBuilder sb = new TextStringBuilder("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_StringMatcher() { - TextStringBuilder sb = new TextStringBuilder("abcdefghijklmnopqrstuvwxyz"); - assertTrue(sb.contains(StringMatcherFactory.INSTANCE.charMatcher('a'))); - assertTrue(sb.contains(StringMatcherFactory.INSTANCE.stringMatcher("pq"))); - assertTrue(sb.contains(StringMatcherFactory.INSTANCE.charMatcher('z'))); - assertFalse(sb.contains(StringMatcherFactory.INSTANCE.stringMatcher("zy"))); - assertFalse(sb.contains((StringMatcher) null)); - - sb = new TextStringBuilder(); - assertFalse(sb.contains(A_NUMBER_MATCHER)); - sb.append("B A1 C"); - assertTrue(sb.contains(A_NUMBER_MATCHER)); - } - - // ----------------------------------------------------------------------- - @Test - public void testIndexOf_char() { - final TextStringBuilder sb = new TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("xyzabc"); - assertEquals(2, sb.indexOf('z', 0)); - assertEquals(-1, sb.indexOf('z', 3)); - } - - @Test - public void testLastIndexOf_char() { - final TextStringBuilder sb = new TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("xyzabc"); - assertEquals(2, sb.lastIndexOf('z', sb.length())); - assertEquals(-1, sb.lastIndexOf('z', 1)); - } - - // ----------------------------------------------------------------------- - @Test - public void testIndexOf_String() { - final TextStringBuilder sb = new TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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() { - TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("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_StringMatcher() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(-1, sb.indexOf((StringMatcher) null)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'))); - - sb.append("ab bd"); - assertEquals(0, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'))); - assertEquals(1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'))); - assertEquals(2, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher())); - assertEquals(4, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('d'))); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.noneMatcher())); - assertEquals(-1, sb.indexOf((StringMatcher) null)); - - sb.append(" A1 junction"); - assertEquals(6, sb.indexOf(A_NUMBER_MATCHER)); - } - - @Test - public void testIndexOf_StringMatcher_int() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(-1, sb.indexOf((StringMatcher) null, 2)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 2)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 0)); - - sb.append("ab bd"); - assertEquals(0, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), -2)); - assertEquals(0, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 0)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 2)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 20)); - - assertEquals(1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), -1)); - assertEquals(1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 0)); - assertEquals(1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 1)); - assertEquals(3, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 2)); - assertEquals(3, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 3)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 4)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 5)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 6)); - - assertEquals(2, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), -2)); - assertEquals(2, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 0)); - assertEquals(2, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 2)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 4)); - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 20)); - - assertEquals(-1, sb.indexOf(StringMatcherFactory.INSTANCE.noneMatcher(), 0)); - assertEquals(-1, sb.indexOf((StringMatcher) 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_StringMatcher() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(-1, sb.lastIndexOf((StringMatcher) null)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'))); - - sb.append("ab bd"); - assertEquals(0, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'))); - assertEquals(3, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'))); - assertEquals(2, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher())); - assertEquals(4, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('d'))); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.noneMatcher())); - assertEquals(-1, sb.lastIndexOf((StringMatcher) null)); - - sb.append(" A1 junction"); - assertEquals(6, sb.lastIndexOf(A_NUMBER_MATCHER)); - } - - @Test - public void testLastIndexOf_StringMatcher_int() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(-1, sb.lastIndexOf((StringMatcher) null, 2)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 2)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 0)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), -1)); - - sb.append("ab bd"); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), -2)); - assertEquals(0, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 0)); - assertEquals(0, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 2)); - assertEquals(0, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('a'), 20)); - - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), -1)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 0)); - assertEquals(1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 1)); - assertEquals(1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 2)); - assertEquals(3, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 3)); - assertEquals(3, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 4)); - assertEquals(3, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 5)); - assertEquals(3, sb.lastIndexOf(StringMatcherFactory.INSTANCE.charMatcher('b'), 6)); - - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), -2)); - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 0)); - assertEquals(2, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 2)); - assertEquals(2, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 4)); - assertEquals(2, sb.lastIndexOf(StringMatcherFactory.INSTANCE.spaceMatcher(), 20)); - - assertEquals(-1, sb.lastIndexOf(StringMatcherFactory.INSTANCE.noneMatcher(), 0)); - assertEquals(-1, sb.lastIndexOf((StringMatcher) 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 StringMatcher A_NUMBER_MATCHER = new StringMatcher() { - - @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 TextStringBuilder b = new TextStringBuilder(); - b.append("a b "); - final StringTokenizer 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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb1 = new TextStringBuilder(); - final TextStringBuilder sb2 = new TextStringBuilder(); - 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 TextStringBuilder sb1 = new TextStringBuilder(); - final TextStringBuilder sb2 = new TextStringBuilder(); - 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_EqualsWithNullTextStringBuilder() throws Exception { - final TextStringBuilder sb = new TextStringBuilder(); - final TextStringBuilder other = null; - assertFalse(sb.equals(other)); - } - - // ----------------------------------------------------------------------- - @Test - public void testHashCode() { - final TextStringBuilder sb = new TextStringBuilder(); - 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 TextStringBuilder sb = new TextStringBuilder("abc"); - assertEquals("abc", sb.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testToStringBuffer() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(new StringBuffer().toString(), sb.toStringBuffer().toString()); - - sb.append("junit"); - assertEquals(new StringBuffer("junit").toString(), sb.toStringBuffer().toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testToStringBuilder() { - final TextStringBuilder sb = new TextStringBuilder(); - assertEquals(new StringBuilder().toString(), sb.toStringBuilder().toString()); - - sb.append("junit"); - assertEquals(new StringBuilder("junit").toString(), sb.toStringBuilder().toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testLang294() { - final TextStringBuilder sb = new TextStringBuilder("\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 TextStringBuilder sb = new TextStringBuilder("onetwothree"); - sb.deleteFirst("three"); - assertEquals(-1, sb.indexOf("three")); - } - - // ----------------------------------------------------------------------- - @Test - public void testLang295() { - final TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder(); - sb.appendFixedWidthPadRight(null, 10, '*'); - assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadRight correctly"); - } - - @Test - public void testLang412Left() { - final TextStringBuilder sb = new TextStringBuilder(); - sb.appendFixedWidthPadLeft(null, 10, '*'); - assertEquals("**********", sb.toString(), "Failed to invoke appendFixedWidthPadLeft correctly"); - } - - @Test - public void testAsBuilder() { - final TextStringBuilder sb = new TextStringBuilder().appendAll("Lorem", " ", "ipsum", " ", "dolor"); - assertEquals(sb.toString(), sb.build()); - } - - // ----------------------------------------------------------------------- - @Test - public void testAppendCharBuffer() { - final TextStringBuilder sb1 = new TextStringBuilder(); - final CharBuffer buf = CharBuffer.allocate(10); - buf.append("0123456789"); - buf.flip(); - sb1.append(buf); - assertEquals("0123456789", sb1.toString()); - - final TextStringBuilder sb2 = new TextStringBuilder(); - sb2.append(buf, 1, 8); - assertEquals("12345678", sb2.toString()); - } - - // ----------------------------------------------------------------------- - @Test - public void testAppendToWriter() throws Exception { - final TextStringBuilder sb = new TextStringBuilder("1234567890"); - final StringWriter writer = new StringWriter(); - writer.append("Test "); - - sb.appendTo(writer); - - assertEquals("Test 1234567890", writer.toString()); - } - - @Test - public void testAppendToStringBuilder() throws Exception { - final TextStringBuilder sb = new TextStringBuilder("1234567890"); - final StringBuilder builder = new StringBuilder("Test "); - - sb.appendTo(builder); - - assertEquals("Test 1234567890", builder.toString()); - } - - @Test - public void testAppendToStringBuffer() throws Exception { - final TextStringBuilder sb = new TextStringBuilder("1234567890"); - final StringBuffer buffer = new StringBuffer("Test "); - - sb.appendTo(buffer); - - assertEquals("Test 1234567890", buffer.toString()); - } - - @Test - public void testAppendToCharBuffer() throws Exception { - final TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder sb = new TextStringBuilder("1234567890"); - final CharBuffer buffer = null; - sb.append(buffer); - assertEquals("1234567890", sb.toString()); - - final TextStringBuilder sb1 = new TextStringBuilder("1234567890"); - final CharBuffer buffer1 = null; - sb.append(buffer1, 0, 0); - assertEquals("1234567890", sb1.toString()); - } - - @Test - public void testAppendCharBufferException() throws Exception { - final TextStringBuilder sb = new TextStringBuilder("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 TextStringBuilder("test1"); - final CharSequence obj2 = new StringBuilder("test2"); - final CharSequence obj3 = new StringBuffer("test3"); - final CharBuffer obj4 = CharBuffer.wrap("test4".toCharArray()); - - final TextStringBuilder sb0 = new TextStringBuilder(); - assertEquals("", sb0.append(obj0).toString()); - - final TextStringBuilder sb1 = new TextStringBuilder(); - assertEquals("test1", sb1.append(obj1).toString()); - - final TextStringBuilder sb2 = new TextStringBuilder(); - assertEquals("test2", sb2.append(obj2).toString()); - - final TextStringBuilder sb3 = new TextStringBuilder(); - assertEquals("test3", sb3.append(obj3).toString()); - - final TextStringBuilder sb4 = new TextStringBuilder(); - assertEquals("test4", sb4.append(obj4).toString()); - - final TextStringBuilder sb5 = new TextStringBuilder(); - assertEquals("", sb5.append(obj0, 0, 0).toString()); - } - - @Test - public void testAppendStringBuilderNull() { - final TextStringBuilder sb1 = new TextStringBuilder(); - final StringBuilder b = null; - assertEquals("", sb1.append(b).toString()); - - final TextStringBuilder sb2 = new TextStringBuilder(); - assertEquals("", sb2.append(b, 0, 0).toString()); - } - - @Test - public void testAppendln() { - final TextStringBuilder sb1 = new TextStringBuilder(); - 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 TextStringBuilder(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 TextStringBuilder().append(charBuffer, 933, 654); - }); - } - - @Test - public void testDeleteCharAtWithNegative() { - assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(() -> { - new TextStringBuilder().deleteCharAt((-1258)); - }); - } - -} diff --git a/src/test/java/org/apache/commons/text/WordUtilsTest.java b/src/test/java/org/apache/commons/text/WordUtilsTest.java deleted file mode 100644 index f03ba81fc9..0000000000 --- a/src/test/java/org/apache/commons/text/WordUtilsTest.java +++ /dev/null @@ -1,542 +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 java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; - -import org.apache.commons.lang3.StringUtils; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link WordUtils} class. - */ -public class WordUtilsTest { - - // ----------------------------------------------------------------------- - @Test - public void testConstructor() { - assertThat(new WordUtils()).isNotNull(); - final Constructor[] cons = WordUtils.class.getDeclaredConstructors(); - assertThat(cons.length).isEqualTo(1); - assertThat(Modifier.isPublic(cons[0].getModifiers())).isTrue(); - assertThat(Modifier.isPublic(WordUtils.class.getModifiers())).isTrue(); - assertThat(Modifier.isFinal(WordUtils.class.getModifiers())).isFalse(); - } - - // ----------------------------------------------------------------------- - @Test - public void testWrap_StringInt() { - assertThat(WordUtils.wrap(null, 20)).isNull(); - assertThat(WordUtils.wrap(null, -1)).isNull(); - - assertThat(WordUtils.wrap("", 20)).isEqualTo(""); - assertThat(WordUtils.wrap("", -1)).isEqualTo(""); - - // normal - final String systemNewLine = System.lineSeparator(); - String input = "Here is one line of text that is going to be wrapped after 20 columns."; - String expected = "Here is one line of" + systemNewLine + "text that is going" + systemNewLine - + "to be wrapped after" + systemNewLine + "20 columns."; - assertThat(WordUtils.wrap(input, 20)).isEqualTo(expected); - - // long word at end - input = "Click here to jump to the commons website - http://commons.apache.org"; - expected = "Click here to jump" + systemNewLine + "to the commons" + systemNewLine + "website -" + systemNewLine - + "http://commons.apache.org"; - assertThat(WordUtils.wrap(input, 20)).isEqualTo(expected); - - // long word in middle - input = "Click here, http://commons.apache.org, to jump to the commons website"; - expected = "Click here," + systemNewLine + "http://commons.apache.org," + systemNewLine + "to jump to the" - + systemNewLine + "commons website"; - assertThat(WordUtils.wrap(input, 20)).isEqualTo(expected); - - // leading spaces on a new line are stripped - // trailing spaces are not stripped - input = "word1 word2 word3"; - expected = "word1 " + systemNewLine + "word2 " + systemNewLine + "word3"; - assertThat(WordUtils.wrap(input, 7)).isEqualTo(expected); - } - - @Test - public void testWrap_StringIntStringBoolean() { - assertThat(WordUtils.wrap(null, 20, "\n", false)).isNull(); - assertThat(WordUtils.wrap(null, 20, "\n", true)).isNull(); - assertThat(WordUtils.wrap(null, 20, null, true)).isNull(); - assertThat(WordUtils.wrap(null, 20, null, false)).isNull(); - assertThat(WordUtils.wrap(null, -1, null, true)).isNull(); - assertThat(WordUtils.wrap(null, -1, null, false)).isNull(); - - assertThat(WordUtils.wrap("", 20, "\n", false)).isEqualTo(""); - assertThat(WordUtils.wrap("", 20, "\n", true)).isEqualTo(""); - assertThat(WordUtils.wrap("", 20, null, false)).isEqualTo(""); - assertThat(WordUtils.wrap("", 20, null, true)).isEqualTo(""); - assertThat(WordUtils.wrap("", -1, null, false)).isEqualTo(""); - assertThat(WordUtils.wrap("", -1, null, true)).isEqualTo(""); - - // normal - String input = "Here is one line of text that is going to be wrapped after 20 columns."; - String expected = "Here is one line of\ntext that is going\nto be wrapped after\n20 columns."; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - - // unusual newline char - input = "Here is one line of text that is going to be wrapped after 20 columns."; - expected = "Here is one line of
text that is going
to be wrapped after
20 columns."; - assertThat(WordUtils.wrap(input, 20, "
", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, "
", true)).isEqualTo(expected); - - // short line length - input = "Here is one line"; - expected = "Here\nis one\nline"; - assertThat(WordUtils.wrap(input, 6, "\n", false)).isEqualTo(expected); - expected = "Here\nis\none\nline"; - assertThat(WordUtils.wrap(input, 2, "\n", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, -1, "\n", false)).isEqualTo(expected); - - // system newline char - final String systemNewLine = System.lineSeparator(); - input = "Here is one line of text that is going to be wrapped after 20 columns."; - expected = "Here is one line of" + systemNewLine + "text that is going" + systemNewLine + "to be wrapped after" - + systemNewLine + "20 columns."; - assertThat(WordUtils.wrap(input, 20, null, false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, null, true)).isEqualTo(expected); - - // with extra spaces - input = " Here: is one line of text that is going to be wrapped after 20 columns."; - expected = "Here: is one line\nof text that is \ngoing to be \nwrapped after 20 \ncolumns."; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - - // with tab - input = "Here is\tone line of text that is going to be wrapped after 20 columns."; - expected = "Here is\tone line of\ntext that is going\nto be wrapped after\n20 columns."; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - - // with tab at wrapColumn - input = "Here is one line of\ttext that is going to be wrapped after 20 columns."; - expected = "Here is one line\nof\ttext that is\ngoing to be wrapped\nafter 20 columns."; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - - // difference because of long word - input = "Click here to jump to the commons website - http://commons.apache.org"; - expected = "Click here to jump\nto the commons\nwebsite -\nhttp://commons.apache.org"; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - expected = "Click here to jump\nto the commons\nwebsite -\nhttp://commons.apach\ne.org"; - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - - // difference because of long word in middle - input = "Click here, http://commons.apache.org, to jump to the commons website"; - expected = "Click here,\nhttp://commons.apache.org,\nto jump to the\ncommons website"; - assertThat(WordUtils.wrap(input, 20, "\n", false)).isEqualTo(expected); - expected = "Click here,\nhttp://commons.apach\ne.org, to jump to\nthe commons website"; - assertThat(WordUtils.wrap(input, 20, "\n", true)).isEqualTo(expected); - } - - @Test - public void testWrap_StringIntStringBooleanString() { - - // no changes test - String input = "flammable/inflammable"; - String expected = "flammable/inflammable"; - assertThat(WordUtils.wrap(input, 30, "\n", false, "/")).isEqualTo(expected); - - // wrap on / and small width - expected = "flammable\ninflammable"; - assertThat(WordUtils.wrap(input, 2, "\n", false, "/")).isEqualTo(expected); - - // wrap long words on / 1 - expected = "flammable\ninflammab\nle"; - assertThat(WordUtils.wrap(input, 9, "\n", true, "/")).isEqualTo(expected); - - // wrap long words on / 2 - expected = "flammable\ninflammable"; - assertThat(WordUtils.wrap(input, 15, "\n", true, "/")).isEqualTo(expected); - - // wrap long words on / 3 - input = "flammableinflammable"; - expected = "flammableinflam\nmable"; - assertThat(WordUtils.wrap(input, 15, "\n", true, "/")).isEqualTo(expected); - } - - // ----------------------------------------------------------------------- - @Test - public void testCapitalize_String() { - assertThat(WordUtils.capitalize(null)).isNull(); - assertThat(WordUtils.capitalize("")).isEqualTo(""); - assertThat(WordUtils.capitalize(" ")).isEqualTo(" "); - - assertThat(WordUtils.capitalize("I")).isEqualTo("I"); - assertThat(WordUtils.capitalize("i")).isEqualTo("I"); - assertThat(WordUtils.capitalize("i am here 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalize("I Am Here 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalize("i am HERE 123")).isEqualTo("I Am HERE 123"); - assertThat(WordUtils.capitalize("I AM HERE 123")).isEqualTo("I AM HERE 123"); - } - - @Test - public void testCapitalizeWithDelimiters_String() { - assertThat(WordUtils.capitalize(null, null)).isNull(); - assertThat(WordUtils.capitalize("", new char[0])).isEqualTo(""); - assertThat(WordUtils.capitalize(" ", new char[0])).isEqualTo(" "); - - char[] chars = new char[] {'-', '+', ' ', '@'}; - assertThat(WordUtils.capitalize("I", chars)).isEqualTo("I"); - assertThat(WordUtils.capitalize("i", chars)).isEqualTo("I"); - assertThat(WordUtils.capitalize("i-am here+123", chars)).isEqualTo("I-Am Here+123"); - assertThat(WordUtils.capitalize("I Am+Here-123", chars)).isEqualTo("I Am+Here-123"); - assertThat(WordUtils.capitalize("i+am-HERE 123", chars)).isEqualTo("I+Am-HERE 123"); - assertThat(WordUtils.capitalize("I-AM HERE+123", chars)).isEqualTo("I-AM HERE+123"); - chars = new char[] {'.'}; - assertThat(WordUtils.capitalize("i aM.fine", chars)).isEqualTo("I aM.Fine"); - assertThat(WordUtils.capitalize("i am.fine", null)).isEqualTo("I Am.fine"); - } - - @Test - public void testCapitalizeFully_String() { - assertThat(WordUtils.capitalizeFully(null)).isNull(); - assertThat(WordUtils.capitalizeFully("")).isEqualTo(""); - assertThat(WordUtils.capitalizeFully(" ")).isEqualTo(" "); - - assertThat(WordUtils.capitalizeFully("I")).isEqualTo("I"); - assertThat(WordUtils.capitalizeFully("i")).isEqualTo("I"); - assertThat(WordUtils.capitalizeFully("i am here 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalizeFully("I Am Here 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalizeFully("i am HERE 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalizeFully("I AM HERE 123")).isEqualTo("I Am Here 123"); - assertThat(WordUtils.capitalizeFully("alphabet")).isEqualTo("Alphabet"); // single word - } - - @Test - public void testCapitalizeFully_Text88() { - assertThat(WordUtils.capitalizeFully("i am fine now", new char[] {})).isEqualTo("I am fine now"); - } - - @Test - public void testUnCapitalize_Text88() { - assertThat(WordUtils.uncapitalize("I am fine now", new char[] {})).isEqualTo("i am fine now"); - } - - @Test - public void testCapitalizeFullyWithDelimiters_String() { - assertThat(WordUtils.capitalizeFully(null, null)).isNull(); - assertThat(WordUtils.capitalizeFully("", new char[0])).isEqualTo(""); - assertThat(WordUtils.capitalizeFully(" ", new char[0])).isEqualTo(" "); - - char[] chars = new char[] {'-', '+', ' ', '@'}; - assertThat(WordUtils.capitalizeFully("I", chars)).isEqualTo("I"); - assertThat(WordUtils.capitalizeFully("i", chars)).isEqualTo("I"); - assertThat(WordUtils.capitalizeFully("i-am here+123", chars)).isEqualTo("I-Am Here+123"); - assertThat(WordUtils.capitalizeFully("I Am+Here-123", chars)).isEqualTo("I Am+Here-123"); - assertThat(WordUtils.capitalizeFully("i+am-HERE 123", chars)).isEqualTo("I+Am-Here 123"); - assertThat(WordUtils.capitalizeFully("I-AM HERE+123", chars)).isEqualTo("I-Am Here+123"); - chars = new char[] {'.'}; - assertThat(WordUtils.capitalizeFully("i aM.fine", chars)).isEqualTo("I am.Fine"); - assertThat(WordUtils.capitalizeFully("i am.fine", null)).isEqualTo("I Am.fine"); - assertThat(WordUtils.capitalizeFully("alphabet", null)).isEqualTo("Alphabet"); // single word - assertThat(WordUtils.capitalizeFully("alphabet", new char[] {'!'})).isEqualTo("Alphabet"); // no matching delim - } - - @Test - public void testContainsAllWords_StringString() { - assertThat(WordUtils.containsAllWords(null, (String) null)).isFalse(); - assertThat(WordUtils.containsAllWords(null, "")).isFalse(); - assertThat(WordUtils.containsAllWords(null, "ab")).isFalse(); - - assertThat(WordUtils.containsAllWords("", (String) null)).isFalse(); - assertThat(WordUtils.containsAllWords("", "")).isFalse(); - assertThat(WordUtils.containsAllWords("", "ab")).isFalse(); - - assertThat(WordUtils.containsAllWords("foo", (String) null)).isFalse(); - assertThat(WordUtils.containsAllWords("bar", "")).isFalse(); - assertThat(WordUtils.containsAllWords("zzabyycdxx", "by")).isFalse(); - assertThat(WordUtils.containsAllWords("lorem ipsum dolor sit amet", "ipsum", "lorem", "dolor")).isTrue(); - assertThat(WordUtils.containsAllWords("lorem ipsum dolor sit amet", "ipsum", null, "lorem", "dolor")).isFalse(); - assertThat(WordUtils.containsAllWords("lorem ipsum null dolor sit amet", "ipsum", null, "lorem", "dolor")) - .isFalse(); - assertThat(WordUtils.containsAllWords("ab", "b")).isFalse(); - assertThat(WordUtils.containsAllWords("ab", "z")).isFalse(); - } - - @Test - public void testUncapitalize_String() { - assertThat(WordUtils.uncapitalize(null)).isNull(); - assertThat(WordUtils.uncapitalize("")).isEqualTo(""); - assertThat(WordUtils.uncapitalize(" ")).isEqualTo(" "); - - assertThat(WordUtils.uncapitalize("I")).isEqualTo("i"); - assertThat(WordUtils.uncapitalize("i")).isEqualTo("i"); - assertThat(WordUtils.uncapitalize("i am here 123")).isEqualTo("i am here 123"); - assertThat(WordUtils.uncapitalize("I Am Here 123")).isEqualTo("i am here 123"); - assertThat(WordUtils.uncapitalize("i am HERE 123")).isEqualTo("i am hERE 123"); - assertThat(WordUtils.uncapitalize("I AM HERE 123")).isEqualTo("i aM hERE 123"); - } - - @Test - public void testUncapitalizeWithDelimiters_String() { - assertThat(WordUtils.uncapitalize(null, null)).isNull(); - assertThat(WordUtils.uncapitalize("", new char[0])).isEqualTo(""); - assertThat(WordUtils.uncapitalize(" ", new char[0])).isEqualTo(" "); - - char[] chars = new char[] {'-', '+', ' ', '@'}; - assertThat(WordUtils.uncapitalize("I", chars)).isEqualTo("i"); - assertThat(WordUtils.uncapitalize("i", chars)).isEqualTo("i"); - assertThat(WordUtils.uncapitalize("i am-here+123", chars)).isEqualTo("i am-here+123"); - assertThat(WordUtils.uncapitalize("I+Am Here-123", chars)).isEqualTo("i+am here-123"); - assertThat(WordUtils.uncapitalize("i-am+HERE 123", chars)).isEqualTo("i-am+hERE 123"); - assertThat(WordUtils.uncapitalize("I AM-HERE+123", chars)).isEqualTo("i aM-hERE+123"); - chars = new char[] {'.'}; - assertThat(WordUtils.uncapitalize("I AM.FINE", chars)).isEqualTo("i AM.fINE"); - assertThat(WordUtils.uncapitalize("I AM.FINE", null)).isEqualTo("i aM.FINE"); - } - - // ----------------------------------------------------------------------- - @Test - public void testInitials_String() { - assertThat(WordUtils.initials(null)).isNull(); - assertThat(WordUtils.initials("")).isEqualTo(""); - assertThat(WordUtils.initials(" ")).isEqualTo(""); - - assertThat(WordUtils.initials("I")).isEqualTo("I"); - assertThat(WordUtils.initials("i")).isEqualTo("i"); - assertThat(WordUtils.initials("Ben John Lee")).isEqualTo("BJL"); - assertThat(WordUtils.initials(" Ben \n John\tLee\t")).isEqualTo("BJL"); - assertThat(WordUtils.initials("Ben J.Lee")).isEqualTo("BJ"); - assertThat(WordUtils.initials(" Ben John . Lee")).isEqualTo("BJ.L"); - assertThat(WordUtils.initials("i am here 123")).isEqualTo("iah1"); - } - - // ----------------------------------------------------------------------- - @Test - public void testInitials_String_charArray() { - char[] array = null; - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(""); - assertThat(WordUtils.initials("I", array)).isEqualTo("I"); - assertThat(WordUtils.initials("i", array)).isEqualTo("i"); - assertThat(WordUtils.initials("SJC", array)).isEqualTo("S"); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials(" Ben \n John\tLee\t", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo("BJ"); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo("BJ.L"); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo("KO"); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo("iah1"); - - array = new char[0]; - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(""); - assertThat(WordUtils.initials("I", array)).isEqualTo(""); - assertThat(WordUtils.initials("i", array)).isEqualTo(""); - assertThat(WordUtils.initials("SJC", array)).isEqualTo(""); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo(""); - assertThat(WordUtils.initials(" Ben \n John\tLee\t", array)).isEqualTo(""); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo(""); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo(""); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo(""); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo(""); - - array = " ".toCharArray(); - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(""); - assertThat(WordUtils.initials("I", array)).isEqualTo("I"); - assertThat(WordUtils.initials("i", array)).isEqualTo("i"); - assertThat(WordUtils.initials("SJC", array)).isEqualTo("S"); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo("BJ"); - assertThat(WordUtils.initials(" Ben \n John\tLee\t", array)).isEqualTo("B\nJ"); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo("BJ.L"); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo("KO"); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo("iah1"); - - array = " .".toCharArray(); - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(""); - assertThat(WordUtils.initials("I", array)).isEqualTo("I"); - assertThat(WordUtils.initials("i", array)).isEqualTo("i"); - assertThat(WordUtils.initials("SJC", array)).isEqualTo("S"); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo("KO"); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo("iah1"); - - array = " .'".toCharArray(); - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(""); - assertThat(WordUtils.initials("I", array)).isEqualTo("I"); - assertThat(WordUtils.initials("i", array)).isEqualTo("i"); - assertThat(WordUtils.initials("SJC", array)).isEqualTo("S"); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo("BJL"); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo("KOM"); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo("iah1"); - - array = "SIJo1".toCharArray(); - assertThat(WordUtils.initials(null, array)).isNull(); - assertThat(WordUtils.initials("", array)).isEqualTo(""); - assertThat(WordUtils.initials(" ", array)).isEqualTo(" "); - assertThat(WordUtils.initials("I", array)).isEqualTo(""); - assertThat(WordUtils.initials("i", array)).isEqualTo("i"); - assertThat(WordUtils.initials("SJC", array)).isEqualTo("C"); - assertThat(WordUtils.initials("Ben John Lee", array)).isEqualTo("Bh"); - assertThat(WordUtils.initials("Ben J.Lee", array)).isEqualTo("B."); - assertThat(WordUtils.initials(" Ben John . Lee", array)).isEqualTo(" h"); - assertThat(WordUtils.initials("Kay O'Murphy", array)).isEqualTo("K"); - assertThat(WordUtils.initials("i am here 123", array)).isEqualTo("i2"); - } - - @Test - public void testInitialsSurrogatePairs() { - // Tests with space as default delimiter - assertThat(WordUtils.initials("\uD800\uDF00\uD800\uDF01 \uD800\uDF02\uD800\uDF03")) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - assertThat(WordUtils.initials("\uD800\uDF00\uD800\uDF01 \uD800\uDF02\uD800\uDF03", null)) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - assertThat(WordUtils.initials("\uD800\uDF00 \uD800\uDF02 ", null)).isEqualTo("\uD800\uDF00\uD800\uDF02"); - - // Tests with UTF-16 as delimiters - assertThat(WordUtils.initials("\uD800\uDF00\uD800\uDF01.\uD800\uDF02\uD800\uDF03", new char[] {'.'})) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - assertThat(WordUtils.initials("\uD800\uDF00\uD800\uDF01A\uD800\uDF02\uD800\uDF03", new char[] {'A'})) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - - // Tests with UTF-32 as delimiters - assertThat(WordUtils.initials( - "\uD800\uDF00\uD800\uDF01\uD800\uDF14\uD800\uDF02\uD800\uDF03", new char[] {'\uD800', '\uDF14'})) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - assertThat(WordUtils.initials("\uD800\uDF00\uD800\uDF01\uD800\uDF14\uD800\uDF18\uD800\uDF02\uD800\uDF03", - new char[] {'\uD800', '\uDF14', '\uD800', '\uDF18'})) - .isEqualTo("\uD800\uDF00\uD800\uDF02"); - } - - // ----------------------------------------------------------------------- - @Test - public void testSwapCase_String() { - assertThat(WordUtils.swapCase(null)).isNull(); - assertThat(WordUtils.swapCase("")).isEqualTo(""); - assertThat(WordUtils.swapCase(" ")).isEqualTo(" "); - - assertThat(WordUtils.swapCase("I")).isEqualTo("i"); - assertThat(WordUtils.swapCase("i")).isEqualTo("I"); - assertThat(WordUtils.swapCase("i am here 123")).isEqualTo("I AM HERE 123"); - assertThat(WordUtils.swapCase("I Am Here 123")).isEqualTo("i aM hERE 123"); - assertThat(WordUtils.swapCase("i am HERE 123")).isEqualTo("I AM here 123"); - assertThat(WordUtils.swapCase("I AM HERE 123")).isEqualTo("i am here 123"); - - final String test = "This String contains a TitleCase character: \u01C8"; - final String expect = "tHIS sTRING CONTAINS A tITLEcASE CHARACTER: \u01C9"; - assertThat(WordUtils.swapCase(test)).isEqualTo(expect); - } - - // ----------------------------------------------------------------------- - @Test - public void testAbbreviateForNullAndEmptyString() { - assertThat((WordUtils.abbreviate(null, 1, -1, ""))).isNull(); - assertThat(WordUtils.abbreviate("", 1, -1, "")).isEqualTo(StringUtils.EMPTY); - assertThat(WordUtils.abbreviate("0123456790", 0, 0, "")).isEqualTo(""); - assertThat(WordUtils.abbreviate(" 0123456790", 0, -1, "")).isEqualTo(""); - } - - // ----------------------------------------------------------------------- - @Test - public void testAbbreviateForUpperLimit() { - assertThat(WordUtils.abbreviate("0123456789", 0, 5, "")).isEqualTo("01234"); - assertThat(WordUtils.abbreviate("012 3456789", 2, 5, "")).isEqualTo("012"); - assertThat(WordUtils.abbreviate("0123456789", 0, -1, "")).isEqualTo("0123456789"); - } - - // ----------------------------------------------------------------------- - @Test - public void testAbbreviateForUpperLimitAndAppendedString() { - assertThat(WordUtils.abbreviate("0123456789", 0, 5, "-")).isEqualTo("01234-"); - assertThat(WordUtils.abbreviate("012 3456789", 2, 5, null)).isEqualTo("012"); - assertThat(WordUtils.abbreviate("0123456789", 0, -1, "")).isEqualTo("0123456789"); - } - - // ----------------------------------------------------------------------- - @Test - public void testAbbreviateForLowerValue() { - assertThat(WordUtils.abbreviate("012 3456789", 0, 5, null)).isEqualTo("012"); - assertThat(WordUtils.abbreviate("01234 56789", 5, 10, null)).isEqualTo("01234"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, -1, null)).isEqualTo("01 23 45 67"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, 10, null)).isEqualTo("01 23 45 6"); - assertThat(WordUtils.abbreviate("0123456789", 15, 20, null)).isEqualTo("0123456789"); - } - - // ----------------------------------------------------------------------- - @Test - public void testAbbreviateForLowerValueAndAppendedString() { - assertThat(WordUtils.abbreviate("012 3456789", 0, 5, null)).isEqualTo("012"); - assertThat(WordUtils.abbreviate("01234 56789", 5, 10, "-")).isEqualTo("01234-"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, -1, "abc")).isEqualTo("01 23 45 67abc"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, 10, "")).isEqualTo("01 23 45 6"); - } - - @Test - public void testAbbreviateForLowerThanMinusOneValues() { - assertThatIllegalArgumentException().isThrownBy(() -> { - assertThat(WordUtils.abbreviate("01 23 45 67 89", 9, -10, null)).isEqualTo("01 23 45 67"); - }); - } - - @Test - public void testAbbreviateUpperLessThanLowerValues() { - assertThatIllegalArgumentException().isThrownBy(() -> { - assertThat(WordUtils.abbreviate("0123456789", 5, 2, "")).isEqualTo("01234"); - }); - } - - @Test - public void testLANG673() { - assertThat(WordUtils.abbreviate("01 23 45 67 89", 0, 40, "")).isEqualTo("01"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 10, 40, "")).isEqualTo("01 23 45 67"); - assertThat(WordUtils.abbreviate("01 23 45 67 89", 40, 40, "")).isEqualTo("01 23 45 67 89"); - } - - @Test - public void testLANG1292() { - // Prior to fix, this was throwing StringIndexOutOfBoundsException - WordUtils.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " - + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " - + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 70); - } - - @Test - public void testText123() throws Exception { - // Prior to fix, this was throwing StringIndexOutOfBoundsException - WordUtils.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " - + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Integer.MAX_VALUE); - } - - @Test - public void testContainsAllWordsWithNull() { - assertThat(WordUtils.containsAllWords("M", null)).isFalse(); - } - -} diff --git a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java b/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java deleted file mode 100644 index a93b40c363..0000000000 --- a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java +++ /dev/null @@ -1,98 +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.diff; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; - -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Tests for the ReplacementsFinder. - */ -public class ReplacementsFinderTest { - - private SimpleHandler handler = null; - - @BeforeEach - public void setUp() { - handler = new SimpleHandler(); - } - - public static Stream parameters() { - return Stream.of( - Arguments.of( - "branco", - "blanco", - 1, - new Character[] {'r'}, - new Character[] {'l'}), - Arguments.of( - "test the blocks before you use it", - "try the blocks before you put it", - 25, - new Character[] {'e', 's', 't', 's', 'e'}, - new Character[] {'r', 'y', 'p', 't'} - )); - } - - @ParameterizedTest - @MethodSource("parameters") - public void testReplacementsHandler(final String left, final String right, final int skipped, - final Character[] from, final Character[] to) { - final StringsComparator sc = new StringsComparator(left, right); - final ReplacementsFinder replacementFinder = new ReplacementsFinder<>(handler); - sc.getScript().visit(replacementFinder); - assertThat(handler.getSkipped()).as("Skipped characters do not match").isEqualTo(skipped); - assertArrayEquals(handler.getFrom().toArray(new Character[0]), from, "From characters do not match"); - assertArrayEquals(to, handler.getTo().toArray(new Character[0]), "To characters do not match"); - } - - // Helper RecplacementsHandler implementation for testing - private class SimpleHandler implements ReplacementsHandler { - private int skipped; - private final List from; - private final List to; - SimpleHandler() { - skipped = 0; - from = new ArrayList<>(); - to = new ArrayList<>(); - } - public int getSkipped() { - return skipped; - } - public List getFrom() { - return from; - } - public List getTo() { - return to; - } - @Override - public void handleReplacement(final int skipped, final List from, final List to) { - this.skipped += skipped; - this.from.addAll(from); - this.to.addAll(to); - } - } -} diff --git a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java b/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java deleted file mode 100644 index 9e9d266d44..0000000000 --- a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java +++ /dev/null @@ -1,132 +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.diff; -import java.util.Arrays; -import java.util.List; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for the StringsComparator. - */ -public class StringsComparatorTest { - private List before; - private List after; - private int[] length; - private int[] lcs; - - @Test - public void testLength() { - for (int i = 0; i < before.size(); ++i) { - final StringsComparator comparator = new StringsComparator(before.get(i), after.get(i)); - assertThat(comparator.getScript().getModifications()).isEqualTo(length[i]); - } - } - - @Test - public void testLongestCommonSubsequence() { - for (int i = 0; i < before.size(); ++i) { - final StringsComparator comparator = new StringsComparator(before.get(i), after.get(i)); - assertThat(comparator.getScript().getLCSLength()).isEqualTo(lcs[i]); - } - } - - @Test - public void testExecution() { - for (int i = 0; i < before.size(); ++i) { - final ExecutionVisitor ev = new ExecutionVisitor<>(); - new StringsComparator(before.get(i), after.get(i)).getScript().visit(ev); - assertThat(ev.getString()).isEqualTo(after.get(i)); - } - } - - private class ExecutionVisitor implements CommandVisitor { - private final StringBuilder v; - ExecutionVisitor() { - v = new StringBuilder(); - } - @Override - public void visitInsertCommand(final T object) { - v.append(object); - } - @Override - public void visitKeepCommand(final T object) { - v.append(object); - } - @Override - public void visitDeleteCommand(final T object) { - } - public String getString() { - return v.toString(); - } - } - @BeforeEach - public void setUp() { - before = Arrays.asList( - "bottle", - "nematode knowledge", - "", - "aa", - "prefixed string", - "ABCABBA", - "glop glop", - "coq", - "spider-man"); - after = Arrays.asList( - "noodle", - "empty bottle", - "", - "C", - "prefix", - "CBABAC", - "pas glop pas glop", - "ane", - "klingon"); - length = new int[] { - 6, - 16, - 0, - 3, - 9, - 5, - 8, - 6, - 13 - }; - lcs = new int[] { - 3, - 7, - 0, - 0, - 6, - 4, - 9, - 0, - 2 - }; - } - @AfterEach - public void tearDown() { - before = null; - after = null; - length = null; - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/Base64DecoderStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/Base64DecoderStringLookupTest.java deleted file mode 100644 index eb8a744d3d..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/Base64DecoderStringLookupTest.java +++ /dev/null @@ -1,38 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link Base64DecoderStringLookup}. - */ -public class Base64DecoderStringLookupTest { - - @Test - public void test() { - Assertions.assertEquals("HelloWorld!", Base64DecoderStringLookup.INSTANCE.lookup("SGVsbG9Xb3JsZCE=")); - } - - @Test - public void testNull() { - Assertions.assertNull(Base64DecoderStringLookup.INSTANCE.lookup(null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/Base64EncoderStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/Base64EncoderStringLookupTest.java deleted file mode 100644 index 9591e20d30..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/Base64EncoderStringLookupTest.java +++ /dev/null @@ -1,38 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link Base64EncoderStringLookup}. - */ -public class Base64EncoderStringLookupTest { - - @Test - public void test() { - Assertions.assertEquals("SGVsbG9Xb3JsZCE=", Base64EncoderStringLookup.INSTANCE.lookup("HelloWorld!")); - } - - @Test - public void testNull() { - Assertions.assertNull(Base64EncoderStringLookup.INSTANCE.lookup(null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupBasicTest.java b/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupBasicTest.java deleted file mode 100644 index cdbd8071ee..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupBasicTest.java +++ /dev/null @@ -1,61 +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.lookup; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link ConstantStringLookup}. - */ -public class ConstantStringLookupBasicTest { - - /** - * Test fixture. - */ - public static final String STRING_FIXTURE = "Hello World!"; - - /** - * Clears the test environment. Here the static cache of the constant lookup class is wiped out. - */ - @AfterEach - public void afterEach() { - ConstantStringLookup.clear(); - } - - /** - * Clears the test environment. Here the static cache of the constant lookup class is wiped out. - */ - @BeforeEach - public void beforeEach() { - ConstantStringLookup.clear(); - } - - @Test - public void testNull() { - Assertions.assertNull(ConstantStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - Assertions.assertEquals(STRING_FIXTURE, ConstantStringLookup.INSTANCE - .lookup(ConstantStringLookupBasicTest.class.getName() + ".STRING_FIXTURE")); - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupTest.java deleted file mode 100644 index fb1c4ca4fa..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/ConstantStringLookupTest.java +++ /dev/null @@ -1,142 +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.lookup; - -import java.awt.event.KeyEvent; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link ConstantStringLookup}. - *

- * This class was adapted from Apache Commons Configuration. - *

- */ -public class ConstantStringLookupTest { - - /** A public field that can be read by the lookup. */ - public static final String FIELD = "Field that can be read"; - - /** A private field that cannot be read by the lookup. */ - @SuppressWarnings("unused") - private static final String PRIVATE_FIELD = "PRIVATE"; - - /** The lookup object to be tested. */ - private ConstantStringLookup stringLookup; - - /** - * Clears the test environment. Here the static cache of the constant lookup class is wiped out. - */ - @AfterEach - public void afterEach() { - ConstantStringLookup.clear(); - } - - /** - * Clears the test environment. Here the static cache of the constant lookup class is wiped out. - */ - @BeforeEach - public void beforeEach() { - stringLookup = ConstantStringLookup.INSTANCE; - } - - /** - * Tests accessing the cache by querying a variable twice. - */ - @Test - public void testLookupCache() { - testLookupConstant(); - testLookupConstant(); - } - - /** - * Tests resolving a valid constant. - */ - @Test - public void testLookupConstant() { - Assertions.assertEquals(FIELD, stringLookup.lookup(variable("FIELD")), "Wrong value of constant"); - } - - /** - * Tries to resolve a variable with an invalid syntax: The name does not contain a dot as a field separator. - */ - @Test - public void testLookupInvalidSyntax() { - Assertions.assertNull(stringLookup.lookup("InvalidVariableName"), - "Non null return value for invalid variable name"); - } - - /** - * Tests resolving a non existing constant. Result should be null. - */ - @Test - public void testLookupNonExisting() { - Assertions.assertNull(stringLookup.lookup(variable("NO_FIELD")), - "Non null return value for non existing constant"); - } - - /** - * Tests resolving a non string constant. Then looks the same variable up from the cache. - */ - @Test - public void testLookupNonString() { - final String ref = KeyEvent.class.getName() + ".VK_ESCAPE"; - final String expected = Integer.toString(KeyEvent.VK_ESCAPE); - Assertions.assertEquals(expected, stringLookup.lookup(ref), "Wrong result of first lookup"); - Assertions.assertEquals(expected, stringLookup.lookup(ref), "Wrong result of 2nd lookup"); - } - - /** - * Tests looking up a null variable. - */ - @Test - public void testLookupNull() { - Assertions.assertNull(stringLookup.lookup(null), "Non null return value for null variable"); - } - - /** - * Tests resolving a private constant. Because a private field cannot be accessed this should again yield null. - */ - @Test - public void testLookupPrivate() { - Assertions.assertNull(stringLookup.lookup(variable("PRIVATE_FIELD")), - "Non null return value for non accessible field"); - } - - /** - * Tests resolving a field from an unknown class. - */ - @Test - public void testLookupUnknownClass() { - Assertions.assertNull(stringLookup.lookup("org.apache.commons.configuration.NonExistingConfig." + FIELD), - "Non null return value for unknown class"); - } - - /** - * Generates the name of a variable for a lookup operation based on the given field name of this class. - * - * @param field - * the field name - * @return the variable for looking up this field - */ - private String variable(final String field) { - return getClass().getName() + '.' + field; - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java deleted file mode 100644 index 69df25eae4..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/DateStringLookupTest.java +++ /dev/null @@ -1,53 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.junit.jupiter.api.Test; - -/** - * Tests {@link DateStringLookup}. - */ -public class DateStringLookupTest { - - @Test - public void testDefault() throws ParseException { - final String formatted = DateStringLookup.INSTANCE.lookup(null); - DateFormat.getInstance().parse(formatted); // throws ParseException - - } - - @Test - public void testFormat() { - final String fomat = "yyyy-MM-dd"; - final String value = DateStringLookup.INSTANCE.lookup(fomat); - assertNotNull(value, "No Date"); - final SimpleDateFormat format = new SimpleDateFormat(fomat); - final String today = format.format(new Date()); - assertEquals(value, today); - - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/DefaultStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/DefaultStringLookupTest.java deleted file mode 100644 index 3cc9711489..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/DefaultStringLookupTest.java +++ /dev/null @@ -1,70 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertSame; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Test; - -/** - * Tests {@link DefaultStringLookup}. - */ -public class DefaultStringLookupTest { - - @Test - public void testEnumValues() { - final Map stringLookupMap = new HashMap<>(); - StringLookupFactory.INSTANCE.addDefaultStringLookups(stringLookupMap); - // Loop through all enums - for (DefaultStringLookup stringLookup : DefaultStringLookup.values()) { - assertSame(stringLookupMap.get(stringLookup.getKey()), stringLookupMap.get(stringLookup.getKey())); - } - } - - @Test - public void testIndividualEnums() { - assertSame(DefaultStringLookup.BASE64_DECODER.getStringLookup(), - StringLookupFactory.INSTANCE.base64DecoderStringLookup()); - assertSame(DefaultStringLookup.BASE64_ENCODER.getStringLookup(), - StringLookupFactory.INSTANCE.base64EncoderStringLookup()); - assertSame(DefaultStringLookup.CONST.getStringLookup(), StringLookupFactory.INSTANCE.constantStringLookup()); - assertSame(DefaultStringLookup.DATE.getStringLookup(), StringLookupFactory.INSTANCE.dateStringLookup()); - assertSame(DefaultStringLookup.ENVIRONMENT.getStringLookup(), - StringLookupFactory.INSTANCE.environmentVariableStringLookup()); - assertSame(DefaultStringLookup.FILE.getStringLookup(), StringLookupFactory.INSTANCE.fileStringLookup()); - assertSame(DefaultStringLookup.JAVA.getStringLookup(), StringLookupFactory.INSTANCE.javaPlatformStringLookup()); - assertSame(DefaultStringLookup.LOCAL_HOST.getStringLookup(), - StringLookupFactory.INSTANCE.localHostStringLookup()); - assertSame(DefaultStringLookup.PROPERTIES.getStringLookup(), - StringLookupFactory.INSTANCE.propertiesStringLookup()); - assertSame(DefaultStringLookup.RESOURCE_BUNDLE.getStringLookup(), - StringLookupFactory.INSTANCE.resourceBundleStringLookup()); - assertSame(DefaultStringLookup.SCRIPT.getStringLookup(), StringLookupFactory.INSTANCE.scriptStringLookup()); - assertSame(DefaultStringLookup.SYSTEM_PROPERTIES.getStringLookup(), - StringLookupFactory.INSTANCE.systemPropertyStringLookup()); - assertSame(DefaultStringLookup.URL.getStringLookup(), StringLookupFactory.INSTANCE.urlStringLookup()); - assertSame(DefaultStringLookup.URL_DECODER.getStringLookup(), - StringLookupFactory.INSTANCE.urlDecoderStringLookup()); - assertSame(DefaultStringLookup.URL_ENCODER.getStringLookup(), - StringLookupFactory.INSTANCE.urlEncoderStringLookup()); - assertSame(DefaultStringLookup.XML.getStringLookup(), StringLookupFactory.INSTANCE.xmlStringLookup()); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java deleted file mode 100644 index b0a9c33751..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookupTest.java +++ /dev/null @@ -1,45 +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.lookup; - -import org.apache.commons.lang3.SystemUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link EnvironmentVariableStringLookup}. - */ -public class EnvironmentVariableStringLookupTest { - - @Test - public void testNull() { - Assertions.assertNull(EnvironmentVariableStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - if (SystemUtils.IS_OS_WINDOWS) { - final String key = "PATH"; - Assertions.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key)); - } else if (SystemUtils.IS_OS_LINUX) { - final String key = "USER"; - Assertions.assertEquals(System.getenv(key), EnvironmentVariableStringLookup.INSTANCE.lookup(key)); - } - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/FileStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/FileStringLookupTest.java deleted file mode 100644 index 5b51b4badd..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/FileStringLookupTest.java +++ /dev/null @@ -1,60 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link FileStringLookup}. - */ -public class FileStringLookupTest { - - @Test - public void testBadCharsetName() { - assertThrows(IllegalArgumentException.class, () -> { - FileStringLookup.INSTANCE.lookup("BAD_CHARSET_NAME:src/test/resources/document.properties"); - }); - } - - @Test - public void testBadDocumentPath() { - assertThrows(IllegalArgumentException.class, () -> { - FileStringLookup.INSTANCE.lookup("BAD_CHARSET_NAME:src/test/resources/DOCUMENT_NOT_FOUND.TXT"); - }); - } - - @Test - public void testNull() { - Assertions.assertNull(FileStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() throws Exception { - final byte[] expectedBytes = Files.readAllBytes(Paths.get("src/test/resources/document.properties")); - final String expectedString = new String(expectedBytes, StandardCharsets.UTF_8); - Assertions.assertEquals(expectedString, - FileStringLookup.INSTANCE.lookup("UTF-8:src/test/resources/document.properties")); - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java deleted file mode 100644 index 1172523ca6..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/InterpolatorStringLookupTest.java +++ /dev/null @@ -1,112 +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.lookup; - -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.assertNull; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link InterpolatorStringLookup}. - */ -public class InterpolatorStringLookupTest { - - private static final String TESTKEY = "TestKey"; - - private static final String TESTKEY2 = "TestKey2"; - - private static final String TESTVAL = "TestValue"; - - @AfterAll - public static void afterAll() throws Throwable { - System.clearProperty(TESTKEY); - System.clearProperty(TESTKEY2); - } - - @BeforeAll - public static void beforeAll() throws Throwable { - System.setProperty(TESTKEY, TESTVAL); - System.setProperty(TESTKEY2, TESTVAL); - } - - private void assertLookupNotEmpty(final StringLookup lookup, final String key) { - final String value = lookup.lookup(key); - assertNotNull(value); - assertFalse(value.isEmpty()); - System.out.println(key + " = " + value); - } - - @Test - public void testLookup() { - final Map map = new HashMap<>(); - map.put(TESTKEY, TESTVAL); - final StringLookup lookup = new InterpolatorStringLookup(MapStringLookup.on(map)); - String value = lookup.lookup(TESTKEY); - assertEquals(TESTVAL, value); - value = lookup.lookup("ctx:" + TESTKEY); - assertEquals(TESTVAL, value); - value = lookup.lookup("sys:" + TESTKEY); - assertEquals(TESTVAL, value); - value = lookup.lookup("BadKey"); - assertNull(value); - value = lookup.lookup("ctx:" + TESTKEY); - assertEquals(TESTVAL, value); - } - - @Test - public void testLookupKeys() { - final InterpolatorStringLookup lookup = new InterpolatorStringLookup((Map) null); - final Map stringLookupMap = lookup.getStringLookupMap(); - StringLookupFactoryTest.assertDefaultKeys(stringLookupMap); - } - - @Test - public void testLookupWithDefaultInterpolator() { - final StringLookup lookup = new InterpolatorStringLookup(); - String value = lookup.lookup("sys:" + TESTKEY); - assertEquals(TESTVAL, value); - value = lookup.lookup("env:PATH"); - assertNotNull(value); - value = lookup.lookup("date:yyyy-MM-dd"); - assertNotNull(value, "No Date"); - final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - final String today = format.format(new Date()); - assertEquals(value, today); - assertLookupNotEmpty(lookup, "java:version"); - assertLookupNotEmpty(lookup, "java:runtime"); - assertLookupNotEmpty(lookup, "java:vm"); - assertLookupNotEmpty(lookup, "java:os"); - assertLookupNotEmpty(lookup, "java:locale"); - assertLookupNotEmpty(lookup, "java:hardware"); - } - - @Test - public void testNull() { - Assertions.assertNull(InterpolatorStringLookup.INSTANCE.lookup(null)); - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java deleted file mode 100644 index 8cbb54cfe4..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/JavaPlatformStringLookupTest.java +++ /dev/null @@ -1,55 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link JavaPlatformStringLookup}. - */ -public class JavaPlatformStringLookupTest { - - @Test - public void testBadKey() { - assertThrows(IllegalArgumentException.class, () -> { - JavaPlatformStringLookup.INSTANCE.lookup("BADKEY"); - }); - } - - @Test - void testMain() { - JavaPlatformStringLookup.main(ArrayUtils.EMPTY_STRING_ARRAY); - } - - @Test - public void testNull() { - Assertions.assertNull(JavaPlatformStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testVm() { - final String key = "vm"; - assertTrue(JavaPlatformStringLookup.INSTANCE.lookup(key).contains(System.getProperty("java.vm.name"))); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java deleted file mode 100644 index 0d8ade7792..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/LocalHostStringLookupTest.java +++ /dev/null @@ -1,54 +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.lookup; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link LocalHostStringLookup}. - */ -public class LocalHostStringLookupTest { - - @Test - public void testAddress() throws UnknownHostException { - Assertions.assertEquals(InetAddress.getLocalHost().getHostAddress(), - LocalHostStringLookup.INSTANCE.lookup("address")); - } - - @Test - public void testCanonicalName() throws UnknownHostException { - Assertions.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(), - LocalHostStringLookup.INSTANCE.lookup("canonical-name")); - } - - @Test - public void testName() throws UnknownHostException { - Assertions.assertEquals(InetAddress.getLocalHost().getHostName(), - LocalHostStringLookup.INSTANCE.lookup("name")); - } - - @Test - public void testNull() { - Assertions.assertNull(LocalHostStringLookup.INSTANCE.lookup(null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java deleted file mode 100644 index d358b24cba..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/MapStringLookupTest.java +++ /dev/null @@ -1,51 +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.lookup; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link MapStringLookup}. - */ -public class MapStringLookupTest { - - @Test - public void testConcurrentHashMapNull() { - Assertions.assertNull(MapStringLookup.on(new ConcurrentHashMap()).lookup(null)); - } - - @Test - public void testHashMapNull() { - Assertions.assertNull(MapStringLookup.on(new HashMap()).lookup(null)); - } - - @Test - public void testOne() { - final String key = "key"; - final String value = "value"; - final Map map = new HashMap<>(); - map.put(key, value); - Assertions.assertEquals(value, MapStringLookup.on(map).lookup(key)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java deleted file mode 100644 index fa5fc47782..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/NullStringLookupTest.java +++ /dev/null @@ -1,33 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link NullStringLookup}. - */ -public class NullStringLookupTest { - - @Test - public void test() { - Assertions.assertEquals(null, NullStringLookup.INSTANCE.lookup("EverythingIsNull")); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/PropertiesStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/PropertiesStringLookupTest.java deleted file mode 100644 index 69aa78e403..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/PropertiesStringLookupTest.java +++ /dev/null @@ -1,89 +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.lookup; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.text.StringSubstitutor; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link PropertiesStringLookup}. - */ -public class PropertiesStringLookupTest { - - private static final String DOC_PATH = "src/test/resources/document.properties"; - private static final String KEY = "mykey"; - private static final String KEY_PATH = DOC_PATH + "::" + KEY; - - @Test - public void testInterpolator() { - final StringSubstitutor stringSubstitutor = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - Assertions.assertEquals("Hello World!", stringSubstitutor.replace("${properties:" + KEY_PATH + "}")); - } - - @Test - public void testInterpolatorNestedColon() { - final StringSubstitutor stringSubstitutor = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup()); - // Need to handle "C:" in the sys prop user.dir. - final String replaced = stringSubstitutor.replace("$${properties:${sys:user.dir}/" + KEY_PATH + "}"); - Assertions.assertEquals( - "${properties:" + System.getProperty("user.dir") + "/src/test/resources/document.properties::mykey}", - replaced); - Assertions.assertEquals("Hello World!", stringSubstitutor.replace(replaced)); - } - - @Test - public void testInterpolatorWithParameterizedKey() { - final Map map = new HashMap<>(); - map.put("KeyIsHere", KEY); - final StringSubstitutor stringSubstitutor = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup(map)); - final String replaced = stringSubstitutor.replace("$${properties:" + DOC_PATH + "::${KeyIsHere}}"); - Assertions.assertEquals("${properties:" + DOC_PATH + "::mykey}", replaced); - Assertions.assertEquals("Hello World!", stringSubstitutor.replace(replaced)); - } - - @Test - public void testInterpolatorWithParameterizedKey2() { - final Map map = new HashMap<>(); - map.put("KeyIsHere", KEY); - final StringSubstitutor stringSubstitutor = new StringSubstitutor( - StringLookupFactory.INSTANCE.interpolatorStringLookup(map)); - final String replaced = stringSubstitutor - .replace("$${properties:${sys:user.dir}/" + DOC_PATH + "::${KeyIsHere}}"); - Assertions.assertEquals("${properties:" + System.getProperty("user.dir") + "/" + DOC_PATH + "::mykey}", - replaced); - Assertions.assertEquals("Hello World!", stringSubstitutor.replace(replaced)); - } - - @Test - public void testNull() { - Assertions.assertNull(PropertiesStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - Assertions.assertEquals("Hello World!", PropertiesStringLookup.INSTANCE.lookup(KEY_PATH)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java deleted file mode 100644 index 7c30aa73d7..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/ResourceBundleStringLookupTest.java +++ /dev/null @@ -1,82 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.util.ResourceBundle; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link ResourceBundleStringLookup}. - */ -public class ResourceBundleStringLookupTest { - - private static final String TEST_RESOURCE_BUNDLE = "testResourceBundleLookup"; - - @Test - public void testAny() { - final String bundleName = TEST_RESOURCE_BUNDLE; - final String bundleKey = "key"; - Assertions.assertEquals(ResourceBundle.getBundle(bundleName).getString(bundleKey), - ResourceBundleStringLookup.INSTANCE.lookup(bundleName + ":" + bundleKey)); - } - - @Test - public void testBadKey() { - final String bundleName = TEST_RESOURCE_BUNDLE; - final String bundleKey = "bad_key"; - assertThrows(IllegalArgumentException.class, () -> { - new ResourceBundleStringLookup(bundleName).lookup(bundleKey); - }); - assertThrows(IllegalArgumentException.class, () -> { - ResourceBundleStringLookup.INSTANCE.lookup(bundleName + ":" + bundleKey); - }); - } - - @Test - public void testBadName() { - assertThrows(IllegalArgumentException.class, () -> { - ResourceBundleStringLookup.INSTANCE.lookup("BAD_RESOURCE_BUNDLE_NAME:KEY"); - }); - } - - @Test - public void testMissingKeyInSpec() { - final String bundleName = TEST_RESOURCE_BUNDLE; - assertThrows(IllegalArgumentException.class, () -> { - ResourceBundleStringLookup.INSTANCE.lookup(bundleName + ":"); - }); - } - - @Test - public void testNull() { - Assertions.assertNull(ResourceBundleStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - final String bundleName = TEST_RESOURCE_BUNDLE; - final String bundleKey = "key"; - Assertions.assertEquals(ResourceBundle.getBundle(bundleName).getString(bundleKey), - new ResourceBundleStringLookup(bundleName).lookup(bundleKey)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/ScriptStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/ScriptStringLookupTest.java deleted file mode 100644 index 2d8d73a09b..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/ScriptStringLookupTest.java +++ /dev/null @@ -1,61 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link ScriptStringLookup}. - */ -public class ScriptStringLookupTest { - - @Test - public void testBadEngineName() { - assertThrows(IllegalArgumentException.class, () -> { - ScriptStringLookup.INSTANCE.lookup("BAD_ENGINE_NAME:\"Hello World!\""); - }); - } - - @Test - public void testBadScript() { - assertThrows(IllegalArgumentException.class, () -> { - ScriptStringLookup.INSTANCE.lookup("javascript:X"); - }); - } - - @Test - public void testNoScript() { - assertThrows(IllegalArgumentException.class, () -> { - ScriptStringLookup.INSTANCE.lookup("ENGINE_NAME:"); - }); - } - - @Test - public void testNull() { - Assertions.assertNull(ScriptStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - Assertions.assertEquals("Hello World!", ScriptStringLookup.INSTANCE.lookup("javascript:\"Hello World!\"")); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/StringLookupFactoryTest.java b/src/test/java/org/apache/commons/text/lookup/StringLookupFactoryTest.java deleted file mode 100644 index 46893fd4f5..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/StringLookupFactoryTest.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.lookup; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link StringLookupFactory}. - */ -public class StringLookupFactoryTest { - - public static void assertDefaultKeys(final Map stringLookupMap) { - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_BASE64_DECODER)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_BASE64_ENCODER)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_CONST)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_DATE)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_ENV)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_FILE)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_JAVA)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_LOCALHOST)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_PROPERTIES)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_RESOURCE_BUNDLE)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_SCRIPT)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_SYS)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_URL)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_URL_DECODER)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_URL_ENCODER)); - assertTrue(stringLookupMap.containsKey(StringLookupFactory.KEY_XML)); - } - - @Test - public void testAddDefaultStringLookupsMap() { - final Map stringLookupMap = new HashMap<>(); - StringLookupFactory.INSTANCE.addDefaultStringLookups(stringLookupMap); - assertDefaultKeys(stringLookupMap); - } - - @Test - public void testAddDefaultStringLookupsNull() { - StringLookupFactory.INSTANCE.addDefaultStringLookups(null); - } - - /** - * Tests that we return the singleton. - */ - @Test - public void testSingletons() { - final StringLookupFactory stringLookupFactory = StringLookupFactory.INSTANCE; - Assertions.assertSame(Base64DecoderStringLookup.INSTANCE, stringLookupFactory.base64DecoderStringLookup()); - Assertions.assertSame(Base64EncoderStringLookup.INSTANCE, stringLookupFactory.base64EncoderStringLookup()); - Assertions.assertSame(ConstantStringLookup.INSTANCE, stringLookupFactory.constantStringLookup()); - Assertions.assertSame(DateStringLookup.INSTANCE, stringLookupFactory.dateStringLookup()); - Assertions.assertSame(EnvironmentVariableStringLookup.INSTANCE, - stringLookupFactory.environmentVariableStringLookup()); - Assertions.assertSame(InterpolatorStringLookup.INSTANCE, stringLookupFactory.interpolatorStringLookup()); - Assertions.assertSame(JavaPlatformStringLookup.INSTANCE, stringLookupFactory.javaPlatformStringLookup()); - Assertions.assertSame(LocalHostStringLookup.INSTANCE, stringLookupFactory.localHostStringLookup()); - Assertions.assertSame(NullStringLookup.INSTANCE, stringLookupFactory.nullStringLookup()); - Assertions.assertSame(ResourceBundleStringLookup.INSTANCE, stringLookupFactory.resourceBundleStringLookup()); - Assertions.assertSame(ScriptStringLookup.INSTANCE, stringLookupFactory.scriptStringLookup()); - Assertions.assertSame(SystemPropertyStringLookup.INSTANCE, stringLookupFactory.systemPropertyStringLookup()); - Assertions.assertSame(UrlDecoderStringLookup.INSTANCE, stringLookupFactory.urlDecoderStringLookup()); - Assertions.assertSame(UrlEncoderStringLookup.INSTANCE, stringLookupFactory.urlEncoderStringLookup()); - Assertions.assertSame(UrlStringLookup.INSTANCE, stringLookupFactory.urlStringLookup()); - Assertions.assertSame(XmlStringLookup.INSTANCE, stringLookupFactory.xmlStringLookup()); - } -} diff --git a/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java deleted file mode 100644 index 4ab7e6eedd..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/SystemPropertyStringLookupTest.java +++ /dev/null @@ -1,39 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link SystemPropertyStringLookup}. - */ -public class SystemPropertyStringLookupTest { - - @Test - public void testNull() { - Assertions.assertNull(SystemPropertyStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testUserName() { - final String key = "user.name"; - Assertions.assertEquals(System.getProperty(key), SystemPropertyStringLookup.INSTANCE.lookup(key)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/UrlDecoderStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/UrlDecoderStringLookupTest.java deleted file mode 100644 index 49c27dcbbb..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/UrlDecoderStringLookupTest.java +++ /dev/null @@ -1,48 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link UrlDecoderStringLookup}. - */ -public class UrlDecoderStringLookupTest { - - @Test - public void testAllPercent() { - Assertions.assertEquals("Hello World!", UrlDecoderStringLookup.INSTANCE.lookup("Hello%20World%21")); - } - - @Test - public void testExclamation() { - Assertions.assertEquals("Hello World!", UrlDecoderStringLookup.INSTANCE.lookup("Hello%20World!")); - } - - @Test - public void testNull() { - Assertions.assertNull(UrlDecoderStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testPlus() { - Assertions.assertEquals("Hello World!", UrlDecoderStringLookup.INSTANCE.lookup("Hello+World!")); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/UrlEncoderStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/UrlEncoderStringLookupTest.java deleted file mode 100644 index 801fe5989c..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/UrlEncoderStringLookupTest.java +++ /dev/null @@ -1,39 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link UrlEncoderStringLookup}. - */ -public class UrlEncoderStringLookupTest { - - @Test - public void test() { - Assertions.assertEquals("Hello+World%21", UrlEncoderStringLookup.INSTANCE.lookup("Hello World!")); - } - - @Test - public void testNull() { - Assertions.assertNull(UrlEncoderStringLookup.INSTANCE.lookup(null)); - } - - -} diff --git a/src/test/java/org/apache/commons/text/lookup/UrlStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/UrlStringLookupTest.java deleted file mode 100644 index 13be02148f..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/UrlStringLookupTest.java +++ /dev/null @@ -1,70 +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.lookup; - -import static org.junit.jupiter.api.Assertions.assertThrows; - -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link UrlStringLookup}. - */ -public class UrlStringLookupTest { - - @Test - public void testBadCharsetName() { - assertThrows(IllegalArgumentException.class, () -> { - UrlStringLookup.INSTANCE.lookup("BAD_CHARSET_NAME:BAD_URL"); - }); - } - - @Test - public void testBadUrl() { - assertThrows(IllegalArgumentException.class, () -> { - UrlStringLookup.INSTANCE.lookup("UTF-8:BAD_URL"); - }); - } - - @Test - public void testFileScheme() throws Exception { - final Path path = Paths.get("src/test/resources/document.properties"); - final URI uri = path.toUri(); - System.out.println(uri); - final byte[] expectedBytes = Files.readAllBytes(path); - final String expectedString = new String(expectedBytes, StandardCharsets.UTF_8); - Assertions.assertEquals(expectedString, UrlStringLookup.INSTANCE.lookup("UTF-8:" + uri.toString())); - } - - @Test - public void testHttpScheme() throws Exception { - Assertions.assertNotNull(UrlStringLookup.INSTANCE.lookup("UTF-8:http://www.google.com")); - } - - @Test - public void testNull() { - Assertions.assertNull(UrlStringLookup.INSTANCE.lookup(null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/lookup/XmlStringLookupTest.java b/src/test/java/org/apache/commons/text/lookup/XmlStringLookupTest.java deleted file mode 100644 index 41be0f962b..0000000000 --- a/src/test/java/org/apache/commons/text/lookup/XmlStringLookupTest.java +++ /dev/null @@ -1,40 +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.lookup; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * Tests {@link XmlStringLookup}. - */ -public class XmlStringLookupTest { - - @Test - public void testNull() { - Assertions.assertNull(XmlStringLookup.INSTANCE.lookup(null)); - } - - @Test - public void testOne() { - final String docName = "src/test/resources/document.xml"; - final String xpath = "/root/path/to/node"; - Assertions.assertEquals("Hello World!", XmlStringLookup.INSTANCE.lookup(docName + ":" + xpath)); - } - -} diff --git a/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java b/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java deleted file mode 100644 index e4d49024bf..0000000000 --- a/src/test/java/org/apache/commons/text/matcher/StringMatcherTest.java +++ /dev/null @@ -1,219 +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.matcher; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link StringMatcher}. - */ -public class StringMatcherTest { - - 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 StringMatcher matcher = StringMatcherFactory.INSTANCE.commaMatcher(); - assertThat(StringMatcherFactory.INSTANCE.commaMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 0, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 1, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 2, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testTabMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.tabMatcher(); - assertThat(StringMatcherFactory.INSTANCE.tabMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 2, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 3, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 4, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testSpaceMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.spaceMatcher(); - assertThat(StringMatcherFactory.INSTANCE.spaceMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 4, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 5, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 6, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testSplitMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.splitMatcher(); - assertThat(StringMatcherFactory.INSTANCE.splitMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 2, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 3, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 4, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 5, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 6, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 7, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 8, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 9, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 10, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testTrimMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.trimMatcher(); - assertThat(StringMatcherFactory.INSTANCE.trimMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 2, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 3, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 4, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 5, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 6, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 7, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 8, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 9, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 10, 0, BUFFER1.length)).isEqualTo(1); - } - - // ----------------------------------------------------------------------- - @Test - public void testSingleQuoteMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.singleQuoteMatcher(); - assertThat(StringMatcherFactory.INSTANCE.singleQuoteMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 10, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 11, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 12, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testDoubleQuoteMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.doubleQuoteMatcher(); - assertThat(StringMatcherFactory.INSTANCE.doubleQuoteMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 11, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 12, 0, BUFFER1.length)).isEqualTo(1); - } - - // ----------------------------------------------------------------------- - @Test - public void testQuoteMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.quoteMatcher(); - assertThat(StringMatcherFactory.INSTANCE.quoteMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 10, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 11, 0, BUFFER1.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER1, 12, 0, BUFFER1.length)).isEqualTo(1); - } - - // ----------------------------------------------------------------------- - @Test - public void testNoneMatcher() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.noneMatcher(); - assertThat(StringMatcherFactory.INSTANCE.noneMatcher()).isSameAs(matcher); - assertThat(matcher.isMatch(BUFFER1, 0, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 1, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 2, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 3, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 4, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 5, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 6, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 7, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 8, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 9, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 10, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 11, 0, BUFFER1.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER1, 12, 0, BUFFER1.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testCharMatcher_char() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.charMatcher('c'); - assertThat(matcher.isMatch(BUFFER2, 0, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 1, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 2, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 3, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 4, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 5, 0, BUFFER2.length)).isEqualTo(0); - } - - // ----------------------------------------------------------------------- - @Test - public void testCharSetMatcher_String() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.charSetMatcher("ace"); - assertThat(matcher.isMatch(BUFFER2, 0, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 1, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 2, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 3, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 4, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 5, 0, BUFFER2.length)).isEqualTo(0); - assertThat(StringMatcherFactory.INSTANCE.charSetMatcher("")) - .isSameAs(StringMatcherFactory.INSTANCE.noneMatcher()); - assertThat(StringMatcherFactory.INSTANCE.charSetMatcher((String) null)) - .isSameAs(StringMatcherFactory.INSTANCE.noneMatcher()); - assertThat(StringMatcherFactory.INSTANCE.charSetMatcher("a") instanceof AbstractStringMatcher.CharMatcher) - .isTrue(); - } - - // ----------------------------------------------------------------------- - @Test - public void testCharSetMatcher_charArray() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.charSetMatcher("ace".toCharArray()); - assertThat(matcher.isMatch(BUFFER2, 0, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 1, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 2, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 3, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 4, 0, BUFFER2.length)).isEqualTo(1); - assertThat(matcher.isMatch(BUFFER2, 5, 0, BUFFER2.length)).isEqualTo(0); - assertThat(StringMatcherFactory.INSTANCE.charSetMatcher(new char[0])) - .isSameAs(StringMatcherFactory.INSTANCE.noneMatcher()); - assertThat(StringMatcherFactory.INSTANCE.charSetMatcher((char[]) null)) - .isSameAs(StringMatcherFactory.INSTANCE.noneMatcher()); - assertThat(StringMatcherFactory.INSTANCE - .charSetMatcher("a".toCharArray()) instanceof AbstractStringMatcher.CharMatcher).isTrue(); - } - - // ----------------------------------------------------------------------- - @Test - public void testStringMatcher_String() { - final StringMatcher matcher = StringMatcherFactory.INSTANCE.stringMatcher("bc"); - assertThat(matcher.isMatch(BUFFER2, 0, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 1, 0, BUFFER2.length)).isEqualTo(2); - assertThat(matcher.isMatch(BUFFER2, 2, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 3, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 4, 0, BUFFER2.length)).isEqualTo(0); - assertThat(matcher.isMatch(BUFFER2, 5, 0, BUFFER2.length)).isEqualTo(0); - assertThat(StringMatcherFactory.INSTANCE.stringMatcher("")) - .isSameAs(StringMatcherFactory.INSTANCE.noneMatcher()); - assertThat(StringMatcherFactory.INSTANCE.stringMatcher((String) null)) - .isSameAs(StringMatcherFactory.INSTANCE.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 StringMatcher, and are not bugs - final StringMatcher matcher = StringMatcherFactory.INSTANCE.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/matcher/StringSubstitutorGetSetTest.java b/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java deleted file mode 100644 index 244d6b5280..0000000000 --- a/src/test/java/org/apache/commons/text/matcher/StringSubstitutorGetSetTest.java +++ /dev/null @@ -1,99 +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.matcher; - -import static org.junit.jupiter.api.Assertions.assertThrows; -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 org.apache.commons.text.StringSubstitutor; -import org.junit.jupiter.api.Test; - -/** - * Test class for {@link StringSubstitutor}. - */ -public class StringSubstitutorGetSetTest { - - /** - * Tests get set. - */ - @Test - public void testGetSetPrefix() { - final StringSubstitutor sub = new StringSubstitutor(); - assertTrue(sub.getVariablePrefixMatcher() instanceof AbstractStringMatcher.StringMatcher); - sub.setVariablePrefix('<'); - assertTrue(sub.getVariablePrefixMatcher() instanceof AbstractStringMatcher.CharMatcher); - - sub.setVariablePrefix("<<"); - assertTrue(sub.getVariablePrefixMatcher() instanceof AbstractStringMatcher.StringMatcher); - assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefix((String) null)); - assertTrue(sub.getVariablePrefixMatcher() instanceof AbstractStringMatcher.StringMatcher); - - final StringMatcher matcher = StringMatcherFactory.INSTANCE.commaMatcher(); - sub.setVariablePrefixMatcher(matcher); - assertSame(matcher, sub.getVariablePrefixMatcher()); - assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefixMatcher((StringMatcher) null)); - assertSame(matcher, sub.getVariablePrefixMatcher()); - } - - /** - * Tests get set. - */ - @Test - public void testGetSetSuffix() { - final StringSubstitutor sub = new StringSubstitutor(); - assertTrue(sub.getVariableSuffixMatcher() instanceof AbstractStringMatcher.StringMatcher); - sub.setVariableSuffix('<'); - assertTrue(sub.getVariableSuffixMatcher() instanceof AbstractStringMatcher.CharMatcher); - - sub.setVariableSuffix("<<"); - assertTrue(sub.getVariableSuffixMatcher() instanceof AbstractStringMatcher.StringMatcher); - assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffix((String) null)); - assertTrue(sub.getVariableSuffixMatcher() instanceof AbstractStringMatcher.StringMatcher); - - final StringMatcher matcher = StringMatcherFactory.INSTANCE.commaMatcher(); - sub.setVariableSuffixMatcher(matcher); - assertSame(matcher, sub.getVariableSuffixMatcher()); - assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffixMatcher((StringMatcher) null)); - assertSame(matcher, sub.getVariableSuffixMatcher()); - } - - /** - * Tests get set. - */ - @Test - public void testGetSetValueDelimiter() { - final StringSubstitutor sub = new StringSubstitutor(); - assertTrue(sub.getValueDelimiterMatcher() instanceof AbstractStringMatcher.StringMatcher); - sub.setValueDelimiter(':'); - assertTrue(sub.getValueDelimiterMatcher() instanceof AbstractStringMatcher.CharMatcher); - - sub.setValueDelimiter("||"); - assertTrue(sub.getValueDelimiterMatcher() instanceof AbstractStringMatcher.StringMatcher); - sub.setValueDelimiter((String) null); - assertNull(sub.getValueDelimiterMatcher()); - - final StringMatcher matcher = StringMatcherFactory.INSTANCE.commaMatcher(); - sub.setValueDelimiterMatcher(matcher); - assertSame(matcher, sub.getValueDelimiterMatcher()); - sub.setValueDelimiterMatcher((StringMatcher) null); - assertNull(sub.getValueDelimiterMatcher()); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java deleted file mode 100644 index 62a7619649..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java +++ /dev/null @@ -1,71 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.math.BigDecimal; -import java.math.RoundingMode; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link CosineSimilarity}. - */ -public class CosineDistanceTest { - - /** - * Cosine distance under test. - */ - private static CosineDistance cosineDistance; - - /** - * Creates the cosine distance object used throughout the tests. - */ - @BeforeAll - public static void setUp() { - cosineDistance = new CosineDistance(); - } - - /** - * Tests the cosine distance with several inputs. - */ - @Test - public void testCosineDistance() { - assertThat(roundValue(cosineDistance.apply("the house", "da house"))).isEqualTo(Double.valueOf(0.5d)); - assertThat(roundValue(cosineDistance.apply("AB", "AB"))).isEqualTo(Double.valueOf(0.0d)); - assertThat(roundValue(cosineDistance.apply("AB", "BA"))).isEqualTo(Double.valueOf(1.0d)); - assertThat(roundValue(cosineDistance.apply( - "the boy was from tamana shi, kumamoto ken, and the girl was from rio de janeiro, rio", - "the boy was from tamana shi, kumamoto, and the boy was from rio de janeiro, rio de janeiro"))) - .isEqualTo(Double.valueOf(0.08d)); - } - - // --- Utility methods - - /** - * Rounds up a value. - * - * @param value a value - * @return rounded up value - */ - private Double roundValue(final Double value) { - return new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue(); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java deleted file mode 100644 index c229cb5818..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java +++ /dev/null @@ -1,67 +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.similarity; - -import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.within; - - -public class CosineSimilarityTest { - - @Test - public void testCosineSimilarityWithNonEmptyMap() { - final CosineSimilarity cosineSimilarity = new CosineSimilarity(); - final Map hashMap = new HashMap<>(); - final Integer integer = -397; - hashMap.put("3J/$3.L", integer); - final Map hashMapTwo = new HashMap<>(); - - assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMapTwo)).isEqualTo(0.0, within(0.01)); - } - - @Test - public void testCosineSimilarityThrowsIllegalArgumentException() { - assertThatIllegalArgumentException().isThrownBy(() -> { - final CosineSimilarity cosineSimilarity = new CosineSimilarity(); - final Map map = new HashMap<>(); - cosineSimilarity.cosineSimilarity(map, null); - }); - } - - @Test - public void testCosineSimilarityWithNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - final CosineSimilarity cosineSimilarity = new CosineSimilarity(); - cosineSimilarity.cosineSimilarity(null, null); - }); - } - - @Test - public void testCosineSimilarityReturningDoubleWhereByteValueIsZero() { - final CosineSimilarity cosineSimilarity = new CosineSimilarity(); - final Map hashMap = new HashMap<>(); - - assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMap)).isEqualTo(0.0, within(0.01)); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java b/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java deleted file mode 100644 index 53042eb2df..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java +++ /dev/null @@ -1,81 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import java.util.Locale; - -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link FuzzyScore}. - */ -public class FuzzyScoreTest { - - private static final FuzzyScore ENGLISH_SCORE = new FuzzyScore(Locale.ENGLISH); - - @Test - public void testGetFuzzyScore() { - assertThat(ENGLISH_SCORE.fuzzyScore("", "")).isEqualTo(0); - assertThat(ENGLISH_SCORE.fuzzyScore("Workshop", "b")).isEqualTo(0); - assertThat(ENGLISH_SCORE.fuzzyScore("Room", "o")).isEqualTo(1); - assertThat(ENGLISH_SCORE.fuzzyScore("Workshop", "w")).isEqualTo(1); - assertThat(ENGLISH_SCORE.fuzzyScore("Workshop", "ws")).isEqualTo(2); - assertThat(ENGLISH_SCORE.fuzzyScore("Workshop", "wo")).isEqualTo(4); - assertThat(ENGLISH_SCORE.fuzzyScore("Apache Software Foundation", "asf")).isEqualTo(3); - } - - @Test - public void testGetFuzzyScore_StringNullLocale() { - assertThatIllegalArgumentException().isThrownBy(() -> { - ENGLISH_SCORE.fuzzyScore("not null", null); - }); - } - - @Test - public void testGetFuzzyScore_NullStringLocale() { - assertThatIllegalArgumentException().isThrownBy(() -> { - ENGLISH_SCORE.fuzzyScore(null, "not null"); - }); - } - - @Test - public void testGetFuzzyScore_NullNullLocale() { - assertThatIllegalArgumentException().isThrownBy(() -> { - ENGLISH_SCORE.fuzzyScore(null, null); - }); - } - - @Test - public void testMissingLocale() { - assertThatIllegalArgumentException().isThrownBy(() -> { - new FuzzyScore((Locale) null); - }); - } - - @Test - public void testGetLocale() { - final Locale locale = Locale.CANADA_FRENCH; - final FuzzyScore fuzzyScore = new FuzzyScore(locale); - final Locale localeTwo = fuzzyScore.getLocale(); - - assertThat(localeTwo).isSameAs(locale); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java deleted file mode 100644 index edad76af96..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/HammingDistanceTest.java +++ /dev/null @@ -1,63 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link HammingDistance}. - */ -public class HammingDistanceTest { - - private static HammingDistance distance; - - @BeforeAll - public static void setUp() { - distance = new HammingDistance(); - } - - @Test - public void testHammingDistance() { - assertThat(distance.apply("", "")).isEqualTo(0); - assertThat(distance.apply("pappa", "pappa")).isEqualTo(0); - assertThat(distance.apply("papaa", "pappa")).isEqualTo(1); - assertThat(distance.apply("karolin", "kathrin")).isEqualTo(3); - assertThat(distance.apply("karolin", "kerstin")).isEqualTo(3); - assertThat(distance.apply("1011101", "1001001")).isEqualTo(2); - assertThat(distance.apply("2173896", "2233796")).isEqualTo(3); - assertThat(distance.apply("ATCG", "ACCC")).isEqualTo(2); - } - - @Test - public void testHammingDistance_nullLeftValue() { - assertThatIllegalArgumentException().isThrownBy(() -> { - distance.apply(null, ""); - }); - } - - @Test - public void testHammingDistance_nullRightValue() { - assertThatIllegalArgumentException().isThrownBy(() -> { - distance.apply("", null); - }); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java deleted file mode 100644 index 56d4909dbb..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java +++ /dev/null @@ -1,76 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link JaccardDistance}. - */ -public class JaccardDistanceTest { - - private static JaccardDistance classBeingTested; - - @BeforeAll - public static void setUp() { - classBeingTested = new JaccardDistance(); - } - - @Test - public void testGettingJaccardDistance() { - assertEquals(1.00d, classBeingTested.apply("", ""), 0.00000000000000000001d); - assertEquals(1.00d, classBeingTested.apply("left", ""), 0.00000000000000000001d); - assertEquals(1.00d, classBeingTested.apply("", "right"), 0.00000000000000000001d); - assertEquals(0.25d, classBeingTested.apply("frog", "fog"), 0.00000000000000000001d); - assertEquals(1.00d, classBeingTested.apply("fly", "ant"), 0.00000000000000000001d); - assertEquals(0.78d, classBeingTested.apply("elephant", "hippo"), 0.00000000000000000001d); - assertEquals(0.36d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.00000000000000000001d); - assertEquals(0.24d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), - 0.00000000000000000001d); - assertEquals(0.11d, classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"), - 0.00000000000000000001d); - assertEquals(0.10d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.00000000000000000001d); - assertEquals(0.87d, classBeingTested.apply("left", "right"), 0.00000000000000000001d); - assertEquals(0.87d, classBeingTested.apply("leettteft", "ritttght"), 0.00000000000000000001d); - assertEquals(0.0d, classBeingTested.apply("the same string", "the same string"), 0.00000000000000000001d); - } - - @Test - public void testGettingJaccardDistanceNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(null, null); - }); - } - - @Test - public void testGettingJaccardDistanceStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(" ", null); - }); - } - - @Test - public void testGettingJaccardDistanceNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(null, "right"); - }); - } -} diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java deleted file mode 100644 index c96d6d3f82..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java +++ /dev/null @@ -1,76 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link JaccardSimilarity}. - */ -public class JaccardSimilarityTest { - - private static JaccardSimilarity classBeingTested; - - @BeforeAll - public static void setUp() { - classBeingTested = new JaccardSimilarity(); - } - - @Test - public void testGettingJaccardSimilarity() { - assertEquals(0.00d, classBeingTested.apply("", ""), 0.00000000000000000001d); - assertEquals(0.00d, classBeingTested.apply("left", ""), 0.00000000000000000001d); - assertEquals(0.00d, classBeingTested.apply("", "right"), 0.00000000000000000001d); - assertEquals(0.75d, classBeingTested.apply("frog", "fog"), 0.00000000000000000001d); - assertEquals(0.00d, classBeingTested.apply("fly", "ant"), 0.00000000000000000001d); - assertEquals(0.22d, classBeingTested.apply("elephant", "hippo"), 0.00000000000000000001d); - assertEquals(0.64d, classBeingTested.apply("ABC Corporation", "ABC Corp"), 0.00000000000000000001d); - assertEquals(0.76d, classBeingTested.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), - 0.00000000000000000001d); - assertEquals(0.89d, classBeingTested.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"), - 0.00000000000000000001d); - assertEquals(0.9d, classBeingTested.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.00000000000000000001d); - assertEquals(0.13d, classBeingTested.apply("left", "right"), 0.00000000000000000001d); - assertEquals(0.13d, classBeingTested.apply("leettteft", "ritttght"), 0.00000000000000000001d); - assertEquals(1.0d, classBeingTested.apply("the same string", "the same string"), 0.00000000000000000001d); - } - - @Test - public void testGettingJaccardSimilarityNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(null, null); - }); - } - - @Test - public void testGettingJaccardSimilarityStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(" ", null); - }); - } - - @Test - public void testGettingJaccardSimilarityNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> { - classBeingTested.apply(null, "right"); - }); - } -} diff --git a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java deleted file mode 100644 index d6bfda04b8..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java +++ /dev/null @@ -1,73 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.junit.jupiter.api.Assertions.assertEquals; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link JaroWinklerDistance}. - */ -public class JaroWinklerDistanceTest { - - private static JaroWinklerDistance distance; - - @BeforeAll - public static void setUp() { - distance = new JaroWinklerDistance(); - } - - @Test - public void testGetJaroWinklerDistance_StringString() { - assertEquals(0.92499d, distance.apply("frog", "fog"), 0.00001d); - assertEquals(0.0d, distance.apply("fly", "ant"), 0.00000000000000000001d); - assertEquals(0.44166d, distance.apply("elephant", "hippo"), 0.00001d); - assertEquals(0.90666d, distance.apply("ABC Corporation", "ABC Corp"), 0.00001d); - assertEquals(0.95251d, distance.apply("D N H Enterprises Inc", "D & H Enterprises, Inc."), 0.00001d); - assertEquals(0.942d, - distance.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness"), 0.00001d); - assertEquals(0.898018d, distance.apply("PENNSYLVANIA", "PENNCISYLVNIA"), 0.00001d); - assertEquals(0.971428d, distance.apply("/opt/software1", "/opt/software2"), 0.00001d); - assertEquals(0.941666d, distance.apply("aaabcd", "aaacdb"), 0.00001d); - assertEquals(0.911111d, distance.apply("John Horn", "John Hopkins"), 0.00001d); - } - - @Test - public void testGetJaroWinklerDistance_NullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - distance.apply(null, null); - }); - } - - @Test - public void testGetJaroWinklerDistance_StringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> { - distance.apply(" ", null); - }); - } - - @Test - public void testGetJaroWinklerDistance_NullString() { - assertThatIllegalArgumentException().isThrownBy(() -> { - distance.apply(null, "clear"); - }); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java deleted file mode 100644 index 1641cbb39e..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java +++ /dev/null @@ -1,462 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import org.apache.commons.text.TextStringBuilder; -import org.junit.jupiter.api.Test; - -public class LevenshteinDetailedDistanceTest { - - private static final LevenshteinDetailedDistance UNLIMITED_DISTANCE = new LevenshteinDetailedDistance(); - - @Test - public void testGetLevenshteinDetailedDistance_StringString() { - LevenshteinResults result = UNLIMITED_DISTANCE.apply("", ""); - assertThat(result.getDistance()).isEqualTo(0); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = UNLIMITED_DISTANCE.apply("", "a"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(1); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = UNLIMITED_DISTANCE.apply("aaapppp", ""); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(7); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = UNLIMITED_DISTANCE.apply("frog", "fog"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(1); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = UNLIMITED_DISTANCE.apply("fly", "ant"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(3); - - result = UNLIMITED_DISTANCE.apply("elephant", "hippo"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = UNLIMITED_DISTANCE.apply("hippo", "elephant"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = UNLIMITED_DISTANCE.apply("hippo", "zzzzzzzz"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = UNLIMITED_DISTANCE.apply("zzzzzzzz", "hippo"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = UNLIMITED_DISTANCE.apply("hello", "hallo"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(1); - } - - @Test - public void testEquals() { - final LevenshteinDetailedDistance classBeingTested = new LevenshteinDetailedDistance(); - LevenshteinResults actualResult = classBeingTested.apply("hello", "hallo"); - LevenshteinResults expectedResult = new LevenshteinResults(1, 0, 0, 1); - assertThat(expectedResult).isEqualTo(actualResult); - - actualResult = classBeingTested.apply("zzzzzzzz", "hippo"); - expectedResult = new LevenshteinResults(8, 0, 3, 5); - assertThat(expectedResult).isEqualTo(actualResult); - assertThat(actualResult).isEqualTo(actualResult); //intentionally added - - actualResult = classBeingTested.apply("", ""); - expectedResult = new LevenshteinResults(0, 0, 0, 0); - assertThat(expectedResult).isEqualTo(actualResult); - } - - @Test - public void testHashCode() { - final LevenshteinDetailedDistance classBeingTested = new LevenshteinDetailedDistance(); - LevenshteinResults actualResult = classBeingTested.apply("aaapppp", ""); - LevenshteinResults expectedResult = new LevenshteinResults(7, 0, 7, 0); - assertThat(expectedResult.hashCode()).isEqualTo(actualResult.hashCode()); - - actualResult = classBeingTested.apply("frog", "fog"); - expectedResult = new LevenshteinResults(1, 0, 1, 0); - assertThat(expectedResult.hashCode()).isEqualTo(actualResult.hashCode()); - - actualResult = classBeingTested.apply("elephant", "hippo"); - expectedResult = new LevenshteinResults(7, 0, 3, 4); - assertThat(expectedResult.hashCode()).isEqualTo(actualResult.hashCode()); - } - - @Test - public void testToString() { - final LevenshteinDetailedDistance classBeingTested = new LevenshteinDetailedDistance(); - LevenshteinResults actualResult = classBeingTested.apply("fly", "ant"); - LevenshteinResults expectedResult = new LevenshteinResults(3, 0, 0, 3); - assertThat(expectedResult.toString()).isEqualTo(actualResult.toString()); - - actualResult = classBeingTested.apply("hippo", "elephant"); - expectedResult = new LevenshteinResults(7, 3, 0, 4); - assertThat(expectedResult.toString()).isEqualTo(actualResult.toString()); - - actualResult = classBeingTested.apply("", "a"); - expectedResult = new LevenshteinResults(1, 1, 0, 0); - assertThat(expectedResult.toString()).isEqualTo(actualResult.toString()); - } - - @Test - public void testGetLevenshteinDetailedDistance_NullString() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null)); - } - - @Test - public void testGetLevenshteinDetailedDistance_StringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a")); - } - - @Test - public void testGetLevenshteinDetailedDistance_StringStringInt() { - - LevenshteinResults result = new LevenshteinDetailedDistance(0).apply("", ""); - - assertThat(result.getDistance()).isEqualTo(0); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(8).apply("aaapppp", ""); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(7); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(7).apply("aaapppp", ""); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(7); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(6).apply("aaapppp", ""); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(0).apply("b", "a"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(0).apply("a", "b"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(0).apply("aa", "aa"); - assertThat(result.getDistance()).isEqualTo(0); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(2).apply("aa", "aa"); - assertThat(result.getDistance()).isEqualTo(0); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(2).apply("aaa", "bbb"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(3).apply("aaa", "bbb"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(3); - - result = new LevenshteinDetailedDistance(10).apply("aaaaaa", "b"); - assertThat(result.getDistance()).isEqualTo(6); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(5); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(8).apply("aaapppp", "b"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(6); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(4).apply("a", "bbb"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(2); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(7).apply("aaapppp", "b"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(6); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(3).apply("a", "bbb"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(2); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(2).apply("a", "bbb"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(2).apply("bbb", "a"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(6).apply("aaapppp", "b"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(1).apply("a", "bbb"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(1).apply("bbb", "a"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(1).apply("12345", "1234567"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(1).apply("1234567", "12345"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(1).apply("frog", "fog"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(1); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(3).apply("fly", "ant"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(3); - - result = new LevenshteinDetailedDistance(7).apply("elephant", "hippo"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = new LevenshteinDetailedDistance(6).apply("elephant", "hippo"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(7).apply("hippo", "elephant"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = new LevenshteinDetailedDistance(7).apply("hippo", "elephant"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = new LevenshteinDetailedDistance(6).apply("hippo", "elephant"); - assertThat(result.getDistance()).isEqualTo(-1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(8).apply("hippo", "zzzzzzzz"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = new LevenshteinDetailedDistance(8).apply("zzzzzzzz", "hippo"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = new LevenshteinDetailedDistance(1).apply("hello", "hallo"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(1); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("frog", "fog"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(1); - assertThat(result.getSubstituteCount()).isEqualTo(0); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("fly", "ant"); - assertThat(result.getDistance()).isEqualTo(3); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(3); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("elephant", "hippo"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("hippo", "elephant"); - assertThat(result.getDistance()).isEqualTo(7); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(4); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("hippo", "zzzzzzzz"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(3); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("zzzzzzzz", "hippo"); - assertThat(result.getDistance()).isEqualTo(8); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(3); - assertThat(result.getSubstituteCount()).isEqualTo(5); - - result = new LevenshteinDetailedDistance(Integer.MAX_VALUE).apply("hello", "hallo"); - assertThat(result.getDistance()).isEqualTo(1); - assertThat(result.getInsertCount()).isEqualTo(0); - assertThat(result.getDeleteCount()).isEqualTo(0); - assertThat(result.getSubstituteCount()).isEqualTo(1); - } - - @Test - public void testGetLevenshteinDetailedDistance_NullStringInt() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a")); - } - - @Test - public void testGetLevenshteinDetailedDistance_StringNullInt() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null)); - } - - @Test - public void testConstructorWithNegativeThreshold() { - assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(-1)); - } - - @Test - public void testGetDefaultInstanceOne() { - final LevenshteinDetailedDistance levenshteinDetailedDistance = - LevenshteinDetailedDistance.getDefaultInstance(); - final LevenshteinResults levenshteinResults = - levenshteinDetailedDistance.apply("Distance: -2147483643, Insert: 0, Delete: 0, Substitute: 0", - "Distance: 0, Insert: 2147483536, Delete: 0, Substitute: 0"); - - assertThat(levenshteinResults.getDistance()).isEqualTo(21); - } - - @Test - public void testGetDefaultInstanceTwo() { - final LevenshteinDetailedDistance levenshteinDetailedDistance = - LevenshteinDetailedDistance.getDefaultInstance(); - final LevenshteinResults levenshteinResults = - levenshteinDetailedDistance.apply("Distance: 2147483647, Insert: 0, Delete: 0, Substitute: 0", - "Distance: 0, Insert: 2147483647, Delete: 0, Substitute: 0"); - - assertThat(levenshteinResults.getDistance()).isEqualTo(20); - } - - @Test - public void testCreatesLevenshteinDetailedDistanceTakingInteger6() { - final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0); - final LevenshteinResults levenshteinResults = - levenshteinDetailedDistance.apply("", "Distance: 38, Insert: 0, Delete: 0, Substitute: 0"); - - assertThat(levenshteinResults.getSubstituteCount()).isEqualTo(0); - assertThat(levenshteinResults.getDeleteCount()).isEqualTo(0); - - assertThat(levenshteinResults.getInsertCount()).isEqualTo(0); - assertThat(levenshteinResults.getDistance()).isEqualTo(-1); - } - - @Test - public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDetailedDistanceTakingInteger() { - assertThatIllegalArgumentException().isThrownBy(() -> { - final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0); - final CharSequence charSequence = new TextStringBuilder(); - - levenshteinDetailedDistance.apply(charSequence, null); - }); - } - - @Test - public void testApplyWithNull() { - assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(0).apply(null, null)); - } - - @Test - public void testGetThreshold() { - final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0); - - assertThat(levenshteinDetailedDistance.getThreshold()).isEqualTo(0); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java deleted file mode 100644 index 45ee27e21b..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java +++ /dev/null @@ -1,144 +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.similarity; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Unit tests for {@link LevenshteinDistance}. - */ -public class LevenshteinDistanceTest { - - private static final LevenshteinDistance UNLIMITED_DISTANCE = new LevenshteinDistance(); - - @Test - public void testGetLevenshteinDistance_StringString() { - assertThat(UNLIMITED_DISTANCE.apply("", "")).isEqualTo(0); - assertThat(UNLIMITED_DISTANCE.apply("", "a")).isEqualTo(1); - assertThat(UNLIMITED_DISTANCE.apply("aaapppp", "")).isEqualTo(7); - assertThat(UNLIMITED_DISTANCE.apply("frog", "fog")).isEqualTo(1); - assertThat(UNLIMITED_DISTANCE.apply("fly", "ant")).isEqualTo(3); - assertThat(UNLIMITED_DISTANCE.apply("elephant", "hippo")).isEqualTo(7); - assertThat(UNLIMITED_DISTANCE.apply("hippo", "elephant")).isEqualTo(7); - assertThat(UNLIMITED_DISTANCE.apply("hippo", "zzzzzzzz")).isEqualTo(8); - assertThat(UNLIMITED_DISTANCE.apply("zzzzzzzz", "hippo")).isEqualTo(8); - assertThat(UNLIMITED_DISTANCE.apply("hello", "hallo")).isEqualTo(1); - } - - @Test - public void testGetLevenshteinDistance_NullString() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null)); - } - - @Test - public void testGetLevenshteinDistance_StringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a")); - } - - @Test - public void testGetLevenshteinDistance_StringStringInt() { - // empty strings - assertThat(new LevenshteinDistance(0).apply("", "")).isEqualTo(0); - assertThat(new LevenshteinDistance(8).apply("aaapppp", "")).isEqualTo(7); - assertThat(new LevenshteinDistance(7).apply("aaapppp", "")).isEqualTo(7); - assertThat(new LevenshteinDistance(6).apply("aaapppp", "")).isEqualTo(-1); - - // unequal strings, zero threshold - assertThat(new LevenshteinDistance(0).apply("b", "a")).isEqualTo(-1); - assertThat(new LevenshteinDistance(0).apply("a", "b")).isEqualTo(-1); - - // equal strings - assertThat(new LevenshteinDistance(0).apply("aa", "aa")).isEqualTo(0); - assertThat(new LevenshteinDistance(2).apply("aa", "aa")).isEqualTo(0); - - // same length - assertThat(new LevenshteinDistance(2).apply("aaa", "bbb")).isEqualTo(-1); - assertThat(new LevenshteinDistance(3).apply("aaa", "bbb")).isEqualTo(3); - - // big stripe - assertThat(new LevenshteinDistance(10).apply("aaaaaa", "b")).isEqualTo(6); - - // distance less than threshold - assertThat(new LevenshteinDistance(8).apply("aaapppp", "b")).isEqualTo(7); - assertThat(new LevenshteinDistance(4).apply("a", "bbb")).isEqualTo(3); - - // distance equal to threshold - assertThat(new LevenshteinDistance(7).apply("aaapppp", "b")).isEqualTo(7); - assertThat(new LevenshteinDistance(3).apply("a", "bbb")).isEqualTo(3); - - // distance greater than threshold - assertThat(new LevenshteinDistance(2).apply("a", "bbb")).isEqualTo(-1); - assertThat(new LevenshteinDistance(2).apply("bbb", "a")).isEqualTo(-1); - assertThat(new LevenshteinDistance(6).apply("aaapppp", "b")).isEqualTo(-1); - - // stripe runs off array, strings not similar - assertThat(new LevenshteinDistance(1).apply("a", "bbb")).isEqualTo(-1); - assertThat(new LevenshteinDistance(1).apply("bbb", "a")).isEqualTo(-1); - - // stripe runs off array, strings are similar - assertThat(new LevenshteinDistance(1).apply("12345", "1234567")).isEqualTo(-1); - assertThat(new LevenshteinDistance(1).apply("1234567", "12345")).isEqualTo(-1); - - // old getLevenshteinDistance test cases - assertThat(new LevenshteinDistance(1).apply("frog", "fog")).isEqualTo(1); - assertThat(new LevenshteinDistance(3).apply("fly", "ant")).isEqualTo(3); - assertThat(new LevenshteinDistance(7).apply("elephant", "hippo")).isEqualTo(7); - assertThat(new LevenshteinDistance(6).apply("elephant", "hippo")).isEqualTo(-1); - assertThat(new LevenshteinDistance(7).apply("hippo", "elephant")).isEqualTo(7); - assertThat(new LevenshteinDistance(6).apply("hippo", "elephant")).isEqualTo(-1); - assertThat(new LevenshteinDistance(8).apply("hippo", "zzzzzzzz")).isEqualTo(8); - assertThat(new LevenshteinDistance(8).apply("zzzzzzzz", "hippo")).isEqualTo(8); - assertThat(new LevenshteinDistance(1).apply("hello", "hallo")).isEqualTo(1); - - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("frog", "fog")).isEqualTo(1); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("fly", "ant")).isEqualTo(3); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("elephant", "hippo")).isEqualTo(7); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("hippo", "elephant")).isEqualTo(7); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("hippo", "zzzzzzzz")).isEqualTo(8); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("zzzzzzzz", "hippo")).isEqualTo(8); - assertThat(new LevenshteinDistance(Integer.MAX_VALUE).apply("hello", "hallo")).isEqualTo(1); - } - - @Test - public void testGetLevenshteinDistance_NullStringInt() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a")); - } - - @Test - public void testGetLevenshteinDistance_StringNullInt() { - assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null)); - } - - @Test - public void testConstructorWithNegativeThreshold() { - assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(-1)); - } - - @Test - public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDistanceTakingInteger() { - assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(0).apply(null, null)); - } - - @Test - public void testGetThresholdDirectlyAfterObjectInstantiation() { - assertThat(new LevenshteinDistance().getThreshold()).isNull(); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java deleted file mode 100644 index 3c113c6c5b..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java +++ /dev/null @@ -1,71 +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.similarity; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LevenshteinResultsTest { - - @Test - public void testEqualsReturningFalse() { - final Integer integerOne = 1662; - final Integer integerTwo = 1164; - final LevenshteinResults levenshteinResults = - new LevenshteinResults(integerOne, integerOne, integerOne, integerOne); - final LevenshteinResults levenshteinResultsTwo = - new LevenshteinResults(integerOne, integerOne, integerTwo, integerTwo); - - assertThat(levenshteinResults.equals(levenshteinResultsTwo)).isFalse(); - } - - @Test - public void testEqualsWithNonNull() { - final Integer integer = 1; - final LevenshteinResults levenshteinResults = new LevenshteinResults(null, integer, integer, null); - final LevenshteinResults levenshteinResultsTwo = new LevenshteinResults(null, null, null, null); - - assertThat(levenshteinResults.equals(levenshteinResultsTwo)).isFalse(); - } - - @Test - public void testEqualsWithNull() { - final Integer integer = -647; - final LevenshteinResults levenshteinResults = new LevenshteinResults(integer, null, null, integer); - - assertThat(levenshteinResults.equals(null)).isFalse(); - } - - @Test - public void testEqualsDifferenceInSubstitutionCount() { - final Integer integer = 1662; - final LevenshteinResults levenshteinResults = new LevenshteinResults(integer, integer, integer, integer); - final LevenshteinResults levenshteinResultsTwo = new LevenshteinResults(integer, integer, integer, null); - - assertThat(levenshteinResults.equals(levenshteinResultsTwo)).isFalse(); - } - - @Test - public void testEqualsSameObject() { - final Integer integer = 1662; - final LevenshteinResults levenshteinResults = new LevenshteinResults(integer, integer, integer, null); - - assertThat(levenshteinResults.equals(levenshteinResults)).isTrue(); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java deleted file mode 100644 index b0a8977912..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java +++ /dev/null @@ -1,69 +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.similarity; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Unit tests for {@link LongestCommonSubsequenceDistance}. - */ -public class LongestCommonSubsequenceDistanceTest { - - private static LongestCommonSubsequenceDistance subject; - - @BeforeAll - public static void setup() { - subject = new LongestCommonSubsequenceDistance(); - } - - @Test - public void testGettingLogestCommonSubsequenceDistacne() { - assertThat(subject.apply("", "")).isEqualTo(0); - assertThat(subject.apply("left", "")).isEqualTo(4); - assertThat(subject.apply("", "right")).isEqualTo(5); - assertThat(subject.apply("frog", "fog")).isEqualTo(1); - assertThat(subject.apply("fly", "ant")).isEqualTo(6); - assertThat(subject.apply("elephant", "hippo")).isEqualTo(11); - assertThat(subject.apply("ABC Corporation", "ABC Corp")).isEqualTo(7); - assertThat(subject.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.")).isEqualTo(4); - assertThat(subject.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")).isEqualTo(9); - assertThat(subject.apply("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo(3); - assertThat(subject.apply("left", "right")).isEqualTo(7); - assertThat(subject.apply("leettteft", "ritttght")).isEqualTo(9); - assertThat(subject.apply("the same string", "the same string")).isEqualTo(0); - } - - @Test - public void testGettingLongestCommonSubsequenceDistanceNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null)); - } - - @Test - public void testGettingLongestCommonSubsequenceDistanceStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null)); - } - - @Test - public void testGettingLongestCommonSubsequenceDistanceNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right")); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java deleted file mode 100644 index 19b73a4e46..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java +++ /dev/null @@ -1,140 +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.similarity; - -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Unit tests for {@link LongestCommonSubsequence}. - */ -public class LongestCommonSubsequenceTest { - - private static LongestCommonSubsequence subject; - - @BeforeAll - public static void setup() { - subject = new LongestCommonSubsequence(); - } - - @Test - public void testLongestCommonSubsequenceApply() { - assertThat(subject.apply("", "")).isEqualTo(0); - assertThat(subject.apply("left", "")).isEqualTo(0); - assertThat(subject.apply("", "right")).isEqualTo(0); - assertThat(subject.apply("frog", "fog")).isEqualTo(3); - assertThat(subject.apply("fly", "ant")).isEqualTo(0); - assertThat(subject.apply("elephant", "hippo")).isEqualTo(1); - assertThat(subject.apply("ABC Corporation", "ABC Corp")).isEqualTo(8); - assertThat(subject.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.")).isEqualTo(20); - assertThat(subject.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")).isEqualTo(24); - assertThat(subject.apply("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo(11); - assertThat(subject.apply("left", "right")).isEqualTo(1); - assertThat(subject.apply("leettteft", "ritttght")).isEqualTo(4); - assertThat(subject.apply("the same string", "the same string")).isEqualTo(15); - } - - @Test - public void testGettingLongestCommonSubsequenceApplyNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null)); - } - - @Test - public void testGettingLongestCommonSubsequenceApplyStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null)); - } - - @Test - public void testGettingLongestCommonSubsequenceApplyNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right")); - } - - @Test - public void testLongestCommonSubsequence() { - assertThat(subject.longestCommonSubsequence("", "")).isEqualTo(""); - assertThat(subject.longestCommonSubsequence("left", "")).isEqualTo(""); - assertThat(subject.longestCommonSubsequence("", "right")).isEqualTo(""); - assertThat(subject.longestCommonSubsequence("frog", "fog")).isEqualTo("fog"); - assertThat(subject.longestCommonSubsequence("fly", "ant")).isEqualTo(""); - assertThat(subject.longestCommonSubsequence("elephant", "hippo")).isEqualTo("h"); - assertThat(subject.longestCommonSubsequence("ABC Corporation", "ABC Corp")).isEqualTo("ABC Corp"); - assertThat(subject.longestCommonSubsequence("D N H Enterprises Inc", "D & H Enterprises, Inc.")) - .isEqualTo("D H Enterprises Inc"); - assertThat(subject.longestCommonSubsequence("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")) - .isEqualTo("My Gym Childrens Fitness"); - assertThat(subject.longestCommonSubsequence("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo("PENNSYLVNIA"); - assertThat(subject.longestCommonSubsequence("left", "right")).isEqualTo("t"); - assertThat(subject.longestCommonSubsequence("leettteft", "ritttght")).isEqualTo("tttt"); - assertThat(subject.longestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string"); - } - - @Test - public void testGettingLongestCommonSubsequenceNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, null)); - } - - @Test - public void testGettingLongestCommonSubsequenceStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(" ", null)); - } - - @Test - public void testGettingLongestCommonSubsequenceNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, "right")); - } - - @Test - @Deprecated - public void testLogestCommonSubsequence() { - assertThat(subject.logestCommonSubsequence("", "")).isEqualTo(""); - assertThat(subject.logestCommonSubsequence("left", "")).isEqualTo(""); - assertThat(subject.logestCommonSubsequence("", "right")).isEqualTo(""); - assertThat(subject.logestCommonSubsequence("frog", "fog")).isEqualTo("fog"); - assertThat(subject.logestCommonSubsequence("fly", "ant")).isEqualTo(""); - assertThat(subject.logestCommonSubsequence("elephant", "hippo")).isEqualTo("h"); - assertThat(subject.logestCommonSubsequence("ABC Corporation", "ABC Corp")).isEqualTo("ABC Corp"); - assertThat(subject.logestCommonSubsequence("D N H Enterprises Inc", "D & H Enterprises, Inc.")) - .isEqualTo("D H Enterprises Inc"); - assertThat(subject.logestCommonSubsequence("My Gym Children's Fitness Center", "My Gym. Childrens Fitness")) - .isEqualTo("My Gym Childrens Fitness"); - assertThat(subject.logestCommonSubsequence("PENNSYLVANIA", "PENNCISYLVNIA")).isEqualTo("PENNSYLVNIA"); - assertThat(subject.logestCommonSubsequence("left", "right")).isEqualTo("t"); - assertThat(subject.logestCommonSubsequence("leettteft", "ritttght")).isEqualTo("tttt"); - assertThat(subject.logestCommonSubsequence("the same string", "the same string")).isEqualTo("the same string"); - } - - @Test - @SuppressWarnings("deprecation") - public void testGettingLogestCommonSubsequenceNullNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, null)); - } - - @Test - @SuppressWarnings("deprecation") - public void testGettingLogestCommonSubsequenceStringNull() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(" ", null)); - } - - @Test - @SuppressWarnings("deprecation") - public void testGettingLogestCommonSubsequenceNullString() { - assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, "right")); - } -} diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java deleted file mode 100644 index 7322d99d94..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/ParameterizedEditDistanceFromTest.java +++ /dev/null @@ -1,69 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - - -/** - * Unit tests for {@link EditDistanceFrom}. - * - * @param The {@link EditDistance} return type. - */ -public class ParameterizedEditDistanceFromTest { - - public static Stream parameters() { - return Stream.of( - Arguments.of(new HammingDistance(), "Sam I am.", "Ham I am.", 1), - Arguments.of(new HammingDistance(), "Japtheth, Ham, Shem", "Japtheth, HAM, Shem", 2), - Arguments.of(new HammingDistance(), "Hamming", "Hamming", 0), - - Arguments.of(new LevenshteinDistance(), "Apache", "a patchy", 4), - Arguments.of(new LevenshteinDistance(), "go", "no go", 3), - Arguments.of(new LevenshteinDistance(), "go", "go", 0), - - Arguments.of(new LevenshteinDistance(4), "Apache", "a patchy", 4), - Arguments.of(new LevenshteinDistance(4), "go", "no go", 3), - Arguments.of(new LevenshteinDistance(0), "go", "go", 0), - - Arguments.of( - new EditDistance() { - @Override - public Boolean apply(final CharSequence left, final CharSequence right) { - return left == right || (left != null && left.equals(right)); - } - }, - "Bob's your uncle.", - "Every good boy does fine.", - false)); - } - - @ParameterizedTest - @MethodSource("parameters") - public void test(final EditDistance editDistance, final CharSequence left, final CharSequence right, - final R distance) { - final EditDistanceFrom editDistanceFrom = new EditDistanceFrom<>(editDistance, left); - assertThat(editDistanceFrom.apply(right)).isEqualTo(distance); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java deleted file mode 100644 index 0c7367d2ef..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/ParameterizedLevenshteinDistanceTest.java +++ /dev/null @@ -1,104 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Unit tests for {@link LevenshteinDistance}. - */ -public class ParameterizedLevenshteinDistanceTest { - - public static Stream parameters() { - return Stream.of( - /* empty strings */ - Arguments.of(0, "", "", 0), - Arguments.of(8, "aaapppp", "", 7), - Arguments.of(7, "aaapppp", "", 7), - Arguments.of(6, "aaapppp", "", -1), - - /* unequal strings, zero threshold */ - Arguments.of(0, "b", "a", -1), - Arguments.of(0, "a", "b", -1), - - /* equal strings */ - Arguments.of(0, "aa", "aa", 0), - Arguments.of(2, "aa", "aa", 0), - - /* same length */ - Arguments.of(2, "aaa", "bbb", -1), - Arguments.of(3, "aaa", "bbb", 3), - - /* big stripe */ - Arguments.of(10, "aaaaaa", "b", 6), - - /* distance less than threshold */ - Arguments.of(8, "aaapppp", "b", 7), - Arguments.of(4, "a", "bbb", 3), - - /* distance equal to threshold */ - Arguments.of(7, "aaapppp", "b", 7), - Arguments.of(3, "a", "bbb", 3), - - /* distance greater than threshold */ - Arguments.of(2, "a", "bbb", -1), - Arguments.of(2, "bbb", "a", -1), - Arguments.of(6, "aaapppp", "b", -1), - - /* stripe runs off array, strings not similar */ - Arguments.of(1, "a", "bbb", -1), - Arguments.of(1, "bbb", "a", -1), - - /* stripe runs off array, strings are similar */ - Arguments.of(1, "12345", "1234567", -1), - Arguments.of(1, "1234567", "12345", -1), - - /* old getLevenshteinDistance test cases */ - Arguments.of(1, "frog", "fog", 1), - Arguments.of(3, "fly", "ant", 3), - Arguments.of(7, "elephant", "hippo", 7), - Arguments.of(6, "elephant", "hippo", -1), - Arguments.of(7, "hippo", "elephant", 7), - Arguments.of(6, "hippo", "elephant", -1), - Arguments.of(8, "hippo", "zzzzzzzz", 8), - Arguments.of(8, "zzzzzzzz", "hippo", 8), - Arguments.of(1, "hello", "hallo", 1), - - Arguments.of(Integer.MAX_VALUE, "frog", "fog", 1), - Arguments.of(Integer.MAX_VALUE, "fly", "ant", 3), - Arguments.of(Integer.MAX_VALUE, "elephant", "hippo", 7), - Arguments.of(Integer.MAX_VALUE, "hippo", "elephant", 7), - Arguments.of(Integer.MAX_VALUE, "hippo", "zzzzzzzz", 8), - Arguments.of(Integer.MAX_VALUE, "zzzzzzzz", "hippo", 8), - Arguments.of(Integer.MAX_VALUE, "hello", "hallo", 1)); - } - - @ParameterizedTest - @MethodSource("parameters") - public void test(final Integer threshold, final CharSequence left, final CharSequence right, - final Integer distance) { - final LevenshteinDistance metric = new LevenshteinDistance(threshold); - assertThat(metric.apply(left, right)).isEqualTo(distance); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java b/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java deleted file mode 100644 index 3022ed5094..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/ParameterizedSimilarityScoreFromTest.java +++ /dev/null @@ -1,60 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.stream.Stream; - -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * Unit tests for {@link SimilarityScoreFrom}. - * - * @param The {@link SimilarityScore} return type. - */ -public class ParameterizedSimilarityScoreFromTest { - - public static Stream parameters() { - return Stream.of( - Arguments.of(new LevenshteinDistance(), "elephant", "hippo", 7), - Arguments.of(new LevenshteinDistance(), "hippo", "elephant", 7), - Arguments.of(new LevenshteinDistance(), "hippo", "zzzzzzzz", 8), - - Arguments.of( - new SimilarityScore() { - @Override - public Boolean apply(final CharSequence left, final CharSequence right) { - return left == right || (left != null && left.equals(right)); - } - }, - "Bob's your uncle.", - "Every good boy does fine.", - false - )); - } - - @ParameterizedTest - @MethodSource("parameters") - public void test(final SimilarityScore similarityScore, final CharSequence left, final CharSequence right, - final R distance) { - final SimilarityScoreFrom similarityScoreFrom = new SimilarityScoreFrom<>(similarityScore, left); - assertThat(similarityScoreFrom.apply(right)).isEqualTo(distance); - } -} diff --git a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java b/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java deleted file mode 100644 index 59ad8d0a58..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java +++ /dev/null @@ -1,41 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import org.junit.jupiter.api.Test; - -public class SimilarityScoreFromTest { - - @Test - public void testFailsToCreateSimilarityScoreFromThrowsIllegalArgumentException() { - assertThatIllegalArgumentException().isThrownBy(() -> new SimilarityScoreFrom<>(null, "")); - } - - @Test - public void testApply() { - final LongestCommonSubsequence longestCommonSubsequence = new LongestCommonSubsequence(); - final SimilarityScoreFrom similarityScoreFrom = - new SimilarityScoreFrom<>(longestCommonSubsequence, "asdf"); - - assertThat(similarityScoreFrom.apply("s")).isEqualTo(1); - } - -} diff --git a/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java b/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java deleted file mode 100644 index 34609f7182..0000000000 --- a/src/test/java/org/apache/commons/text/similarity/StringMetricFromTest.java +++ /dev/null @@ -1,66 +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.similarity; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link EditDistanceFrom}. - */ -public class StringMetricFromTest { - - @Test - public void testEquivalence() { - final EditDistance metric = new LevenshteinDistance(); - final String left = "Apache"; - final String right = "a patchy"; - final Integer distance = 4; - final EditDistanceFrom metricFrom = new EditDistanceFrom<>(metric, left); - - assertThat(metricFrom.apply(right)).isEqualTo(distance); - assertThat(metricFrom.apply(right)).isEqualTo(metric.apply(left, right)); - } - - @Test - public void testJavadocExample() { - final EditDistance metric = new LevenshteinDistance(); - final String target = "Apache"; - final EditDistanceFrom metricFrom = - new EditDistanceFrom<>(metric, target); - String mostSimilar = null; - Integer shortestDistance = null; - - for (final String test : new String[] {"Appaloosa", "a patchy", "apple" }) { - final Integer distance = metricFrom.apply(test); - if (shortestDistance == null || distance < shortestDistance) { - shortestDistance = distance; - mostSimilar = test; - } - } - assertThat(mostSimilar).isEqualTo("a patchy"); - assertThat(shortestDistance).isEqualTo(4); - } - - @Test - public void testMissingMetric() { - assertThatIllegalArgumentException().isThrownBy(() -> new EditDistanceFrom(null, "no go")); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java deleted file mode 100644 index fba9516554..0000000000 --- a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java +++ /dev/null @@ -1,66 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link AggregateTranslator}. - */ -public class AggregateTranslatorTest { - - @Test - public void testNullConstructor() { - final String testString = "foo"; - final AggregateTranslator subject = new AggregateTranslator((CharSequenceTranslator[]) null); - assertThat(subject.translate(testString)).isEqualTo(testString); - } - - @Test - public void testNullVarargConstructor() { - final String testString = "foo"; - final AggregateTranslator subject = new AggregateTranslator((CharSequenceTranslator) null); - assertThat(subject.translate(testString)).isEqualTo(testString); - } - - @Test - public void testNonNull() throws IOException { - final Map oneTwoMap = new HashMap<>(); - oneTwoMap.put("one", "two"); - final Map threeFourMap = new HashMap<>(); - threeFourMap.put("three", "four"); - final CharSequenceTranslator translator1 = new LookupTranslator(oneTwoMap); - final CharSequenceTranslator translator2 = new LookupTranslator(threeFourMap); - final AggregateTranslator subject = new AggregateTranslator(translator1, translator2); - final StringWriter out1 = new StringWriter(); - final int result1 = subject.translate(new StringBuffer("one"), 0, out1); - assertThat(result1).as("Incorrect codepoint consumption").isEqualTo(3); - assertThat(out1.toString()).as("Incorrect value").isEqualTo("two"); - final StringWriter out2 = new StringWriter(); - final int result2 = subject.translate(new StringBuffer("three"), 0, out2); - assertThat(result2).as("Incorrect codepoint consumption").isEqualTo(5); - assertThat(out2.toString()).as("Incorrect value").isEqualTo("four"); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java deleted file mode 100644 index 3adbc8ec62..0000000000 --- a/src/test/java/org/apache/commons/text/translate/CodePointTranslatorTest.java +++ /dev/null @@ -1,40 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.PipedReader; -import java.io.PipedWriter; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CodePointTranslatorTest { - - @Test - public void testAboveReturningNonNull() throws IOException { - final NumericEntityEscaper numericEntityEscaper = NumericEntityEscaper.above(0); - final UnicodeEscaper unicodeEscaper = new UnicodeEscaper(); - final String string = unicodeEscaper.toUtf16Escape(0); - final PipedReader pipedReader = new PipedReader(); - final PipedWriter pipedWriter = new PipedWriter(pipedReader); - - assertThat(numericEntityEscaper.translate(string, 0, pipedWriter)).isEqualTo(1); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java b/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java deleted file mode 100644 index ab7393fceb..0000000000 --- a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java +++ /dev/null @@ -1,130 +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.translate; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - -import org.apache.commons.lang3.CharUtils; -import org.junit.jupiter.api.Test; - -public class CsvTranslatorsTest { - - @Test - public void csvEscaperPlaneTextTest() throws IOException { - final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper(); - final Writer writer = new StringWriter(); - final String input = "hi this is just a plane text nothing to do with csv!"; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(input).isEqualTo(data); - } - - @Test - public void csvEscaperCommaTest() throws IOException { - final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,a,test"; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("\"hi,this,is,a,test\""); - } - - @Test - public void csvEscaperQuoteTest() throws IOException { - final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,a,\"quote,test"; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("\"hi,this,is,a,\"\"quote,test\""); - } - - @Test - public void csvEscaperCRTest() throws IOException { - final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,a,CR,test" + String.valueOf(CharUtils.CR); - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("\"hi,this,is,a,CR,test" + String.valueOf(CharUtils.CR) + "\""); - } - - @Test - public void csvEscaperLFTest() throws IOException { - final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,a,LF,test" + String.valueOf(CharUtils.LF); - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("\"hi,this,is,a,LF,test" + String.valueOf(CharUtils.LF) + "\""); - } - - @Test - public void csvUnEscaperPlaneTextTest() throws IOException { - final CsvTranslators.CsvUnescaper escaper = new CsvTranslators.CsvUnescaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,unescape,test"; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("hi,this,is,unescape,test"); - } - - @Test - public void csvUnEscaperTest1() throws IOException { - final CsvTranslators.CsvUnescaper escaper = new CsvTranslators.CsvUnescaper(); - final Writer writer = new StringWriter(); - final String input = "\"hi,this,is,unescape,test\""; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("hi,this,is,unescape,test"); - } - - @Test - public void csvUnEscaperTest2() throws IOException { - final CsvTranslators.CsvUnescaper escaper = new CsvTranslators.CsvUnescaper(); - final Writer writer = new StringWriter(); - final String input = "\"hi,this,is,unescape,test"; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(input).isEqualTo(data); - } - - @Test - public void csvUnEscaperTest3() throws IOException { - final CsvTranslators.CsvUnescaper escaper = new CsvTranslators.CsvUnescaper(); - final Writer writer = new StringWriter(); - final String input = "hi,this,is,unescape,test\""; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(input).isEqualTo(data); - } - - @Test - public void csvUnEscaperTest4() throws IOException { - final CsvTranslators.CsvUnescaper escaper = new CsvTranslators.CsvUnescaper(); - final Writer writer = new StringWriter(); - final String input = "\"hi,this,is,\"unescape,test\""; - escaper.translateWhole(input, writer); - final String data = writer.toString(); - assertThat(data).isEqualTo("hi,this,is,\"unescape,test"); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java b/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java deleted file mode 100644 index 49528d0464..0000000000 --- a/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java +++ /dev/null @@ -1,132 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link EntityArrays}. - */ -public class EntityArraysTest { - - @Test - public void testConstructorExists() { - new EntityArrays(); - } - - // LANG-659, LANG-658 - avoid duplicate entries - @Test - public void testForDuplicatedDeclaredMapKeys() throws Exception { - final String packageDirectory = EntityArraysTest.class.getPackage().getName().replace(".", "/"); - try (BufferedReader br = new BufferedReader(new FileReader("src/main/java/" + packageDirectory - + "/EntityArrays.java"))) { - String line; - int mapDeclarationCounter = 0; - while ((line = br.readLine()) != null) { - //Start with map declaration and count put lines - if (line.contains("new HashMap<>();")) { - mapDeclarationCounter = 0; - } else if (line.contains(".put(")) { - mapDeclarationCounter++; - } else if (line.contains("Collections.unmodifiableMap(initialMap);")) { - final String mapVariableName = line.split("=")[0].trim(); - @SuppressWarnings("unchecked") // This is test code - final - Map mapValue = (Map) - EntityArrays.class.getDeclaredField(mapVariableName).get(EntityArrays.class); - // Validate that we are not inserting into the same key twice in the map declaration. If this, - // indeed was the case the keySet().size() would be smaller than the number of put() statements - assertThat(mapValue.keySet().size()).isEqualTo(mapDeclarationCounter); - } - } - } - } - - @Test - public void testForDuplicateDeclaredMapValuesISO8859Map() { - assertThat(EntityArrays.ISO8859_1_ESCAPE.keySet()).hasSameSizeAs( - EntityArrays.ISO8859_1_UNESCAPE.keySet()); - } - - @Test - public void testISO8859Map() { - testEscapeVsUnescapeMaps(EntityArrays.ISO8859_1_ESCAPE, EntityArrays.ISO8859_1_UNESCAPE); - } - - @Test - public void testForDuplicateDeclaredMapValuesHtml40ExtendedMap() { - assertThat(EntityArrays.HTML40_EXTENDED_ESCAPE.keySet()).hasSameSizeAs( - EntityArrays.HTML40_EXTENDED_UNESCAPE.keySet()); - } - - @Test - public void testHtml40ExtendedMap() { - testEscapeVsUnescapeMaps(EntityArrays.HTML40_EXTENDED_ESCAPE, EntityArrays.HTML40_EXTENDED_UNESCAPE); - } - - @Test - public void testForDuplicateDeclaredMapValuesAposMap() { - assertThat(EntityArrays.APOS_ESCAPE.keySet()).hasSameSizeAs( - EntityArrays.APOS_UNESCAPE.keySet()); - } - - @Test - public void testAposMap() { - testEscapeVsUnescapeMaps(EntityArrays.APOS_ESCAPE, EntityArrays.APOS_UNESCAPE); - } - - @Test - public void testForDuplicateDeclaredMapValuesBasicMap() { - assertThat(EntityArrays.BASIC_ESCAPE.keySet()).hasSameSizeAs( - EntityArrays.BASIC_UNESCAPE.keySet()); - } - - @Test - public void testBasicMap() { - testEscapeVsUnescapeMaps(EntityArrays.BASIC_ESCAPE, EntityArrays.BASIC_UNESCAPE); - } - - @Test - public void testForDuplicateDeclaredMapValuesJavaCtrlCharsMap() { - assertThat(EntityArrays.JAVA_CTRL_CHARS_ESCAPE.keySet()).hasSameSizeAs( - EntityArrays.JAVA_CTRL_CHARS_UNESCAPE.keySet()); - } - - @Test - public void testJavaCntrlCharsMap() { - testEscapeVsUnescapeMaps(EntityArrays.JAVA_CTRL_CHARS_ESCAPE, EntityArrays.JAVA_CTRL_CHARS_UNESCAPE); - } - - private void testEscapeVsUnescapeMaps(final Map escapeMap, - final Map unescapeMap) { - for (final CharSequence escapeKey : escapeMap.keySet()) { - for (final CharSequence unescapeKey : unescapeMap.keySet()) { - if (escapeKey == unescapeMap.get(unescapeKey)) { - assertThat(unescapeKey).isEqualTo(escapeMap.get(escapeKey)); - } - } - } - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java b/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java deleted file mode 100644 index 6f547a3b11..0000000000 --- a/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java +++ /dev/null @@ -1,69 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.UnsupportedEncodingException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link JavaUnicodeEscaper}. - */ -public class JavaUnicodeEscaperTest { - - @Test - public void testBelow() { - final JavaUnicodeEscaper jue = JavaUnicodeEscaper.below('F'); - - final String input = "ADFGZ"; - final String result = jue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the below method") - .isEqualTo("\\u0041\\u0044FGZ"); - } - - @Test - public void testBetween() { - final JavaUnicodeEscaper jue = JavaUnicodeEscaper.between('F', 'L'); - - final String input = "ADFGZ"; - final String result = jue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the between method") - .isEqualTo("AD\\u0046\\u0047Z"); - } - - @Test - public void testAbove() { - final JavaUnicodeEscaper jue = JavaUnicodeEscaper.above('F'); - - final String input = "ADFGZ"; - final String result = jue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the above method") - .isEqualTo("ADF\\u0047\\u005A"); - } - - @Test - public void testToUtf16Escape() throws UnsupportedEncodingException { - final JavaUnicodeEscaper jue = JavaUnicodeEscaper.below('F'); - // According to https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B10000..U.2B10FFFF, - // Character ?, U+24B62, Binary Code Point 0010 0100 1011 0110 0010, - // Binary UTF-167 1101 1000 0101 0010 1101 1111 0110 0010, UTF-16 Hex Code Units D852 DF62 - final String encoding = jue.toUtf16Escape(Integer.parseInt("024B62", 16)); - assertThat(encoding).isEqualTo("\\uD852\\uDF62"); - } -} diff --git a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java deleted file mode 100644 index 868ea40b2a..0000000000 --- a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java +++ /dev/null @@ -1,64 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.StringWriter; -import java.security.InvalidParameterException; -import java.util.HashMap; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -/** - * Unit tests for {@link LookupTranslator}. - */ -public class LookupTranslatorTest { - - @Test - public void testBasicLookup() throws IOException { - final Map translatorMap = new HashMap<>(); - translatorMap.put("one", "two"); - final LookupTranslator lt = new LookupTranslator(translatorMap); - final StringWriter out = new StringWriter(); - final int result = lt.translate("one", 0, out); - assertThat(result).as("Incorrect codepoint consumption").isEqualTo(3); - assertThat(out.toString()).as("Incorrect value").isEqualTo("two"); - } - - // Tests: https://issues.apache.org/jira/browse/LANG-882 - @Test - public void testLang882() throws IOException { - final Map translatorMap = new HashMap<>(); - translatorMap.put(new StringBuffer("one"), new StringBuffer("two")); - final LookupTranslator lt = new LookupTranslator(translatorMap); - final StringWriter out = new StringWriter(); - final int result = lt.translate(new StringBuffer("one"), 0, out); - assertThat(result).as("Incorrect codepoint consumption").isEqualTo(3); - assertThat(out.toString()).as("Incorrect value").isEqualTo("two"); - } - - @Test - public void testFailsToCreateLookupTranslatorThrowsInvalidParameterException() { - assertThatExceptionOfType(InvalidParameterException.class).isThrownBy(() -> new LookupTranslator(null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java deleted file mode 100644 index 121136a58c..0000000000 --- a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java +++ /dev/null @@ -1,68 +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.translate; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link NumericEntityEscaper}. - */ -public class NumericEntityEscaperTest { - - @Test - public void testBelow() { - final NumericEntityEscaper nee = NumericEntityEscaper.below('F'); - - final String input = "ADFGZ"; - final String result = nee.translate(input); - assertThat(result).as("Failed to escape numeric entities via the below method").isEqualTo("ADFGZ"); - } - - @Test - public void testBetween() { - final NumericEntityEscaper nee = NumericEntityEscaper.between('F', 'L'); - - final String input = "ADFGZ"; - final String result = nee.translate(input); - assertThat(result).as("Failed to escape numeric entities via the between method").isEqualTo("ADFGZ"); - } - - @Test - public void testAbove() { - final NumericEntityEscaper nee = NumericEntityEscaper.above('F'); - - final String input = "ADFGZ"; - final String result = nee.translate(input); - assertThat(result).as("Failed to escape numeric entities via the above method").isEqualTo("ADFGZ"); - } - - // See LANG-617 - @Test - public void testSupplementary() { - final NumericEntityEscaper nee = new NumericEntityEscaper(); - final String input = "\uD803\uDC22"; - final String expected = "𐰢"; - - final String result = nee.translate(input); - assertThat(result).as("Failed to escape numeric entities supplementary characters").isEqualTo(expected); - - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java deleted file mode 100644 index 341cd63aa4..0000000000 --- a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java +++ /dev/null @@ -1,98 +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.translate; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -/** - * Unit tests for {@link NumericEntityUnescaper}. - */ -public class NumericEntityUnescaperTest { - - @Test - public void testSupplementaryUnescaping() { - final NumericEntityUnescaper neu = new NumericEntityUnescaper(); - final String input = "𐰢"; - final String expected = "\uD803\uDC22"; - - final String result = neu.translate(input); - assertThat(result).as("Failed to unescape numeric entities supplementary characters").isEqualTo(expected); - } - - @Test - public void testOutOfBounds() { - final NumericEntityUnescaper neu = new NumericEntityUnescaper(); - - assertThat(neu.translate("Test &")).as("Failed to ignore when last character is &").isEqualTo("Test &"); - assertThat(neu.translate("Test &#")).as("Failed to ignore when last character is &").isEqualTo("Test &#"); - assertThat(neu.translate("Test &#x")).as("Failed to ignore when last character is &").isEqualTo("Test &#x"); - assertThat(neu.translate("Test &#X")).as("Failed to ignore when last character is &").isEqualTo("Test &#X"); - } - - @Test - public void testUnfinishedEntity() { - // parse it - NumericEntityUnescaper neu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional); - String input = "Test 0 not test"; - String expected = "Test \u0030 not test"; - - String result = neu.translate(input); - assertThat(result).as("Failed to support unfinished entities (i.e. missing semi-colon)").isEqualTo(expected); - - // ignore it - neu = new NumericEntityUnescaper(); - input = "Test 0 not test"; - expected = input; - - result = neu.translate(input); - assertThat(result).as("Failed to ignore unfinished entities (i.e. missing semi-colon)").isEqualTo(expected); - - // fail it - neu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon); - input = "Test 0 not test"; - - try { - result = neu.translate(input); - fail("IllegalArgumentException expected"); - } catch (final IllegalArgumentException iae) { - // expected - } - } - - @Test - public void testCreatesNumericEntityUnescaperOne() { - final NumericEntityUnescaper.OPTION[] numericEntityUnescaperOPTIONArray = new NumericEntityUnescaper.OPTION[0]; - final NumericEntityUnescaper numericEntityUnescaper = - new NumericEntityUnescaper(numericEntityUnescaperOPTIONArray); - - assertThat(numericEntityUnescaper.translate("2|y|O7y`&#uVWj")).isEqualTo("2|y|O7y`&#uVWj"); - } - - @Test - public void testCreatesNumericEntityUnescaperTwo() { - final NumericEntityUnescaper.OPTION[] numericEntityUnescaperOPTIONArray = new NumericEntityUnescaper.OPTION[0]; - final NumericEntityUnescaper numericEntityUnescaper = - new NumericEntityUnescaper(numericEntityUnescaperOPTIONArray); - - assertThat(numericEntityUnescaper.translate("Ws2v8|O=7NR&#cB")).isEqualTo("Ws2v8|O=7NR&#cB"); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java deleted file mode 100644 index 8e4462f5dc..0000000000 --- a/src/test/java/org/apache/commons/text/translate/OctalUnescaperTest.java +++ /dev/null @@ -1,83 +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.translate; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link OctalUnescaper}. - */ -public class OctalUnescaperTest { - - @Test - public void testBetween() { - final OctalUnescaper oue = new OctalUnescaper(); //.between("1", "377"); - - String input = "\\45"; - String result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\45"); - - input = "\\377"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\377"); - - input = "\\377 and"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\377 and"); - - input = "\\378 and"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\37" + "8 and"); - - input = "\\378"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\37" + "8"); - - input = "\\1"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\1"); - - input = "\\036"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\036"); - - input = "\\0365"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\036" + "5"); - - input = "\\003"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\003"); - - input = "\\0003"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\000" + "3"); - - input = "\\279"; - result = oue.translate(input); - assertThat(result).as("Failed to unescape octal characters via the between method").isEqualTo("\279"); - - input = "\\999"; - result = oue.translate(input); - assertThat(result).as("Failed to ignore an out of range octal character via the between method") - .isEqualTo("\\999"); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java deleted file mode 100644 index 82b0ce244f..0000000000 --- a/src/test/java/org/apache/commons/text/translate/SinglePassTranslatorTest.java +++ /dev/null @@ -1,64 +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.translate; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; - -/** - * Unit test for {@link SinglePassTranslator} - */ -public class SinglePassTranslatorTest { - - private final SinglePassTranslator dummyTranslator = new SinglePassTranslator() { - @Override - void translateWhole(final CharSequence input, final Writer out) throws IOException { - } - }; - - private StringWriter out; - - @BeforeEach - public void before() { - out = new StringWriter(); - } - - @Test - public void codePointsAreReturned() throws Exception { - assertThat(dummyTranslator.translate("", 0, out)).isEqualTo(0); - assertThat(dummyTranslator.translate("abc", 0, out)).isEqualTo(3); - assertThat(dummyTranslator.translate("abcdefg", 0, out)).isEqualTo(7); - } - - @Test - public void indexIsValidated() throws Exception { - assertThatIllegalArgumentException().isThrownBy(() -> dummyTranslator.translate("abc", 1, out)); - } - - @Test - public void testTranslateThrowsIllegalArgumentException() throws IOException { - assertThatIllegalArgumentException().isThrownBy(() -> dummyTranslator.translate("(,Fk", 647, null)); - } - -} diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java deleted file mode 100644 index 8f4bfe1d21..0000000000 --- a/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java +++ /dev/null @@ -1,58 +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.translate; - -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link UnicodeEscaper}. - */ -public class UnicodeEscaperTest { - - @Test - public void testBelow() { - final UnicodeEscaper ue = UnicodeEscaper.below('F'); - - final String input = "ADFGZ"; - final String result = ue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the below method") - .isEqualTo("\\u0041\\u0044FGZ"); - } - - @Test - public void testBetween() { - final UnicodeEscaper ue = UnicodeEscaper.between('F', 'L'); - - final String input = "ADFGZ"; - final String result = ue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the between method") - .isEqualTo("AD\\u0046\\u0047Z"); - } - - @Test - public void testAbove() { - final UnicodeEscaper ue = UnicodeEscaper.above('F'); - - final String input = "ADFGZ"; - final String result = ue.translate(input); - assertThat(result).as("Failed to escape Unicode characters via the above method") - .isEqualTo("ADF\\u0047\\u005A"); - } -} diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java deleted file mode 100644 index b329c98963..0000000000 --- a/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java +++ /dev/null @@ -1,55 +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.translate; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; - -/** - * Unit tests for {@link UnicodeEscaper}. - */ -public class UnicodeUnescaperTest { - - // Requested in LANG-507 - @Test - public void testUPlus() { - final UnicodeUnescaper uu = new UnicodeUnescaper(); - - final String input = "\\u+0047"; - assertThat(uu.translate(input)).as("Failed to unescape Unicode characters with 'u+' notation").isEqualTo("G"); - } - - @Test - public void testUuuuu() { - final UnicodeUnescaper uu = new UnicodeUnescaper(); - - final String input = "\\uuuuuuuu0047"; - final String result = uu.translate(input); - assertThat(result).as("Failed to unescape Unicode characters with many 'u' characters").isEqualTo("G"); - } - - @Test - public void testLessThanFour() { - final UnicodeUnescaper uu = new UnicodeUnescaper(); - - final String input = "\\0047\\u006"; - assertThrows(IllegalArgumentException.class, () -> uu.translate(input)); - } -} diff --git a/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java deleted file mode 100644 index 3ba4a6d947..0000000000 --- a/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java +++ /dev/null @@ -1,47 +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.translate; - -import org.junit.jupiter.api.Test; - -import java.io.CharArrayWriter; -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link UnicodeUnpairedSurrogateRemover}. - */ -public class UnicodeUnpairedSurrogateRemoverTest { - final UnicodeUnpairedSurrogateRemover subject = new UnicodeUnpairedSurrogateRemover(); - final CharArrayWriter writer = new CharArrayWriter(); // nothing is ever written to it - - @Test - public void testValidCharacters() throws IOException { - assertThat(subject.translate(0xd7ff, writer)).isFalse(); - assertThat(subject.translate(0xe000, writer)).isFalse(); - assertThat(writer.size()).isZero(); - } - - @Test - public void testInvalidCharacters() throws IOException { - assertThat(subject.translate(0xd800, writer)).isTrue(); - assertThat(subject.translate(0xdfff, writer)).isTrue(); - assertThat(writer.size()).isZero(); - } -} - From b841163e06556a525c70add96533d17e7b8ccaec Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sat, 12 Jan 2019 05:26:19 +0200 Subject: [PATCH 05/13] Add multiple classes at once --- .../commons/text/diff/package-info.java | 25 ----------- .../commons/text/lookup/package-info.java | 29 ------------ .../commons/text/matcher/package-info.java | 25 ----------- .../org/apache/commons/text/package-info.java | 22 ---------- .../commons/text/similarity/package-info.java | 44 ------------------- .../commons/text/translate/package-info.java | 24 ---------- 6 files changed, 169 deletions(-) delete mode 100644 src/main/java/org/apache/commons/text/diff/package-info.java delete mode 100644 src/main/java/org/apache/commons/text/lookup/package-info.java delete mode 100644 src/main/java/org/apache/commons/text/matcher/package-info.java delete mode 100644 src/main/java/org/apache/commons/text/package-info.java delete mode 100644 src/main/java/org/apache/commons/text/similarity/package-info.java delete mode 100644 src/main/java/org/apache/commons/text/translate/package-info.java diff --git a/src/main/java/org/apache/commons/text/diff/package-info.java b/src/main/java/org/apache/commons/text/diff/package-info.java deleted file mode 100644 index 92fde8636f..0000000000 --- a/src/main/java/org/apache/commons/text/diff/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 diff between strings.

- * - *

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:

- * - *
    - *
  • {@link org.apache.commons.text.similarity.CosineDistance Cosine Distance}
  • - *
  • {@link org.apache.commons.text.similarity.CosineSimilarity Cosine Similarity}
  • - *
  • {@link org.apache.commons.text.similarity.FuzzyScore Fuzzy Score}
  • - *
  • {@link org.apache.commons.text.similarity.HammingDistance Hamming Distance}
  • - *
  • {@link org.apache.commons.text.similarity.JaroWinklerDistance Jaro-Winkler Distance}
  • - *
  • {@link org.apache.commons.text.similarity.LevenshteinDistance Levenshtein Distance}
  • - *
  • {@link org.apache.commons.text.similarity.LongestCommonSubsequenceDistance - * Longest Commons Subsequence Distance}
  • - *
- * - *

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; From c04f9068de8306f0151330c6f1e44d569dca55a5 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sat, 12 Jan 2019 10:01:32 +0200 Subject: [PATCH 06/13] No more need for separate JDK 11 builds. Removes compatibility for JDK 9 and 10. --- pom.xml | 763 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 396 insertions(+), 367 deletions(-) diff --git a/pom.xml b/pom.xml index d7ba9ed02d..b789f68180 100644 --- a/pom.xml +++ b/pom.xml @@ -16,403 +16,432 @@ limitations under the License. --> - - 4.0.0 + + 4.0.0 com.jwebmp jwebmp-builder 0.0.0_0-SNAPSHOT - commons-text + commons-text - Apache Commons Text - Apache Commons Text is a library focused on algorithms working on strings. - http://commons.apache.org/proper/commons-text + Apache Commons Text + Apache Commons Text is a library focused on algorithms working on strings. + http://commons.apache.org/proper/commons-text - - ISO-8859-1 - UTF-8 + + ISO-8859-1 + UTF-8 - text - org.apache.commons.text + text + org.apache.commons.text - 1.6 - (Java 8+) + 1.6 + (Java 8+) - TEXT - 12318221 + TEXT + 12318221 - text - https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text - site-content + text + https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text + site-content - 5.3.1 + 5.3.1 - 3.0.0 - 8.14 + 3.0.0 + 8.14 - 3.1.8 + 3.1.8 - 0.8.2 + 0.8.2 - - false - - 0.13.0 - false + + false + + 0.13.0 + false - - 1.6 - RC1 - true - scm:svn:https://dist.apache.org/repos/dist/dev/commons/${commons.componentid} - Rob Tompkins - B6E73D84EA4FCC47166087253FAAD2CD5ECBB314 - + + 1.6 + RC1 + true + scm:svn:https://dist.apache.org/repos/dist/dev/commons/${commons.componentid} + Rob Tompkins + B6E73D84EA4FCC47166087253FAAD2CD5ECBB314 + - + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + - org.junit - junit-bom - ${junit.version} - pom - import + com.jwebmp + commons-lang3 + ${project.version} - - + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.junit.platform + junit-platform-launcher + test + + + org.assertj + assertj-core + test + + - - - com.jwebmp - commons-lang3 - ${project.version} - - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - - - org.junit.platform - junit-platform-launcher - test - - - org.assertj - assertj-core - test - - + + clean verify apache-rat:check clirr:check checkstyle:check spotbugs:check javadoc:javadoc + + + + org.apache.rat + apache-rat-plugin + + + site-content/** + src/site/resources/download_lang.cgi + src/test/resources/stringEscapeUtilsTestData.txt + src/site/resources/release-notes/RELEASE-NOTES-*.txt + + + + + com.github.siom79.japicmp + japicmp-maven-plugin + + false + + - - clean verify apache-rat:check clirr:check checkstyle:check spotbugs:check javadoc:javadoc - - - - org.apache.rat - apache-rat-plugin - - - site-content/** - src/site/resources/download_lang.cgi - src/test/resources/stringEscapeUtilsTestData.txt - src/site/resources/release-notes/RELEASE-NOTES-*.txt - - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - false - - + + + + + maven-checkstyle-plugin + ${checkstyle.plugin.version} + + false + ${basedir}/checkstyle.xml + ${basedir}/license-header.txt + ${basedir}/checkstyle-suppressions.xml + ${basedir}/checkstyle-suppressions.xml + true + + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.plugin.version} + + ${basedir}/sb-excludes.xml + + + + maven-assembly-plugin + + + src/assembly/bin.xml + src/assembly/src.xml + + gnu + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + ${commons.module.name} + + + + + + - - - - - maven-checkstyle-plugin - ${checkstyle.plugin.version} - - false - ${basedir}/checkstyle.xml - ${basedir}/license-header.txt - ${basedir}/checkstyle-suppressions.xml - ${basedir}/checkstyle-suppressions.xml - true - - - - com.puppycrawl.tools - checkstyle - ${checkstyle.version} - - - - - com.github.spotbugs - spotbugs-maven-plugin - ${spotbugs.plugin.version} - - ${basedir}/sb-excludes.xml - - - - maven-assembly-plugin - - - src/assembly/bin.xml - src/assembly/src.xml - - gnu - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - ${commons.module.name} - - - - - - + + + + maven-checkstyle-plugin + ${checkstyle.plugin.version} + + false + ${basedir}/checkstyle.xml + ${basedir}/license-header.txt + ${basedir}/checkstyle-suppressions.xml + ${basedir}/checkstyle-suppressions.xml + true + + + + + checkstyle + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.plugin.version} + + ${basedir}/sb-excludes.xml + + + + org.codehaus.mojo + clirr-maven-plugin + + info + + + + maven-pmd-plugin + 3.10.0 + + ${maven.compiler.target} + + + + + pmd + cpd + + + + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + + + Needs Work + + + TODO + exact + + + FIXME + exact + + + XXX + exact + + + + + Noteable Markers + + + NOTE + exact + + + NOPMD + exact + + + NOSONAR + exact + + + + + + + + + org.codehaus.mojo + javancss-maven-plugin + + + - - - - maven-checkstyle-plugin - ${checkstyle.plugin.version} - - false - ${basedir}/checkstyle.xml - ${basedir}/license-header.txt - ${basedir}/checkstyle-suppressions.xml - ${basedir}/checkstyle-suppressions.xml - true - - - - - checkstyle - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - ${spotbugs.plugin.version} - - ${basedir}/sb-excludes.xml - - - - org.codehaus.mojo - clirr-maven-plugin - - info - - - - maven-pmd-plugin - 3.10.0 - - ${maven.compiler.target} - - - - - pmd - cpd - - - - - - org.codehaus.mojo - taglist-maven-plugin - 2.4 - - - - - Needs Work - - - TODO - exact - - - FIXME - exact - - - XXX - exact - - - - - Noteable Markers - - - NOTE - exact - - - NOPMD - exact - - - NOSONAR - exact - - - - - - - - - org.codehaus.mojo - javancss-maven-plugin - - - + 2014 - 2014 + + + kinow + Bruno P. Kinoshita + kinow@apache.org + + + britter + Benedikt Ritter + britter@apache.org + + + chtompki + Rob Tompkins + chtompki@apache.org + + + ggregory + Gary Gregory + ggregory@apache.org + + + djones + Duncan Jones + djones@apache.org + + - - - kinow - Bruno P. Kinoshita - kinow@apache.org - - - britter - Benedikt Ritter - britter@apache.org - - - chtompki - Rob Tompkins - chtompki@apache.org - - - ggregory - Gary Gregory - ggregory@apache.org - - - djones - Duncan Jones - djones@apache.org - - + + + Don Jeba + donjeba@yahoo.com + + + Sampanna Kahu + + + Jarek Strzelecki + + + Lee Adcock + + + Amey Jadiye + ameyjadiye@gmail.com + + + Arun Vinud S S + + + Ioannis Sermetziadis + + + Jostein Tveit + + + Luciano Medallia + + + Jan Martin Keil + + + Nandor Kollar + + + Nick Wong + + - - - Don Jeba - donjeba@yahoo.com - - - Sampanna Kahu - - - Jarek Strzelecki - - - Lee Adcock - - - Amey Jadiye - ameyjadiye@gmail.com - - - Arun Vinud S S - - - Ioannis Sermetziadis - - - Jostein Tveit - - - Luciano Medallia - - - Jan Martin Keil - - - Nandor Kollar - - - Nick Wong - - + + scm:git:http://git-wip-us.apache.org/repos/asf/commons-text.git + scm:git:https://git-wip-us.apache.org/repos/asf/commons-text.git + https://git-wip-us.apache.org/repos/asf?p=commons-text.git + - - scm:git:http://git-wip-us.apache.org/repos/asf/commons-text.git - scm:git:https://git-wip-us.apache.org/repos/asf/commons-text.git - https://git-wip-us.apache.org/repos/asf?p=commons-text.git - + + jira + http://issues.apache.org/jira/browse/TEXT + - - jira - http://issues.apache.org/jira/browse/TEXT - + + + apache.website + Apache Commons Site + scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text/ + + - - - apache.website - Apache Commons Site - scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text/ - - + + + jdk8 + + + + org.moditect + moditect-maven-plugin + + + add-module-infos + package + + add-module-info + + + true + + + src/jre11/java/module-info.java + + + + + + + + + - - - jdk11 - - [9,) - - - - true - true - - - - jdk12 - - [12,) - - - - true - - true - - - + + jdk11 + + [9,) + + + + true + true + + + + jdk12 + + [12,) + + + + true + + true + + + From 80c01d0eadad734f7770415979471afa9a151cc0 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Fri, 12 Apr 2019 01:21:47 +0200 Subject: [PATCH 07/13] Dev Kit Build Up and Mass structure cleanup --- pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index b789f68180..a46c688506 100644 --- a/pom.xml +++ b/pom.xml @@ -19,12 +19,13 @@ 4.0.0 - com.jwebmp - jwebmp-builder + com.jwebmp.jpms + jpms-pending-modules 0.0.0_0-SNAPSHOT commons-text + com.jwebmp.jpms.commons Apache Commons Text Apache Commons Text is a library focused on algorithms working on strings. http://commons.apache.org/proper/commons-text @@ -84,7 +85,7 @@ - com.jwebmp + com.jwebmp.jpms.commons commons-lang3 ${project.version} From 6126e6b12721328597bc40e680a42e17a3917542 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Mon, 13 May 2019 17:51:46 +0200 Subject: [PATCH 08/13] Jakarta Activation and JAXB Move --- pom.xml.versionsBackup | 448 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 448 insertions(+) create mode 100644 pom.xml.versionsBackup diff --git a/pom.xml.versionsBackup b/pom.xml.versionsBackup new file mode 100644 index 0000000000..a46c688506 --- /dev/null +++ b/pom.xml.versionsBackup @@ -0,0 +1,448 @@ + + + + + 4.0.0 + + com.jwebmp.jpms + jpms-pending-modules + 0.0.0_0-SNAPSHOT + + commons-text + + com.jwebmp.jpms.commons + Apache Commons Text + Apache Commons Text is a library focused on algorithms working on strings. + http://commons.apache.org/proper/commons-text + + + ISO-8859-1 + UTF-8 + + text + org.apache.commons.text + + 1.6 + (Java 8+) + + TEXT + 12318221 + + text + https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text + site-content + + 5.3.1 + + 3.0.0 + 8.14 + + 3.1.8 + + 0.8.2 + + + false + + 0.13.0 + false + + + 1.6 + RC1 + true + scm:svn:https://dist.apache.org/repos/dist/dev/commons/${commons.componentid} + Rob Tompkins + B6E73D84EA4FCC47166087253FAAD2CD5ECBB314 + + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + + + com.jwebmp.jpms.commons + commons-lang3 + ${project.version} + + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.junit.platform + junit-platform-launcher + test + + + org.assertj + assertj-core + test + + + + + clean verify apache-rat:check clirr:check checkstyle:check spotbugs:check javadoc:javadoc + + + + org.apache.rat + apache-rat-plugin + + + site-content/** + src/site/resources/download_lang.cgi + src/test/resources/stringEscapeUtilsTestData.txt + src/site/resources/release-notes/RELEASE-NOTES-*.txt + + + + + com.github.siom79.japicmp + japicmp-maven-plugin + + false + + + + + + + + maven-checkstyle-plugin + ${checkstyle.plugin.version} + + false + ${basedir}/checkstyle.xml + ${basedir}/license-header.txt + ${basedir}/checkstyle-suppressions.xml + ${basedir}/checkstyle-suppressions.xml + true + + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.plugin.version} + + ${basedir}/sb-excludes.xml + + + + maven-assembly-plugin + + + src/assembly/bin.xml + src/assembly/src.xml + + gnu + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + ${commons.module.name} + + + + + + + + + + + maven-checkstyle-plugin + ${checkstyle.plugin.version} + + false + ${basedir}/checkstyle.xml + ${basedir}/license-header.txt + ${basedir}/checkstyle-suppressions.xml + ${basedir}/checkstyle-suppressions.xml + true + + + + + checkstyle + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + ${spotbugs.plugin.version} + + ${basedir}/sb-excludes.xml + + + + org.codehaus.mojo + clirr-maven-plugin + + info + + + + maven-pmd-plugin + 3.10.0 + + ${maven.compiler.target} + + + + + pmd + cpd + + + + + + org.codehaus.mojo + taglist-maven-plugin + 2.4 + + + + + Needs Work + + + TODO + exact + + + FIXME + exact + + + XXX + exact + + + + + Noteable Markers + + + NOTE + exact + + + NOPMD + exact + + + NOSONAR + exact + + + + + + + + + org.codehaus.mojo + javancss-maven-plugin + + + + + 2014 + + + + kinow + Bruno P. Kinoshita + kinow@apache.org + + + britter + Benedikt Ritter + britter@apache.org + + + chtompki + Rob Tompkins + chtompki@apache.org + + + ggregory + Gary Gregory + ggregory@apache.org + + + djones + Duncan Jones + djones@apache.org + + + + + + Don Jeba + donjeba@yahoo.com + + + Sampanna Kahu + + + Jarek Strzelecki + + + Lee Adcock + + + Amey Jadiye + ameyjadiye@gmail.com + + + Arun Vinud S S + + + Ioannis Sermetziadis + + + Jostein Tveit + + + Luciano Medallia + + + Jan Martin Keil + + + Nandor Kollar + + + Nick Wong + + + + + scm:git:http://git-wip-us.apache.org/repos/asf/commons-text.git + scm:git:https://git-wip-us.apache.org/repos/asf/commons-text.git + https://git-wip-us.apache.org/repos/asf?p=commons-text.git + + + + jira + http://issues.apache.org/jira/browse/TEXT + + + + + apache.website + Apache Commons Site + scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text/ + + + + + + jdk8 + + + + org.moditect + moditect-maven-plugin + + + add-module-infos + package + + add-module-info + + + true + + + src/jre11/java/module-info.java + + + + + + + + + + + + jdk11 + + [9,) + + + + true + true + + + + jdk12 + + [12,) + + + + true + + true + + + + From 533a481060edaeec2050a29ec341a98b9804711d Mon Sep 17 00:00:00 2001 From: GedMarc Date: Mon, 13 May 2019 17:54:49 +0200 Subject: [PATCH 09/13] Jakarta Activation and JAXB Move --- pom.xml.versionsBackup | 448 ----------------------------------------- 1 file changed, 448 deletions(-) delete mode 100644 pom.xml.versionsBackup diff --git a/pom.xml.versionsBackup b/pom.xml.versionsBackup deleted file mode 100644 index a46c688506..0000000000 --- a/pom.xml.versionsBackup +++ /dev/null @@ -1,448 +0,0 @@ - - - - - 4.0.0 - - com.jwebmp.jpms - jpms-pending-modules - 0.0.0_0-SNAPSHOT - - commons-text - - com.jwebmp.jpms.commons - Apache Commons Text - Apache Commons Text is a library focused on algorithms working on strings. - http://commons.apache.org/proper/commons-text - - - ISO-8859-1 - UTF-8 - - text - org.apache.commons.text - - 1.6 - (Java 8+) - - TEXT - 12318221 - - text - https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text - site-content - - 5.3.1 - - 3.0.0 - 8.14 - - 3.1.8 - - 0.8.2 - - - false - - 0.13.0 - false - - - 1.6 - RC1 - true - scm:svn:https://dist.apache.org/repos/dist/dev/commons/${commons.componentid} - Rob Tompkins - B6E73D84EA4FCC47166087253FAAD2CD5ECBB314 - - - - - - org.junit - junit-bom - ${junit.version} - pom - import - - - - - - - com.jwebmp.jpms.commons - commons-lang3 - ${project.version} - - - - org.junit.jupiter - junit-jupiter-engine - test - - - org.junit.jupiter - junit-jupiter-params - test - - - org.junit.platform - junit-platform-launcher - test - - - org.assertj - assertj-core - test - - - - - clean verify apache-rat:check clirr:check checkstyle:check spotbugs:check javadoc:javadoc - - - - org.apache.rat - apache-rat-plugin - - - site-content/** - src/site/resources/download_lang.cgi - src/test/resources/stringEscapeUtilsTestData.txt - src/site/resources/release-notes/RELEASE-NOTES-*.txt - - - - - com.github.siom79.japicmp - japicmp-maven-plugin - - false - - - - - - - - maven-checkstyle-plugin - ${checkstyle.plugin.version} - - false - ${basedir}/checkstyle.xml - ${basedir}/license-header.txt - ${basedir}/checkstyle-suppressions.xml - ${basedir}/checkstyle-suppressions.xml - true - - - - com.puppycrawl.tools - checkstyle - ${checkstyle.version} - - - - - com.github.spotbugs - spotbugs-maven-plugin - ${spotbugs.plugin.version} - - ${basedir}/sb-excludes.xml - - - - maven-assembly-plugin - - - src/assembly/bin.xml - src/assembly/src.xml - - gnu - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - - ${commons.module.name} - - - - - - - - - - - maven-checkstyle-plugin - ${checkstyle.plugin.version} - - false - ${basedir}/checkstyle.xml - ${basedir}/license-header.txt - ${basedir}/checkstyle-suppressions.xml - ${basedir}/checkstyle-suppressions.xml - true - - - - - checkstyle - - - - - - - com.github.spotbugs - spotbugs-maven-plugin - ${spotbugs.plugin.version} - - ${basedir}/sb-excludes.xml - - - - org.codehaus.mojo - clirr-maven-plugin - - info - - - - maven-pmd-plugin - 3.10.0 - - ${maven.compiler.target} - - - - - pmd - cpd - - - - - - org.codehaus.mojo - taglist-maven-plugin - 2.4 - - - - - Needs Work - - - TODO - exact - - - FIXME - exact - - - XXX - exact - - - - - Noteable Markers - - - NOTE - exact - - - NOPMD - exact - - - NOSONAR - exact - - - - - - - - - org.codehaus.mojo - javancss-maven-plugin - - - - - 2014 - - - - kinow - Bruno P. Kinoshita - kinow@apache.org - - - britter - Benedikt Ritter - britter@apache.org - - - chtompki - Rob Tompkins - chtompki@apache.org - - - ggregory - Gary Gregory - ggregory@apache.org - - - djones - Duncan Jones - djones@apache.org - - - - - - Don Jeba - donjeba@yahoo.com - - - Sampanna Kahu - - - Jarek Strzelecki - - - Lee Adcock - - - Amey Jadiye - ameyjadiye@gmail.com - - - Arun Vinud S S - - - Ioannis Sermetziadis - - - Jostein Tveit - - - Luciano Medallia - - - Jan Martin Keil - - - Nandor Kollar - - - Nick Wong - - - - - scm:git:http://git-wip-us.apache.org/repos/asf/commons-text.git - scm:git:https://git-wip-us.apache.org/repos/asf/commons-text.git - https://git-wip-us.apache.org/repos/asf?p=commons-text.git - - - - jira - http://issues.apache.org/jira/browse/TEXT - - - - - apache.website - Apache Commons Site - scm:svn:https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-text/ - - - - - - jdk8 - - - - org.moditect - moditect-maven-plugin - - - add-module-infos - package - - add-module-info - - - true - - - src/jre11/java/module-info.java - - - - - - - - - - - - jdk11 - - [9,) - - - - true - true - - - - jdk12 - - [12,) - - - - true - - true - - - - From 86be068876f79f4d4fc9ed2832cbb382c559f768 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 26 May 2019 14:27:44 +0200 Subject: [PATCH 10/13] Javadoc enabling for commons-text --- pom.xml | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/pom.xml b/pom.xml index a46c688506..45ac28b003 100644 --- a/pom.xml +++ b/pom.xml @@ -420,29 +420,5 @@ - - - jdk11 - - [9,) - - - - true - true - - - - jdk12 - - [12,) - - - - true - - true - - From 39834e4a612609f45d4b5c8e5b9242768fd43576 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sat, 21 Sep 2019 19:57:50 +0200 Subject: [PATCH 11/13] Apache Poi and the commons libaries with it --- pom.xml | 30 ------------------------------ 1 file changed, 30 deletions(-) diff --git a/pom.xml b/pom.xml index 45ac28b003..bb5698b4d5 100644 --- a/pom.xml +++ b/pom.xml @@ -391,34 +391,4 @@ - - - jdk8 - - - - org.moditect - moditect-maven-plugin - - - add-module-infos - package - - add-module-info - - - true - - - src/jre11/java/module-info.java - - - - - - - - - - From 93ad13eac9cde6b745455176db93cf9c070c7c37 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 22 Sep 2019 22:53:28 +0200 Subject: [PATCH 12/13] Guava, Type JAR in Dependencies --- README.md | 4 ++-- pom.xml | 28 ++++++++++++++-------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5fb2d4f1bd..6c764cc73e 100644 --- a/README.md +++ b/README.md @@ -67,8 +67,8 @@ Alternatively you can pull it from the central Maven repositories: org.apache.commons commons-text - 1.6 - + 1.6jar + ``` Contributing diff --git a/pom.xml b/pom.xml index bb5698b4d5..7240e9e187 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ commons-text - com.jwebmp.jpms.commons + com.jwebmp.jpms.thirdparty.commons Apache Commons Text Apache Commons Text is a library focused on algorithms working on strings. http://commons.apache.org/proper/commons-text @@ -85,31 +85,31 @@ - com.jwebmp.jpms.commons + com.jwebmp.jpms.thirdparty.commons commons-lang3 - ${project.version} - + ${project.version}jar + org.junit.jupiter junit-jupiter-engine - test - + testjar + org.junit.jupiter junit-jupiter-params - test - + testjar + org.junit.platform junit-platform-launcher - test - + testjar + org.assertj assertj-core - test - + testjar + @@ -154,8 +154,8 @@ com.puppycrawl.tools checkstyle - ${checkstyle.version} - + ${checkstyle.version}jar + From b61cd66d662978d1eae9df23f28649c940795543 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Wed, 25 Sep 2019 04:33:29 +0200 Subject: [PATCH 13/13] MSSQL to 7.4.1 JRE 12, and a bunch of others --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 7240e9e187..37ce2b4cb3 100644 --- a/pom.xml +++ b/pom.xml @@ -25,7 +25,7 @@ commons-text - com.jwebmp.jpms.thirdparty.commons + com.jwebmp.jpms.thirdparty Apache Commons Text Apache Commons Text is a library focused on algorithms working on strings. http://commons.apache.org/proper/commons-text @@ -85,7 +85,7 @@ - com.jwebmp.jpms.thirdparty.commons + com.jwebmp.jpms.thirdparty commons-lang3 ${project.version}jar