You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2022/05/29 12:33:51 UTC
[commons-text] 02/06: Sort methods
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git
commit 09c1f4be5de94775e9435d420ddcd036ff4b1e31
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Sun May 29 08:12:06 2022 -0400
Sort methods
---
.../commons/text/similarity/CosineSimilarity.java | 28 +-
.../apache/commons/text/similarity/Counter.java | 12 +-
.../commons/text/similarity/EditDistanceFrom.java | 16 +-
.../text/similarity/IntersectionResult.java | 42 +-
.../text/similarity/IntersectionSimilarity.java | 100 +--
.../text/similarity/JaroWinklerDistance.java | 94 +--
.../text/similarity/JaroWinklerSimilarity.java | 106 +--
.../similarity/LevenshteinDetailedDistance.java | 320 ++++----
.../text/similarity/LevenshteinDistance.java | 158 ++--
.../text/similarity/LevenshteinResults.java | 46 +-
.../text/similarity/LongestCommonSubsequence.java | 200 ++---
.../apache/commons/text/StringSubstitutorTest.java | 44 +-
.../commons/text/diff/ReplacementsFinderTest.java | 62 +-
.../commons/text/diff/StringsComparatorTest.java | 78 +-
.../commons/text/jmh/DoubleFormatPerformance.java | 82 +-
.../jmh/LongestCommonSubsequencePerformance.java | 112 +--
.../commons/text/numbers/DoubleFormatTest.java | 690 ++++++++--------
.../commons/text/numbers/ParsedDecimalTest.java | 914 ++++++++++-----------
.../text/similarity/CosineDistanceTest.java | 24 +-
.../text/similarity/CosineSimilarityTest.java | 26 +-
.../commons/text/similarity/FuzzyScoreTest.java | 18 +-
.../text/similarity/IntersectionResultTest.java | 108 +--
.../similarity/IntersectionSimilarityTest.java | 334 ++++----
.../text/similarity/JaccardDistanceTest.java | 8 +-
.../text/similarity/JaccardSimilarityTest.java | 8 +-
.../text/similarity/JaroWinklerDistanceTest.java | 30 +-
.../text/similarity/JaroWinklerSimilarityTest.java | 54 +-
.../LevenshteinDetailedDistanceTest.java | 234 +++---
.../text/similarity/LevenshteinDistanceTest.java | 60 +-
.../text/similarity/LevenshteinResultsTest.java | 34 +-
.../LongestCommonSubsequenceDistanceTest.java | 8 +-
.../similarity/LongestCommonSubsequenceTest.java | 100 +--
.../text/similarity/SimilarityScoreFromTest.java | 10 +-
.../text/translate/AggregateTranslatorTest.java | 28 +-
.../commons/text/translate/CsvTranslatorsTest.java | 30 +-
.../commons/text/translate/EntityArraysTest.java | 74 +-
.../text/translate/JavaUnicodeEscaperTest.java | 20 +-
.../text/translate/LookupTranslatorTest.java | 10 +-
.../text/translate/NumericEntityEscaperTest.java | 18 +-
.../text/translate/NumericEntityUnescaperTest.java | 48 +-
.../commons/text/translate/UnicodeEscaperTest.java | 20 +-
.../text/translate/UnicodeUnescaperTest.java | 16 +-
.../UnicodeUnpairedSurrogateRemoverTest.java | 12 +-
43 files changed, 2218 insertions(+), 2218 deletions(-)
diff --git a/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java b/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
index 57eb25f5..edd873c5 100644
--- a/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/CosineSimilarity.java
@@ -66,20 +66,6 @@ public class CosineSimilarity {
return cosineSimilarity;
}
- /**
- * Returns a set with strings common to the two given maps.
- *
- * @param leftVector left vector map
- * @param rightVector right vector map
- * @return common strings
- */
- private Set<CharSequence> getIntersection(final Map<CharSequence, Integer> leftVector,
- final Map<CharSequence, Integer> rightVector) {
- final Set<CharSequence> intersection = new HashSet<>(leftVector.keySet());
- intersection.retainAll(rightVector.keySet());
- return intersection;
- }
-
/**
* Computes the dot product of two vectors. It ignores remaining elements. It means
* that if a vector is longer than other, then a smaller part of it will be used to compute
@@ -99,4 +85,18 @@ public class CosineSimilarity {
return dotProduct;
}
+ /**
+ * Returns a set with strings common to the two given maps.
+ *
+ * @param leftVector left vector map
+ * @param rightVector right vector map
+ * @return common strings
+ */
+ private Set<CharSequence> getIntersection(final Map<CharSequence, Integer> leftVector,
+ final Map<CharSequence, Integer> rightVector) {
+ final Set<CharSequence> intersection = new HashSet<>(leftVector.keySet());
+ intersection.retainAll(rightVector.keySet());
+ return intersection;
+ }
+
}
diff --git a/src/main/java/org/apache/commons/text/similarity/Counter.java b/src/main/java/org/apache/commons/text/similarity/Counter.java
index 03129273..b49a1b30 100644
--- a/src/main/java/org/apache/commons/text/similarity/Counter.java
+++ b/src/main/java/org/apache/commons/text/similarity/Counter.java
@@ -32,12 +32,6 @@ import java.util.Map;
*/
final class Counter {
- /**
- * Hidden constructor.
- */
- private Counter() {
- }
-
/**
* It counts how many times each element provided occurred in an array and
* returns a dict with the element as key and the count as value.
@@ -58,4 +52,10 @@ final class Counter {
return innerCounter;
}
+ /**
+ * Hidden constructor.
+ */
+ private Counter() {
+ }
+
}
diff --git a/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java b/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
index 5aef77f4..f81e2f07 100644
--- a/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
+++ b/src/main/java/org/apache/commons/text/similarity/EditDistanceFrom.java
@@ -88,21 +88,21 @@ public class EditDistanceFrom<R> {
}
/**
- * Gets the left parameter.
+ * Gets the edit distance.
*
- * @return The left parameter
+ * @return The edit distance
*/
- public CharSequence getLeft() {
- return left;
+ public EditDistance<R> getEditDistance() {
+ return editDistance;
}
/**
- * Gets the edit distance.
+ * Gets the left parameter.
*
- * @return The edit distance
+ * @return The left parameter
*/
- public EditDistance<R> getEditDistance() {
- return editDistance;
+ public CharSequence getLeft() {
+ return left;
}
}
diff --git a/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java b/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
index 72710599..711af57a 100644
--- a/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
+++ b/src/main/java/org/apache/commons/text/similarity/IntersectionResult.java
@@ -70,6 +70,27 @@ public class IntersectionResult {
this.intersection = intersection;
}
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ final IntersectionResult result = (IntersectionResult) o;
+ return sizeA == result.sizeA && sizeB == result.sizeB && intersection == result.intersection;
+ }
+
+ /**
+ * Gets the size of the intersection between set A and B.
+ *
+ * @return {@code |A ∩ B|}
+ */
+ public int getIntersection() {
+ return intersection;
+ }
+
/**
* Gets the size of set A.
*
@@ -88,27 +109,6 @@ public class IntersectionResult {
return sizeB;
}
- /**
- * Gets the size of the intersection between set A and B.
- *
- * @return {@code |A ∩ B|}
- */
- public int getIntersection() {
- return intersection;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- final IntersectionResult result = (IntersectionResult) o;
- return sizeA == result.sizeA && sizeB == result.sizeB && intersection == result.intersection;
- }
-
@Override
public int hashCode() {
return Objects.hash(sizeA, sizeB, intersection);
diff --git a/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java b/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
index 09af8fe6..c692342c 100644
--- a/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/IntersectionSimilarity.java
@@ -36,13 +36,6 @@ import java.util.function.Function;
* @see HashMap
*/
public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionResult> {
- /** The converter used to create the elements from the characters. */
- private final Function<CharSequence, Collection<T>> converter;
-
- // The following is adapted from commons-collections for a Bag.
- // A Bag is a collection that can store the count of the number
- // of copies of each element.
-
/**
* Mutable counter class for storing the count of elements.
*/
@@ -51,6 +44,10 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
int count = 1;
}
+ // The following is adapted from commons-collections for a Bag.
+ // A Bag is a collection that can store the count of the number
+ // of copies of each element.
+
/**
* A minimal implementation of a Bag that can store elements and a count.
*
@@ -84,6 +81,15 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
}
}
+ /**
+ * Returns a Set view of the mappings contained in this bag.
+ *
+ * @return The Set view
+ */
+ Set<Entry<T, BagCount>> entrySet() {
+ return map.entrySet();
+ }
+
/**
* Returns the number of occurrence of the given element in this bag by
* looking up its count in the underlying map.
@@ -99,15 +105,6 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
return 0;
}
- /**
- * Returns a Set view of the mappings contained in this bag.
- *
- * @return The Set view
- */
- Set<Entry<T, BagCount>> entrySet() {
- return map.entrySet();
- }
-
/**
* Get the number of unique elements in the bag.
*
@@ -118,6 +115,28 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
}
}
+ /**
+ * Computes the intersection between two sets. This is the count of all the elements
+ * that are within both sets.
+ *
+ * @param <T> the type of the elements in the set
+ * @param setA the set A
+ * @param setB the set B
+ * @return The intersection
+ */
+ private static <T> int getIntersection(final Set<T> setA, final Set<T> setB) {
+ int intersection = 0;
+ for (final T element : setA) {
+ if (setB.contains(element)) {
+ intersection++;
+ }
+ }
+ return intersection;
+ }
+
+ /** The converter used to create the elements from the characters. */
+ private final Function<CharSequence, Collection<T>> converter;
+
/**
* Create a new intersection similarity using the provided converter.
*
@@ -184,40 +203,6 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
return new IntersectionResult(sizeA, sizeB, intersection);
}
- /**
- * Converts the collection to a bag. The bag will contain the count of each element
- * in the collection.
- *
- * @param objects the objects
- * @return The bag
- */
- private TinyBag toBag(final Collection<T> objects) {
- final TinyBag bag = new TinyBag(objects.size());
- for (final T t : objects) {
- bag.add(t);
- }
- return bag;
- }
-
- /**
- * Computes the intersection between two sets. This is the count of all the elements
- * that are within both sets.
- *
- * @param <T> the type of the elements in the set
- * @param setA the set A
- * @param setB the set B
- * @return The intersection
- */
- private static <T> int getIntersection(final Set<T> setA, final Set<T> setB) {
- int intersection = 0;
- for (final T element : setA) {
- if (setB.contains(element)) {
- intersection++;
- }
- }
- return intersection;
- }
-
/**
* Computes the intersection between two bags. This is the sum of the minimum
* count of each element that is within both sets.
@@ -236,4 +221,19 @@ public class IntersectionSimilarity<T> implements SimilarityScore<IntersectionRe
}
return intersection;
}
+
+ /**
+ * Converts the collection to a bag. The bag will contain the count of each element
+ * in the collection.
+ *
+ * @param objects the objects
+ * @return The bag
+ */
+ private TinyBag toBag(final Collection<T> objects) {
+ final TinyBag bag = new TinyBag(objects.size());
+ for (final T t : objects) {
+ bag.add(t);
+ }
+ return bag;
+ }
}
diff --git a/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java b/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
index ef6619f5..892f456b 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaroWinklerDistance.java
@@ -32,53 +32,6 @@ public class JaroWinklerDistance implements EditDistance<Double> {
@Deprecated
public static final int INDEX_NOT_FOUND = -1;
- /**
- * Jaro Winkler similarity object used to calculate the distance (1 - similarity).
- */
- private final JaroWinklerSimilarity similarity = new JaroWinklerSimilarity();
-
- /**
- * Computes the Jaro Winkler Distance between two character sequences.
- *
- * <pre>
- * distance.apply(null, null) = IllegalArgumentException
- * distance.apply("foo", null) = IllegalArgumentException
- * distance.apply(null, "foo") = IllegalArgumentException
- * distance.apply("", "") = 0.0
- * distance.apply("foo", "foo") = 0.0
- * distance.apply("foo", "foo ") = 0.06
- * distance.apply("foo", "foo ") = 0.09
- * distance.apply("foo", " foo ") = 0.13
- * distance.apply("foo", " foo") = 0.49
- * distance.apply("", "a") = 1.0
- * distance.apply("aaapppp", "") = 1.0
- * distance.apply("frog", "fog") = 0.07
- * distance.apply("fly", "ant") = 1.0
- * distance.apply("elephant", "hippo") = 0.56
- * distance.apply("hippo", "elephant") = 0.56
- * distance.apply("hippo", "zzzzzzzz") = 1.0
- * distance.apply("hello", "hallo") = 0.12
- * distance.apply("ABC Corporation", "ABC Corp") = 0.09
- * distance.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.05
- * distance.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.08
- * distance.apply("PENNSYLVANIA", "PENNCISYLVNIA") = 0.12
- * </pre>
- *
- * @param left the first CharSequence, must not be null
- * @param right the second CharSequence, must not be null
- * @return result distance
- * @throws IllegalArgumentException if either CharSequence input is {@code null}
- */
- @Override
- public Double apply(final CharSequence left, final CharSequence right) {
-
- if (left == null || right == null) {
- throw new IllegalArgumentException("CharSequences must not be null");
- }
-
- return 1 - similarity.apply(left, right);
- }
-
// TODO: remove this method in 2.0, see TEXT-104
/**
* This method returns the Jaro-Winkler string matches, half transpositions, prefix array.
@@ -145,4 +98,51 @@ public class JaroWinklerDistance implements EditDistance<Double> {
}
return new int[] {matches, halfTranspositions, prefix};
}
+
+ /**
+ * Jaro Winkler similarity object used to calculate the distance (1 - similarity).
+ */
+ private final JaroWinklerSimilarity similarity = new JaroWinklerSimilarity();
+
+ /**
+ * Computes the Jaro Winkler Distance between two character sequences.
+ *
+ * <pre>
+ * distance.apply(null, null) = IllegalArgumentException
+ * distance.apply("foo", null) = IllegalArgumentException
+ * distance.apply(null, "foo") = IllegalArgumentException
+ * distance.apply("", "") = 0.0
+ * distance.apply("foo", "foo") = 0.0
+ * distance.apply("foo", "foo ") = 0.06
+ * distance.apply("foo", "foo ") = 0.09
+ * distance.apply("foo", " foo ") = 0.13
+ * distance.apply("foo", " foo") = 0.49
+ * distance.apply("", "a") = 1.0
+ * distance.apply("aaapppp", "") = 1.0
+ * distance.apply("frog", "fog") = 0.07
+ * distance.apply("fly", "ant") = 1.0
+ * distance.apply("elephant", "hippo") = 0.56
+ * distance.apply("hippo", "elephant") = 0.56
+ * distance.apply("hippo", "zzzzzzzz") = 1.0
+ * distance.apply("hello", "hallo") = 0.12
+ * distance.apply("ABC Corporation", "ABC Corp") = 0.09
+ * distance.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.05
+ * distance.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.08
+ * distance.apply("PENNSYLVANIA", "PENNCISYLVNIA") = 0.12
+ * </pre>
+ *
+ * @param left the first CharSequence, must not be null
+ * @param right the second CharSequence, must not be null
+ * @return result distance
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}
+ */
+ @Override
+ public Double apply(final CharSequence left, final CharSequence right) {
+
+ if (left == null || right == null) {
+ throw new IllegalArgumentException("CharSequences must not be null");
+ }
+
+ return 1 - similarity.apply(left, right);
+ }
}
diff --git a/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java b/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
index 3f51860b..d5e26513 100644
--- a/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
+++ b/src/main/java/org/apache/commons/text/similarity/JaroWinklerSimilarity.java
@@ -43,59 +43,6 @@ import org.apache.commons.lang3.StringUtils;
*/
public class JaroWinklerSimilarity implements SimilarityScore<Double> {
- /**
- * Computes the Jaro Winkler Similarity between two character sequences.
- *
- * <pre>
- * sim.apply(null, null) = IllegalArgumentException
- * sim.apply("foo", null) = IllegalArgumentException
- * sim.apply(null, "foo") = IllegalArgumentException
- * sim.apply("", "") = 1.0
- * sim.apply("foo", "foo") = 1.0
- * sim.apply("foo", "foo ") = 0.94
- * sim.apply("foo", "foo ") = 0.91
- * sim.apply("foo", " foo ") = 0.87
- * sim.apply("foo", " foo") = 0.51
- * sim.apply("", "a") = 0.0
- * sim.apply("aaapppp", "") = 0.0
- * sim.apply("frog", "fog") = 0.93
- * sim.apply("fly", "ant") = 0.0
- * sim.apply("elephant", "hippo") = 0.44
- * sim.apply("hippo", "elephant") = 0.44
- * sim.apply("hippo", "zzzzzzzz") = 0.0
- * sim.apply("hello", "hallo") = 0.88
- * sim.apply("ABC Corporation", "ABC Corp") = 0.91
- * sim.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
- * sim.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
- * sim.apply("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
- * </pre>
- *
- * @param left the first CharSequence, must not be null
- * @param right the second CharSequence, must not be null
- * @return result similarity
- * @throws IllegalArgumentException if either CharSequence input is {@code null}
- */
- @Override
- public Double apply(final CharSequence left, final CharSequence right) {
- final double defaultScalingFactor = 0.1;
-
- if (left == null || right == null) {
- throw new IllegalArgumentException("CharSequences must not be null");
- }
-
- if (StringUtils.equals(left, right)) {
- return 1d;
- }
-
- final int[] mtp = matches(left, right);
- final double m = mtp[0];
- if (m == 0) {
- return 0d;
- }
- final double j = ((m / left.length() + m / right.length() + (m - (double) mtp[1] / 2) / m)) / 3;
- return j < 0.7d ? j : j + defaultScalingFactor * mtp[2] * (1d - j);
- }
-
/**
* This method returns the Jaro-Winkler string matches, half transpositions, prefix array.
*
@@ -159,4 +106,57 @@ public class JaroWinklerSimilarity implements SimilarityScore<Double> {
return new int[] {matches, halfTranspositions, prefix};
}
+ /**
+ * Computes the Jaro Winkler Similarity between two character sequences.
+ *
+ * <pre>
+ * sim.apply(null, null) = IllegalArgumentException
+ * sim.apply("foo", null) = IllegalArgumentException
+ * sim.apply(null, "foo") = IllegalArgumentException
+ * sim.apply("", "") = 1.0
+ * sim.apply("foo", "foo") = 1.0
+ * sim.apply("foo", "foo ") = 0.94
+ * sim.apply("foo", "foo ") = 0.91
+ * sim.apply("foo", " foo ") = 0.87
+ * sim.apply("foo", " foo") = 0.51
+ * sim.apply("", "a") = 0.0
+ * sim.apply("aaapppp", "") = 0.0
+ * sim.apply("frog", "fog") = 0.93
+ * sim.apply("fly", "ant") = 0.0
+ * sim.apply("elephant", "hippo") = 0.44
+ * sim.apply("hippo", "elephant") = 0.44
+ * sim.apply("hippo", "zzzzzzzz") = 0.0
+ * sim.apply("hello", "hallo") = 0.88
+ * sim.apply("ABC Corporation", "ABC Corp") = 0.91
+ * sim.apply("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.95
+ * sim.apply("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.92
+ * sim.apply("PENNSYLVANIA", "PENNCISYLVNIA") = 0.88
+ * </pre>
+ *
+ * @param left the first CharSequence, must not be null
+ * @param right the second CharSequence, must not be null
+ * @return result similarity
+ * @throws IllegalArgumentException if either CharSequence input is {@code null}
+ */
+ @Override
+ public Double apply(final CharSequence left, final CharSequence right) {
+ final double defaultScalingFactor = 0.1;
+
+ if (left == null || right == null) {
+ throw new IllegalArgumentException("CharSequences must not be null");
+ }
+
+ if (StringUtils.equals(left, right)) {
+ return 1d;
+ }
+
+ final int[] mtp = matches(left, right);
+ final double m = mtp[0];
+ if (m == 0) {
+ return 0d;
+ }
+ final double j = ((m / left.length() + m / right.length() + (m - (double) mtp[1] / 2) / m)) / 3;
+ return j < 0.7d ? j : j + defaultScalingFactor * mtp[2] * (1d - j);
+ }
+
}
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
index 7d41104a..478f8405 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinDetailedDistance.java
@@ -37,74 +37,99 @@ public class LevenshteinDetailedDistance implements EditDistance<LevenshteinResu
private static final LevenshteinDetailedDistance DEFAULT_INSTANCE = new LevenshteinDetailedDistance();
/**
- * Threshold.
- */
- private final Integer threshold;
-
- /**
- * <p>
- * This returns the default instance that uses a version
- * of the algorithm that does not use a threshold parameter.
- * </p>
+ * Finds count for each of the three [insert, delete, substitute] operations
+ * needed. This is based on the matrix formed based on the two character
+ * sequence.
*
- * @see LevenshteinDetailedDistance#getDefaultInstance()
+ * @param left character sequence which need to be converted from
+ * @param right character sequence which need to be converted to
+ * @param matrix two dimensional array containing
+ * @param swapped tells whether the value for left character sequence and right
+ * character sequence were swapped to save memory
+ * @return result object containing the count of insert, delete and substitute and total count needed
*/
- public LevenshteinDetailedDistance() {
- this(null);
- }
+ private static LevenshteinResults findDetailedResults(final CharSequence left,
+ final CharSequence right,
+ final int[][] matrix,
+ final boolean swapped) {
- /**
- * If the threshold is not null, distance calculations will be limited to a maximum length.
- *
- * <p>If the threshold is null, the unlimited version of the algorithm will be used.</p>
- *
- * @param threshold If this is null then distances calculations will not be limited. This may not be negative.
- */
- public LevenshteinDetailedDistance(final Integer threshold) {
- if (threshold != null && threshold < 0) {
- throw new IllegalArgumentException("Threshold must not be negative");
- }
- this.threshold = threshold;
- }
+ int delCount = 0;
+ int addCount = 0;
+ int subCount = 0;
- /**
- * Finds the Levenshtein distance between two Strings.
- *
- * <p>A higher score indicates a greater distance.</p>
- *
- * <p>The previous implementation of the Levenshtein distance algorithm
- * was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
- *
- * <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
- * which can occur when my Java implementation is used with very large strings.<br>
- * This implementation of the Levenshtein distance algorithm
- * is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
- *
- * <pre>
- * distance.apply(null, *) = IllegalArgumentException
- * distance.apply(*, null) = IllegalArgumentException
- * distance.apply("","") = 0
- * distance.apply("","a") = 1
- * distance.apply("aaapppp", "") = 7
- * distance.apply("frog", "fog") = 1
- * distance.apply("fly", "ant") = 3
- * distance.apply("elephant", "hippo") = 7
- * distance.apply("hippo", "elephant") = 7
- * distance.apply("hippo", "zzzzzzzz") = 8
- * distance.apply("hello", "hallo") = 1
- * </pre>
- *
- * @param left the first string, must not be null
- * @param right the second string, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either String input {@code null}
- */
- @Override
- public LevenshteinResults apply(final CharSequence left, final CharSequence right) {
- if (threshold != null) {
- return limitedCompare(left, right, threshold);
+ int rowIndex = right.length();
+ int columnIndex = left.length();
+
+ int dataAtLeft = 0;
+ int dataAtTop = 0;
+ int dataAtDiagonal = 0;
+ int data = 0;
+ boolean deleted = false;
+ boolean added = false;
+
+ while (rowIndex >= 0 && columnIndex >= 0) {
+
+ if (columnIndex == 0) {
+ dataAtLeft = -1;
+ } else {
+ dataAtLeft = matrix[rowIndex][columnIndex - 1];
+ }
+ if (rowIndex == 0) {
+ dataAtTop = -1;
+ } else {
+ dataAtTop = matrix[rowIndex - 1][columnIndex];
+ }
+ if (rowIndex > 0 && columnIndex > 0) {
+ dataAtDiagonal = matrix[rowIndex - 1][columnIndex - 1];
+ } else {
+ dataAtDiagonal = -1;
+ }
+ if (dataAtLeft == -1 && dataAtTop == -1 && dataAtDiagonal == -1) {
+ break;
+ }
+ data = matrix[rowIndex][columnIndex];
+
+ // case in which the character at left and right are the same,
+ // in this case none of the counters will be incremented.
+ if (columnIndex > 0 && rowIndex > 0 && left.charAt(columnIndex - 1) == right.charAt(rowIndex - 1)) {
+ columnIndex--;
+ rowIndex--;
+ continue;
+ }
+
+ // handling insert and delete cases.
+ deleted = false;
+ added = false;
+ if (data - 1 == dataAtLeft && (data <= dataAtDiagonal && data <= dataAtTop)
+ || (dataAtDiagonal == -1 && dataAtTop == -1)) { // NOPMD
+ columnIndex--;
+ if (swapped) {
+ addCount++;
+ added = true;
+ } else {
+ delCount++;
+ deleted = true;
+ }
+ } else if (data - 1 == dataAtTop && (data <= dataAtDiagonal && data <= dataAtLeft)
+ || (dataAtDiagonal == -1 && dataAtLeft == -1)) { // NOPMD
+ rowIndex--;
+ if (swapped) {
+ delCount++;
+ deleted = true;
+ } else {
+ addCount++;
+ added = true;
+ }
+ }
+
+ // substituted case
+ if (!added && !deleted) {
+ subCount++;
+ columnIndex--;
+ rowIndex--;
+ }
}
- return unlimitedCompare(left, right);
+ return new LevenshteinResults(addCount + delCount + subCount, addCount, delCount, subCount);
}
/**
@@ -116,15 +141,6 @@ public class LevenshteinDetailedDistance implements EditDistance<LevenshteinResu
return DEFAULT_INSTANCE;
}
- /**
- * Gets the distance threshold.
- *
- * @return The distance threshold
- */
- public Integer getThreshold() {
- return threshold;
- }
-
/**
* Finds the Levenshtein distance between two CharSequences if it's less than or
* equal to a given threshold.
@@ -425,98 +441,82 @@ public class LevenshteinDetailedDistance implements EditDistance<LevenshteinResu
}
/**
- * Finds count for each of the three [insert, delete, substitute] operations
- * needed. This is based on the matrix formed based on the two character
- * sequence.
- *
- * @param left character sequence which need to be converted from
- * @param right character sequence which need to be converted to
- * @param matrix two dimensional array containing
- * @param swapped tells whether the value for left character sequence and right
- * character sequence were swapped to save memory
- * @return result object containing the count of insert, delete and substitute and total count needed
+ * Threshold.
*/
- private static LevenshteinResults findDetailedResults(final CharSequence left,
- final CharSequence right,
- final int[][] matrix,
- final boolean swapped) {
-
- int delCount = 0;
- int addCount = 0;
- int subCount = 0;
-
- int rowIndex = right.length();
- int columnIndex = left.length();
-
- int dataAtLeft = 0;
- int dataAtTop = 0;
- int dataAtDiagonal = 0;
- int data = 0;
- boolean deleted = false;
- boolean added = false;
-
- while (rowIndex >= 0 && columnIndex >= 0) {
-
- if (columnIndex == 0) {
- dataAtLeft = -1;
- } else {
- dataAtLeft = matrix[rowIndex][columnIndex - 1];
- }
- if (rowIndex == 0) {
- dataAtTop = -1;
- } else {
- dataAtTop = matrix[rowIndex - 1][columnIndex];
- }
- if (rowIndex > 0 && columnIndex > 0) {
- dataAtDiagonal = matrix[rowIndex - 1][columnIndex - 1];
- } else {
- dataAtDiagonal = -1;
- }
- if (dataAtLeft == -1 && dataAtTop == -1 && dataAtDiagonal == -1) {
- break;
- }
- data = matrix[rowIndex][columnIndex];
+ private final Integer threshold;
- // case in which the character at left and right are the same,
- // in this case none of the counters will be incremented.
- if (columnIndex > 0 && rowIndex > 0 && left.charAt(columnIndex - 1) == right.charAt(rowIndex - 1)) {
- columnIndex--;
- rowIndex--;
- continue;
- }
+ /**
+ * <p>
+ * This returns the default instance that uses a version
+ * of the algorithm that does not use a threshold parameter.
+ * </p>
+ *
+ * @see LevenshteinDetailedDistance#getDefaultInstance()
+ */
+ public LevenshteinDetailedDistance() {
+ this(null);
+ }
- // handling insert and delete cases.
- deleted = false;
- added = false;
- if (data - 1 == dataAtLeft && (data <= dataAtDiagonal && data <= dataAtTop)
- || (dataAtDiagonal == -1 && dataAtTop == -1)) { // NOPMD
- columnIndex--;
- if (swapped) {
- addCount++;
- added = true;
- } else {
- delCount++;
- deleted = true;
- }
- } else if (data - 1 == dataAtTop && (data <= dataAtDiagonal && data <= dataAtLeft)
- || (dataAtDiagonal == -1 && dataAtLeft == -1)) { // NOPMD
- rowIndex--;
- if (swapped) {
- delCount++;
- deleted = true;
- } else {
- addCount++;
- added = true;
- }
- }
+ /**
+ * If the threshold is not null, distance calculations will be limited to a maximum length.
+ *
+ * <p>If the threshold is null, the unlimited version of the algorithm will be used.</p>
+ *
+ * @param threshold If this is null then distances calculations will not be limited. This may not be negative.
+ */
+ public LevenshteinDetailedDistance(final Integer threshold) {
+ if (threshold != null && threshold < 0) {
+ throw new IllegalArgumentException("Threshold must not be negative");
+ }
+ this.threshold = threshold;
+ }
- // substituted case
- if (!added && !deleted) {
- subCount++;
- columnIndex--;
- rowIndex--;
- }
+ /**
+ * Finds the Levenshtein distance between two Strings.
+ *
+ * <p>A higher score indicates a greater distance.</p>
+ *
+ * <p>The previous implementation of the Levenshtein distance algorithm
+ * was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
+ *
+ * <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
+ * which can occur when my Java implementation is used with very large strings.<br>
+ * This implementation of the Levenshtein distance algorithm
+ * is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
+ *
+ * <pre>
+ * distance.apply(null, *) = IllegalArgumentException
+ * distance.apply(*, null) = IllegalArgumentException
+ * distance.apply("","") = 0
+ * distance.apply("","a") = 1
+ * distance.apply("aaapppp", "") = 7
+ * distance.apply("frog", "fog") = 1
+ * distance.apply("fly", "ant") = 3
+ * distance.apply("elephant", "hippo") = 7
+ * distance.apply("hippo", "elephant") = 7
+ * distance.apply("hippo", "zzzzzzzz") = 8
+ * distance.apply("hello", "hallo") = 1
+ * </pre>
+ *
+ * @param left the first string, must not be null
+ * @param right the second string, must not be null
+ * @return result distance, or -1
+ * @throws IllegalArgumentException if either String input {@code null}
+ */
+ @Override
+ public LevenshteinResults apply(final CharSequence left, final CharSequence right) {
+ if (threshold != null) {
+ return limitedCompare(left, right, threshold);
}
- return new LevenshteinResults(addCount + delCount + subCount, addCount, delCount, subCount);
+ return unlimitedCompare(left, right);
+ }
+
+ /**
+ * Gets the distance threshold.
+ *
+ * @return The distance threshold
+ */
+ public Integer getThreshold() {
+ return threshold;
}
}
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
index 7f90a53d..83b1bf3a 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinDistance.java
@@ -40,76 +40,6 @@ public class LevenshteinDistance implements EditDistance<Integer> {
*/
private static final LevenshteinDistance DEFAULT_INSTANCE = new LevenshteinDistance();
- /**
- * Threshold.
- */
- private final Integer threshold;
-
- /**
- * This returns the default instance that uses a version
- * of the algorithm that does not use a threshold parameter.
- *
- * @see LevenshteinDistance#getDefaultInstance()
- */
- public LevenshteinDistance() {
- this(null);
- }
-
- /**
- * If the threshold is not null, distance calculations will be limited to a maximum length.
- * If the threshold is null, the unlimited version of the algorithm will be used.
- *
- * @param threshold
- * If this is null then distances calculations will not be limited.
- * This may not be negative.
- */
- public LevenshteinDistance(final Integer threshold) {
- if (threshold != null && threshold < 0) {
- throw new IllegalArgumentException("Threshold must not be negative");
- }
- this.threshold = threshold;
- }
-
- /**
- * Finds the Levenshtein distance between two Strings.
- *
- * <p>A higher score indicates a greater distance.</p>
- *
- * <p>The previous implementation of the Levenshtein distance algorithm
- * was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
- *
- * <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
- * which can occur when my Java implementation is used with very large strings.<br>
- * This implementation of the Levenshtein distance algorithm
- * is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
- *
- * <pre>
- * distance.apply(null, *) = IllegalArgumentException
- * distance.apply(*, null) = IllegalArgumentException
- * distance.apply("","") = 0
- * distance.apply("","a") = 1
- * distance.apply("aaapppp", "") = 7
- * distance.apply("frog", "fog") = 1
- * distance.apply("fly", "ant") = 3
- * distance.apply("elephant", "hippo") = 7
- * distance.apply("hippo", "elephant") = 7
- * distance.apply("hippo", "zzzzzzzz") = 8
- * distance.apply("hello", "hallo") = 1
- * </pre>
- *
- * @param left the first string, must not be null
- * @param right the second string, must not be null
- * @return result distance, or -1
- * @throws IllegalArgumentException if either String input {@code null}
- */
- @Override
- public Integer apply(final CharSequence left, final CharSequence right) {
- if (threshold != null) {
- return limitedCompare(left, right, threshold);
- }
- return unlimitedCompare(left, right);
- }
-
/**
* Gets the default instance.
*
@@ -119,15 +49,6 @@ public class LevenshteinDistance implements EditDistance<Integer> {
return DEFAULT_INSTANCE;
}
- /**
- * Gets the distance threshold.
- *
- * @return The distance threshold
- */
- public Integer getThreshold() {
- return threshold;
- }
-
/**
* Find the Levenshtein distance between two CharSequences if it's less than or
* equal to a given threshold.
@@ -396,4 +317,83 @@ public class LevenshteinDistance implements EditDistance<Integer> {
return p[n];
}
+ /**
+ * Threshold.
+ */
+ private final Integer threshold;
+
+ /**
+ * This returns the default instance that uses a version
+ * of the algorithm that does not use a threshold parameter.
+ *
+ * @see LevenshteinDistance#getDefaultInstance()
+ */
+ public LevenshteinDistance() {
+ this(null);
+ }
+
+ /**
+ * If the threshold is not null, distance calculations will be limited to a maximum length.
+ * If the threshold is null, the unlimited version of the algorithm will be used.
+ *
+ * @param threshold
+ * If this is null then distances calculations will not be limited.
+ * This may not be negative.
+ */
+ public LevenshteinDistance(final Integer threshold) {
+ if (threshold != null && threshold < 0) {
+ throw new IllegalArgumentException("Threshold must not be negative");
+ }
+ this.threshold = threshold;
+ }
+
+ /**
+ * Finds the Levenshtein distance between two Strings.
+ *
+ * <p>A higher score indicates a greater distance.</p>
+ *
+ * <p>The previous implementation of the Levenshtein distance algorithm
+ * was from <a href="http://www.merriampark.com/ld.htm">http://www.merriampark.com/ld.htm</a></p>
+ *
+ * <p>Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError
+ * which can occur when my Java implementation is used with very large strings.<br>
+ * This implementation of the Levenshtein distance algorithm
+ * is from <a href="http://www.merriampark.com/ldjava.htm">http://www.merriampark.com/ldjava.htm</a></p>
+ *
+ * <pre>
+ * distance.apply(null, *) = IllegalArgumentException
+ * distance.apply(*, null) = IllegalArgumentException
+ * distance.apply("","") = 0
+ * distance.apply("","a") = 1
+ * distance.apply("aaapppp", "") = 7
+ * distance.apply("frog", "fog") = 1
+ * distance.apply("fly", "ant") = 3
+ * distance.apply("elephant", "hippo") = 7
+ * distance.apply("hippo", "elephant") = 7
+ * distance.apply("hippo", "zzzzzzzz") = 8
+ * distance.apply("hello", "hallo") = 1
+ * </pre>
+ *
+ * @param left the first string, must not be null
+ * @param right the second string, must not be null
+ * @return result distance, or -1
+ * @throws IllegalArgumentException if either String input {@code null}
+ */
+ @Override
+ public Integer apply(final CharSequence left, final CharSequence right) {
+ if (threshold != null) {
+ return limitedCompare(left, right, threshold);
+ }
+ return unlimitedCompare(left, right);
+ }
+
+ /**
+ * Gets the distance threshold.
+ *
+ * @return The distance threshold
+ */
+ public Integer getThreshold() {
+ return threshold;
+ }
+
}
diff --git a/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java b/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
index c1935ce7..a3632d71 100644
--- a/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
+++ b/src/main/java/org/apache/commons/text/similarity/LevenshteinResults.java
@@ -66,6 +66,29 @@ public class LevenshteinResults {
this.substituteCount = substituteCount;
}
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ final LevenshteinResults result = (LevenshteinResults) o;
+ return Objects.equals(distance, result.distance) && Objects.equals(insertCount, result.insertCount)
+ && Objects.equals(deleteCount, result.deleteCount)
+ && Objects.equals(substituteCount, result.substituteCount);
+ }
+
+ /**
+ * Gets the number of character deletion needed to change one character sequence to other.
+ *
+ * @return delete character count
+ */
+ public Integer getDeleteCount() {
+ return deleteCount;
+ }
+
/**
* Gets the distance between two character sequences.
*
@@ -84,15 +107,6 @@ public class LevenshteinResults {
return insertCount;
}
- /**
- * Gets the number of character deletion needed to change one character sequence to other.
- *
- * @return delete character count
- */
- public Integer getDeleteCount() {
- return deleteCount;
- }
-
/**
* Gets the number of character substitution needed to change one character sequence into another.
*
@@ -102,20 +116,6 @@ public class LevenshteinResults {
return substituteCount;
}
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
- final LevenshteinResults result = (LevenshteinResults) o;
- return Objects.equals(distance, result.distance) && Objects.equals(insertCount, result.insertCount)
- && Objects.equals(deleteCount, result.deleteCount)
- && Objects.equals(substituteCount, result.substituteCount);
- }
-
@Override
public int hashCode() {
return Objects.hash(distance, insertCount, deleteCount, substituteCount);
diff --git a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
index c2ab36e0..3629bab6 100644
--- a/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
+++ b/src/main/java/org/apache/commons/text/similarity/LongestCommonSubsequence.java
@@ -50,47 +50,6 @@ package org.apache.commons.text.similarity;
* @since 1.0
*/
public class LongestCommonSubsequence implements SimilarityScore<Integer> {
- /**
- * Calculates the longest common subsequence similarity score of two {@code CharSequence}'s passed as
- * input.
- *
- * <p>
- * This method implements a more efficient version of LCS algorithm which has quadratic time and
- * linear space complexity.
- * </p>
- *
- * <p>
- * This method is based on newly implemented {@link #algorithmB(CharSequence, CharSequence)}.
- * An evaluation using JMH revealed that this method is almost two times faster than its previous version.
- * </p>
- *
- * @param left first character sequence
- * @param right second character sequence
- * @return length of the longest common subsequence of <code>left</code> and <code>right</code>
- * @throws IllegalArgumentException if either String input {@code null}
- */
- @Override
- public Integer apply(final CharSequence left, final CharSequence right) {
- // Quick return for invalid inputs
- if (left == null || right == null) {
- throw new IllegalArgumentException("Inputs must not be null");
- }
- // Find lengths of two strings
- final int leftSz = left.length();
- final int rightSz = right.length();
-
- // Check if we can avoid calling algorithmB which involves heap space allocation
- if (leftSz == 0 || rightSz == 0) {
- return 0;
- }
-
- // Check if we can save even more space
- if (leftSz < rightSz) {
- return algorithmB(right, left)[leftSz];
- }
- return algorithmB(left, right)[rightSz];
- }
-
/**
* An implementation of "ALG B" from Hirschberg's CACM '71 paper.
* Assuming the first input sequence is of size <code>m</code> and the second input sequence is of size
@@ -134,6 +93,106 @@ public class LongestCommonSubsequence implements SimilarityScore<Integer> {
return dpRows[1];
}
+ /**
+ * An implementation of "ALG C" from Hirschberg's CACM '71 paper.
+ * Assuming the first input sequence is of size <code>m</code> and the second input sequence is of size
+ * <code>n</code>, this method returns the Longest Common Subsequence (LCS) of the two sequences in
+ * <i>O(m*n)</i> time and <i>O(m+n)</i> space.
+ *
+ * @param left first input sequence.
+ * @param right second input sequence.
+ * @return the LCS of <code>left</code> and <code>right</code>
+ * @since 1.10
+ */
+ private static String algorithmC(final CharSequence left, final CharSequence right) {
+ final int m = left.length();
+ final int n = right.length();
+
+ final StringBuilder out = new StringBuilder();
+
+ if (m == 1) { // Handle trivial cases, as per the paper
+ final char leftCh = left.charAt(0);
+ for (int j = 0; j < n; j++) {
+ if (leftCh == right.charAt(j)) {
+ out.append(leftCh);
+ break;
+ }
+ }
+ } else if (n > 0 && m > 1) {
+ final int mid = m / 2; // Find the middle point
+
+ final CharSequence leftFirstPart = left.subSequence(0, mid);
+ final CharSequence leftSecondPart = left.subSequence(mid, m);
+
+ // Step 3 of the algorithm: two calls to Algorithm B
+ final int[] l1 = algorithmB(leftFirstPart, right);
+ final int[] l2 = algorithmB(reverse(leftSecondPart), reverse(right));
+
+ // Find k, as per the Step 4 of the algorithm
+ int k = 0;
+ int t = 0;
+ for (int j = 0; j <= n; j++) {
+ final int s = l1[j] + l2[n - j];
+ if (t < s) {
+ t = s;
+ k = j;
+ }
+ }
+
+ // Step 5: solve simpler problems, recursively
+ out.append(algorithmC(leftFirstPart, right.subSequence(0, k)));
+ out.append(algorithmC(leftSecondPart, right.subSequence(k, n)));
+ }
+
+ return out.toString();
+ }
+
+ // An auxiliary method for CharSequence reversal
+ private static String reverse(final CharSequence s) {
+ return (new StringBuilder(s)).reverse().toString();
+ }
+
+ /**
+ * Calculates the longest common subsequence similarity score of two {@code CharSequence}'s passed as
+ * input.
+ *
+ * <p>
+ * This method implements a more efficient version of LCS algorithm which has quadratic time and
+ * linear space complexity.
+ * </p>
+ *
+ * <p>
+ * This method is based on newly implemented {@link #algorithmB(CharSequence, CharSequence)}.
+ * An evaluation using JMH revealed that this method is almost two times faster than its previous version.
+ * </p>
+ *
+ * @param left first character sequence
+ * @param right second character sequence
+ * @return length of the longest common subsequence of <code>left</code> and <code>right</code>
+ * @throws IllegalArgumentException if either String input {@code null}
+ */
+ @Override
+ public Integer apply(final CharSequence left, final CharSequence right) {
+ // Quick return for invalid inputs
+ if (left == null || right == null) {
+ throw new IllegalArgumentException("Inputs must not be null");
+ }
+ // Find lengths of two strings
+ final int leftSz = left.length();
+ final int rightSz = right.length();
+
+ // Check if we can avoid calling algorithmB which involves heap space allocation
+ if (leftSz == 0 || rightSz == 0) {
+ return 0;
+ }
+
+ // Check if we can save even more space
+ if (leftSz < rightSz) {
+ return algorithmB(right, left)[leftSz];
+ }
+ return algorithmB(left, right)[rightSz];
+ }
+
/**
* Computes the longest common subsequence between the two {@code CharSequence}'s passed as input.
*
@@ -213,65 +272,6 @@ public class LongestCommonSubsequence implements SimilarityScore<Integer> {
return algorithmC(left, right);
}
- /**
- * An implementation of "ALG C" from Hirschberg's CACM '71 paper.
- * Assuming the first input sequence is of size <code>m</code> and the second input sequence is of size
- * <code>n</code>, this method returns the Longest Common Subsequence (LCS) of the two sequences in
- * <i>O(m*n)</i> time and <i>O(m+n)</i> space.
- *
- * @param left first input sequence.
- * @param right second input sequence.
- * @return the LCS of <code>left</code> and <code>right</code>
- * @since 1.10
- */
- private static String algorithmC(final CharSequence left, final CharSequence right) {
- final int m = left.length();
- final int n = right.length();
-
- final StringBuilder out = new StringBuilder();
-
- if (m == 1) { // Handle trivial cases, as per the paper
- final char leftCh = left.charAt(0);
- for (int j = 0; j < n; j++) {
- if (leftCh == right.charAt(j)) {
- out.append(leftCh);
- break;
- }
- }
- } else if (n > 0 && m > 1) {
- final int mid = m / 2; // Find the middle point
-
- final CharSequence leftFirstPart = left.subSequence(0, mid);
- final CharSequence leftSecondPart = left.subSequence(mid, m);
-
- // Step 3 of the algorithm: two calls to Algorithm B
- final int[] l1 = algorithmB(leftFirstPart, right);
- final int[] l2 = algorithmB(reverse(leftSecondPart), reverse(right));
-
- // Find k, as per the Step 4 of the algorithm
- int k = 0;
- int t = 0;
- for (int j = 0; j <= n; j++) {
- final int s = l1[j] + l2[n - j];
- if (t < s) {
- t = s;
- k = j;
- }
- }
-
- // Step 5: solve simpler problems, recursively
- out.append(algorithmC(leftFirstPart, right.subSequence(0, k)));
- out.append(algorithmC(leftSecondPart, right.subSequence(k, n)));
- }
-
- return out.toString();
- }
-
- // An auxiliary method for CharSequence reversal
- private static String reverse(final CharSequence s) {
- return (new StringBuilder(s)).reverse().toString();
- }
-
/**
* Computes the lcsLengthArray for the sake of doing the actual lcs calculation. This is the
* dynamic programming portion of the algorithm, and is the reason for the runtime complexity being
diff --git a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java b/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
index d1005bcc..7788f66d 100644
--- a/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
+++ b/src/test/java/org/apache/commons/text/StringSubstitutorTest.java
@@ -754,6 +754,28 @@ public class StringSubstitutorTest {
assertThatNullPointerException().isThrownBy(() -> StringSubstitutor.replace(null, (Properties) null));
}
+ @Test
+ public void testReplaceThrowsStringIndexOutOfBoundsException() {
+ final StringSubstitutor sub = new StringSubstitutor();
+
+ // replace(char[], int, int)
+ final char[] emptyCharArray = {};
+ // offset greater than array length
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
+ () -> sub.replace(emptyCharArray, 0, 1));
+ // source != null && (offset > source.length || offset < 0)
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
+ () -> sub.replace(emptyCharArray, 1, 0));
+
+ // replace(String, int, int)
+ // offset greater than source length
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
+ () -> sub.replace("", 1, 1));
+ // source != null && offset >= 0 && offset <= source.length() && (length > -offset + source.length() || length < 0)
+ assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
+ () -> sub.replace("", 0, 1));
+ }
+
/**
* Tests replace creates output same as input.
*/
@@ -1086,26 +1108,4 @@ public class StringSubstitutorTest {
assertEqualsCharSeq("value $${escaped}", replace(sub, org));
}
- @Test
- public void testReplaceThrowsStringIndexOutOfBoundsException() {
- final StringSubstitutor sub = new StringSubstitutor();
-
- // replace(char[], int, int)
- final char[] emptyCharArray = {};
- // offset greater than array length
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
- () -> sub.replace(emptyCharArray, 0, 1));
- // source != null && (offset > source.length || offset < 0)
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
- () -> sub.replace(emptyCharArray, 1, 0));
-
- // replace(String, int, int)
- // offset greater than source length
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
- () -> sub.replace("", 1, 1));
- // source != null && offset >= 0 && offset <= source.length() && (length > -offset + source.length() || length < 0)
- assertThatExceptionOfType(StringIndexOutOfBoundsException.class).isThrownBy(
- () -> sub.replace("", 0, 1));
- }
-
}
diff --git a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java b/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
index b7ec5ac4..001ee5a9 100644
--- a/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
+++ b/src/test/java/org/apache/commons/text/diff/ReplacementsFinderTest.java
@@ -34,33 +34,6 @@ import org.junit.jupiter.params.provider.MethodSource;
*/
public class ReplacementsFinderTest {
- private SimpleHandler handler;
-
- @BeforeEach
- public void setUp() {
- handler = new SimpleHandler();
- }
-
- public static Stream<Arguments> 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<Character> replacementFinder = new ReplacementsFinder<>(handler);
- sc.getScript().visit(replacementFinder);
- assertThat(handler.getSkipped()).as("Skipped characters do not match").isEqualTo(skipped);
- assertArrayEquals(handler.getFrom().toArray(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY), from,
- "From characters do not match");
- assertArrayEquals(to, handler.getTo().toArray(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY),
- "To characters do not match");
- }
-
// Helper ReplacementsHandler implementation for testing
private static class SimpleHandler implements ReplacementsHandler<Character> {
private int skipped;
@@ -73,14 +46,14 @@ public class ReplacementsFinderTest {
to = new ArrayList<>();
}
- public int getSkipped() {
- return skipped;
- }
-
public List<Character> getFrom() {
return from;
}
+ public int getSkipped() {
+ return skipped;
+ }
+
public List<Character> getTo() {
return to;
}
@@ -92,4 +65,31 @@ public class ReplacementsFinderTest {
this.to.addAll(to);
}
}
+
+ public static Stream<Arguments> 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'}));
+ }
+
+ private SimpleHandler handler;
+
+ @BeforeEach
+ public void setUp() {
+ handler = new SimpleHandler();
+ }
+
+ @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<Character> replacementFinder = new ReplacementsFinder<>(handler);
+ sc.getScript().visit(replacementFinder);
+ assertThat(handler.getSkipped()).as("Skipped characters do not match").isEqualTo(skipped);
+ assertArrayEquals(handler.getFrom().toArray(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY), from,
+ "From characters do not match");
+ assertArrayEquals(to, handler.getTo().toArray(ArrayUtils.EMPTY_CHARACTER_OBJECT_ARRAY),
+ "To characters do not match");
+ }
}
diff --git a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java b/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
index a64928f9..9c76d472 100644
--- a/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
+++ b/src/test/java/org/apache/commons/text/diff/StringsComparatorTest.java
@@ -28,36 +28,6 @@ import org.junit.jupiter.api.Test;
* Tests for the StringsComparator.
*/
public class StringsComparatorTest {
- private List<String> before;
- private List<String> 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<Character> ev = new ExecutionVisitor<>();
- new StringsComparator(before.get(i), after.get(i)).getScript().visit(ev);
- assertThat(ev.getString()).isEqualTo(after.get(i));
- }
- }
-
private static class ExecutionVisitor<T> implements CommandVisitor<T> {
private final StringBuilder v;
@@ -66,24 +36,29 @@ public class StringsComparatorTest {
v = new StringBuilder();
}
- @Override
- public void visitInsertCommand(final T object) {
- v.append(object);
+ public String getString() {
+ return v.toString();
}
@Override
- public void visitKeepCommand(final T object) {
- v.append(object);
+ public void visitDeleteCommand(final T object) {
+ // noop
}
@Override
- public void visitDeleteCommand(final T object) {
- // noop
+ public void visitInsertCommand(final T object) {
+ v.append(object);
}
- public String getString() {
- return v.toString();
+ @Override
+ public void visitKeepCommand(final T object) {
+ v.append(object);
}
}
+ private List<String> before;
+ private List<String> after;
+ private int[] length;
+
+ private int[] lcs;
@BeforeEach
public void setUp() {
@@ -130,10 +105,35 @@ public class StringsComparatorTest {
2
};
}
+
@AfterEach
public void tearDown() {
before = null;
after = null;
length = null;
}
+
+ @Test
+ public void testExecution() {
+ for (int i = 0; i < before.size(); ++i) {
+ final ExecutionVisitor<Character> ev = new ExecutionVisitor<>();
+ new StringsComparator(before.get(i), after.get(i)).getScript().visit(ev);
+ assertThat(ev.getString()).isEqualTo(after.get(i));
+ }
+ }
+
+ @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]);
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/text/jmh/DoubleFormatPerformance.java b/src/test/java/org/apache/commons/text/jmh/DoubleFormatPerformance.java
index 92c3c7c8..bbae86a2 100644
--- a/src/test/java/org/apache/commons/text/jmh/DoubleFormatPerformance.java
+++ b/src/test/java/org/apache/commons/text/jmh/DoubleFormatPerformance.java
@@ -48,18 +48,6 @@ import org.openjdk.jmh.infra.Blackhole;
@Fork(value = 1, jvmArgs = {"-server", "-Xms512M", "-Xmx512M"})
public class DoubleFormatPerformance {
- /** Decimal format pattern for plain output. */
- private static final String PLAIN_PATTERN = "0.0##";
-
- /** Decimal format pattern for plain output with thousands grouping. */
- private static final String PLAIN_GROUPED_PATTERN = "#,##0.0##";
-
- /** Decimal format pattern for scientific output. */
- private static final String SCI_PATTERN = "0.0##E0";
-
- /** Decimal format pattern for engineering output. */
- private static final String ENG_PATTERN = "##0.0##E0";
-
/** Benchmark input providing a source of random double values. */
@State(Scope.Thread)
public static class DoubleInput {
@@ -94,6 +82,18 @@ public class DoubleFormatPerformance {
}
}
+ /** Decimal format pattern for plain output. */
+ private static final String PLAIN_PATTERN = "0.0##";
+
+ /** Decimal format pattern for plain output with thousands grouping. */
+ private static final String PLAIN_GROUPED_PATTERN = "#,##0.0##";
+
+ /** Decimal format pattern for scientific output. */
+ private static final String SCI_PATTERN = "0.0##E0";
+
+ /** Decimal format pattern for engineering output. */
+ private static final String ENG_PATTERN = "##0.0##E0";
+
/** Create a random double value with exponent in the range {@code [minExp, maxExp]}.
* @param minExp minimum exponent; must be less than {@code maxExp}
* @param maxExp maximum exponent; must be greater than {@code minExp}
@@ -148,24 +148,6 @@ public class DoubleFormatPerformance {
runDoubleFunction(input, bh, d -> "0.0");
}
- /** Benchmark testing the {@link Double#toString()} method.
- * @param input benchmark state input
- * @param bh jmh blackhole for consuming output
- */
- @Benchmark
- public void doubleToString(final DoubleInput input, final Blackhole bh) {
- runDoubleFunction(input, bh, Double::toString);
- }
-
- /** Benchmark testing the {@link String#format(String, Object...)} method.
- * @param input benchmark state input
- * @param bh jmh blackhole for consuming output
- */
- @Benchmark
- public void stringFormat(final DoubleInput input, final Blackhole bh) {
- runDoubleFunction(input, bh, d -> String.format("%f", d));
- }
-
/** Benchmark testing the BigDecimal formatting performance.
* @param input benchmark state input
* @param bh jmh blackhole for consuming output
@@ -179,6 +161,16 @@ public class DoubleFormatPerformance {
runDoubleFunction(input, bh, fn);
}
+ /** Benchmark testing the {@link DecimalFormat} class with engineering format.
+ * @param input benchmark state input
+ * @param bh jmh blackhole for consuming output
+ */
+ @Benchmark
+ public void decimalFormatEngineering(final DoubleInput input, final Blackhole bh) {
+ final DecimalFormat fmt = new DecimalFormat(ENG_PATTERN);
+ runDoubleFunction(input, bh, fmt::format);
+ }
+
/** Benchmark testing the {@link DecimalFormat} class.
* @param input benchmark state input
* @param bh jmh blackhole for consuming output
@@ -209,14 +201,17 @@ public class DoubleFormatPerformance {
runDoubleFunction(input, bh, fmt::format);
}
- /** Benchmark testing the {@link DecimalFormat} class with engineering format.
+ /** Benchmark testing the {@link DoubleFormat#ENGINEERING} format.
* @param input benchmark state input
* @param bh jmh blackhole for consuming output
*/
@Benchmark
- public void decimalFormatEngineering(final DoubleInput input, final Blackhole bh) {
- final DecimalFormat fmt = new DecimalFormat(ENG_PATTERN);
- runDoubleFunction(input, bh, fmt::format);
+ public void doubleFormatEngineering(final DoubleInput input, final Blackhole bh) {
+ final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
+ .maxPrecision(6)
+ .alwaysIncludeExponent(true)
+ .build();
+ runDoubleFunction(input, bh, fmt);
}
/** Benchmark testing the {@link DoubleFormat#PLAIN} format.
@@ -258,16 +253,21 @@ public class DoubleFormatPerformance {
runDoubleFunction(input, bh, fmt);
}
- /** Benchmark testing the {@link DoubleFormat#ENGINEERING} format.
+ /** Benchmark testing the {@link Double#toString()} method.
* @param input benchmark state input
* @param bh jmh blackhole for consuming output
*/
@Benchmark
- public void doubleFormatEngineering(final DoubleInput input, final Blackhole bh) {
- final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
- .maxPrecision(6)
- .alwaysIncludeExponent(true)
- .build();
- runDoubleFunction(input, bh, fmt);
+ public void doubleToString(final DoubleInput input, final Blackhole bh) {
+ runDoubleFunction(input, bh, Double::toString);
+ }
+
+ /** Benchmark testing the {@link String#format(String, Object...)} method.
+ * @param input benchmark state input
+ * @param bh jmh blackhole for consuming output
+ */
+ @Benchmark
+ public void stringFormat(final DoubleInput input, final Blackhole bh) {
+ runDoubleFunction(input, bh, d -> String.format("%f", d));
}
}
diff --git a/src/test/java/org/apache/commons/text/jmh/LongestCommonSubsequencePerformance.java b/src/test/java/org/apache/commons/text/jmh/LongestCommonSubsequencePerformance.java
index 87914834..5b2787fa 100644
--- a/src/test/java/org/apache/commons/text/jmh/LongestCommonSubsequencePerformance.java
+++ b/src/test/java/org/apache/commons/text/jmh/LongestCommonSubsequencePerformance.java
@@ -51,62 +51,6 @@ import org.openjdk.jmh.annotations.Warmup;
@Measurement(iterations = 5, time = 1)
@Fork(value = 1, jvmArgs = {"-server", "-Xms512M", "-Xmx512M"})
public class LongestCommonSubsequencePerformance {
- @State(Scope.Benchmark)
- public static class InputData {
- final List<Pair<CharSequence, CharSequence>> inputs = new ArrayList<>();
-
- @Setup(Level.Trial)
- public void setup() {
- final ClassLoader classloader = Thread.currentThread().getContextClassLoader();
- try (InputStream is = classloader.getResourceAsStream("org/apache/commons/text/lcs-perf-analysis-inputs.csv");
- InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is));
- BufferedReader br = new BufferedReader(isr)) {
- String line;
- while ((line = br.readLine()) != null && !line.trim().isEmpty()) {
- line = line.trim();
- final int indexOfComma = line.indexOf(',');
- final String inputA = line.substring(0, indexOfComma);
- final String inputB = line.substring(1 + indexOfComma);
- this.inputs.add(ImmutablePair.of(inputA, inputB));
- }
- } catch (final IOException exception) {
- throw new UncheckedIOException(exception.getMessage(), exception);
- }
- }
- }
-
- @Benchmark
- public void testLCSLenBaseline(final InputData data) {
- final BaselineLongestCommonSubsequence lcs = new BaselineLongestCommonSubsequence();
- for (final Pair<CharSequence, CharSequence> input : data.inputs) {
- lcs.apply(input.getLeft(), input.getRight());
- }
- }
-
- @Benchmark
- public void testLCSBaseline(final InputData data) {
- final BaselineLongestCommonSubsequence lcs = new BaselineLongestCommonSubsequence();
- for (final Pair<CharSequence, CharSequence> input : data.inputs) {
- lcs.longestCommonSubsequence(input.getLeft(), input.getRight());
- }
- }
-
- @Benchmark
- public void testLCSLen(final InputData data) {
- final LongestCommonSubsequence lcs = new LongestCommonSubsequence();
- for (final Pair<CharSequence, CharSequence> input : data.inputs) {
- lcs.apply(input.getLeft(), input.getRight());
- }
- }
-
- @Benchmark
- public void testLCS(final InputData data) {
- final LongestCommonSubsequence lcs = new LongestCommonSubsequence();
- for (final Pair<CharSequence, CharSequence> input : data.inputs) {
- lcs.longestCommonSubsequence(input.getLeft(), input.getRight());
- }
- }
-
/**
* Older implementation of LongestCommonSubsequence.
* Code is copied from Apache Commons Text version 1.10.0-SNAPSHOT
@@ -164,4 +108,60 @@ public class LongestCommonSubsequencePerformance {
return lcsLengthArray;
}
}
+
+ @State(Scope.Benchmark)
+ public static class InputData {
+ final List<Pair<CharSequence, CharSequence>> inputs = new ArrayList<>();
+
+ @Setup(Level.Trial)
+ public void setup() {
+ final ClassLoader classloader = Thread.currentThread().getContextClassLoader();
+ try (InputStream is = classloader.getResourceAsStream("org/apache/commons/text/lcs-perf-analysis-inputs.csv");
+ InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is));
+ BufferedReader br = new BufferedReader(isr)) {
+ String line;
+ while ((line = br.readLine()) != null && !line.trim().isEmpty()) {
+ line = line.trim();
+ final int indexOfComma = line.indexOf(',');
+ final String inputA = line.substring(0, indexOfComma);
+ final String inputB = line.substring(1 + indexOfComma);
+ this.inputs.add(ImmutablePair.of(inputA, inputB));
+ }
+ } catch (final IOException exception) {
+ throw new UncheckedIOException(exception.getMessage(), exception);
+ }
+ }
+ }
+
+ @Benchmark
+ public void testLCS(final InputData data) {
+ final LongestCommonSubsequence lcs = new LongestCommonSubsequence();
+ for (final Pair<CharSequence, CharSequence> input : data.inputs) {
+ lcs.longestCommonSubsequence(input.getLeft(), input.getRight());
+ }
+ }
+
+ @Benchmark
+ public void testLCSBaseline(final InputData data) {
+ final BaselineLongestCommonSubsequence lcs = new BaselineLongestCommonSubsequence();
+ for (final Pair<CharSequence, CharSequence> input : data.inputs) {
+ lcs.longestCommonSubsequence(input.getLeft(), input.getRight());
+ }
+ }
+
+ @Benchmark
+ public void testLCSLen(final InputData data) {
+ final LongestCommonSubsequence lcs = new LongestCommonSubsequence();
+ for (final Pair<CharSequence, CharSequence> input : data.inputs) {
+ lcs.apply(input.getLeft(), input.getRight());
+ }
+ }
+
+ @Benchmark
+ public void testLCSLenBaseline(final InputData data) {
+ final BaselineLongestCommonSubsequence lcs = new BaselineLongestCommonSubsequence();
+ for (final Pair<CharSequence, CharSequence> input : data.inputs) {
+ lcs.apply(input.getLeft(), input.getRight());
+ }
+ }
}
diff --git a/src/test/java/org/apache/commons/text/numbers/DoubleFormatTest.java b/src/test/java/org/apache/commons/text/numbers/DoubleFormatTest.java
index 3df3e1b0..052ad590 100644
--- a/src/test/java/org/apache/commons/text/numbers/DoubleFormatTest.java
+++ b/src/test/java/org/apache/commons/text/numbers/DoubleFormatTest.java
@@ -28,6 +28,142 @@ import org.junit.jupiter.api.Test;
class DoubleFormatTest {
+ private static void assertLocalizedFormatsAreEqual(final double d, final DecimalFormat df,
+ final DoubleFunction<String> fmt, final Locale loc) {
+ // NOTE: Perform the string comparison only on non-format characters. This is required because
+ // JDK 16 adds directionality characters to strings for certain locales, such as Arabic, whereas
+ // previous JDKs do not. We will match the behavior of the previous versions here and ignore formatting
+ // for test purposes.
+ final String dfStr = trimFormatChars(df.format(d));
+ final String fmtStr = trimFormatChars(fmt.apply(d));
+
+ Assertions.assertEquals(dfStr, fmtStr,
+ () -> "Unexpected output for locale [" + loc.toLanguageTag() + "] and double value " + d);
+ }
+
+ private static void checkDefaultFormatSpecial(final DoubleFunction<String> fmt) {
+ checkFormat(fmt, 0.0, "0.0");
+ checkFormat(fmt, -0.0, "-0.0");
+ checkFormat(fmt, Double.NaN, "NaN");
+ checkFormat(fmt, Double.POSITIVE_INFINITY, "Infinity");
+ checkFormat(fmt, Double.NEGATIVE_INFINITY, "-Infinity");
+ }
+
+ private static void checkFormat(final DoubleFunction<String> fmt, final double d, final String str) {
+ Assertions.assertEquals(str, fmt.apply(d));
+ }
+
+ /** Check that the given double value can be exactly recovered from formatted string representation
+ * produced by the format instance.
+ * @param fmt format instance
+ * @param d input double value
+ */
+ private static void checkFormatAccuracy(final DoubleFunction<String> fmt, final double d) {
+ final String str = fmt.apply(d);
+ final double parsed = Double.parseDouble(str);
+ Assertions.assertEquals(d, parsed, () -> "Formatted double string [" + str + "] did not match input value");
+ }
+
+ /** Check that the given format type correctly formats doubles when using the
+ * default configuration options. The format itself is not checked; only the
+ * fact that the input double can be successfully recovered using {@link Double#parseDouble(String)}
+ * is asserted.
+ * @param type format type
+ */
+ private static void checkFormatAccuracyWithDefaults(final DoubleFormat type) {
+ final DoubleFunction<String> fmt = type.builder().build();
+
+ checkDefaultFormatSpecial(fmt);
+
+ checkFormatAccuracy(fmt, Double.MIN_VALUE);
+ checkFormatAccuracy(fmt, -Double.MIN_VALUE);
+
+ checkFormatAccuracy(fmt, Double.MIN_NORMAL);
+ checkFormatAccuracy(fmt, -Double.MIN_NORMAL);
+
+ checkFormatAccuracy(fmt, Double.MAX_VALUE);
+ checkFormatAccuracy(fmt, -Double.MAX_VALUE);
+
+ checkFormatAccuracy(fmt, Math.PI);
+ checkFormatAccuracy(fmt, Math.E);
+
+ final Random rnd = new Random(10L);
+ final int cnt = 1000;
+ for (int i = 0; i < cnt; ++i) {
+ checkFormatAccuracy(fmt, randomDouble(rnd));
+ }
+ }
+
+ private static void checkLocalizedFormat(final Locale loc, final String pattern,
+ final Function<Locale, DoubleFunction<String>> factory) {
+ // arrange
+ final DecimalFormat df = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(loc));
+ final DoubleFunction<String> fmt = factory.apply(loc);
+
+ // act/assert
+ assertLocalizedFormatsAreEqual(0.0, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(Double.POSITIVE_INFINITY, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(Double.NEGATIVE_INFINITY, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(Double.NaN, df, fmt, loc);
+
+ assertLocalizedFormatsAreEqual(1.0, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(-1.0, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(Math.PI, df, fmt, loc);
+ assertLocalizedFormatsAreEqual(Math.E, df, fmt, loc);
+
+ final Random rnd = new Random(12L);
+ final int minExp = -100;
+ final int maxExp = 100;
+ final int cnt = 1000;
+ for (int i = 0; i < cnt; ++i) {
+ assertLocalizedFormatsAreEqual(randomDouble(minExp, maxExp, rnd), df, fmt, loc);
+ }
+ }
+
+ private static void checkLocalizedFormats(final String pattern,
+ final Function<Locale, DoubleFunction<String>> factory) {
+ for (final Locale loc : Locale.getAvailableLocales()) {
+ checkLocalizedFormat(loc, pattern, factory);
+ }
+ }
+
+ /** Create a random double value with exponent in the range {@code [minExp, maxExp]}.
+ * @param minExp minimum exponent; must be less than {@code maxExp}
+ * @param maxExp maximum exponent; must be greater than {@code minExp}
+ * @param rnd random number generator
+ * @return random double
+ */
+ private static double randomDouble(final int minExp, final int maxExp, final Random rnd) {
+ // Create random doubles using random bits in the sign bit and the mantissa.
+ final long mask = ((1L << 52) - 1) | 1L << 63;
+ final long bits = rnd.nextLong() & mask;
+ // The exponent must be unsigned so + 1023 to the signed exponent
+ final long exp = rnd.nextInt(maxExp - minExp + 1) + minExp + 1023;
+ return Double.longBitsToDouble(bits | (exp << 52));
+ }
+
+ /** Create a random double value using the full range of exponent values.
+ * @param rnd random number generator
+ * @return random double
+ */
+ private static double randomDouble(final Random rnd) {
+ return randomDouble(Double.MIN_EXPONENT, Double.MAX_EXPONENT, rnd);
+ }
+
+ /** Remove Unicode {@link Character#FORMAT format} characters from the given string.
+ * @param str input string
+ * @return input string with format characters removed
+ */
+ private static String trimFormatChars(final String str) {
+ final StringBuilder sb = new StringBuilder();
+ for (final char c : str.toCharArray()) {
+ if (Character.getType(c) != Character.FORMAT) {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
@Test
void testBuilder_illegalArgs() {
// arrange
@@ -45,65 +181,35 @@ class DoubleFormatTest {
}
@Test
- void testFormatAccuracy() {
- // act/assert
- checkFormatAccuracyWithDefaults(DoubleFormat.PLAIN);
- checkFormatAccuracyWithDefaults(DoubleFormat.MIXED);
- checkFormatAccuracyWithDefaults(DoubleFormat.SCIENTIFIC);
- checkFormatAccuracyWithDefaults(DoubleFormat.ENGINEERING);
- }
-
- @Test
- void testPlain_defaults() {
+ void testCustomDigitString() {
// arrange
- final DoubleFunction<String> fmt = DoubleFormat.PLAIN.builder()
- .build();
+ final String digits = "abcdefghij";
+ final DoubleFunction<String> plain = DoubleFormat.PLAIN.builder().digits(digits).build();
+ final DoubleFunction<String> sci = DoubleFormat.SCIENTIFIC.builder().digits(digits).build();
+ final DoubleFunction<String> eng = DoubleFormat.ENGINEERING.builder().digits(digits).build();
+ final DoubleFunction<String> mixed = DoubleFormat.MIXED.builder().digits(digits).build();
// act/assert
- checkFormat(fmt, 0.00001, "0.00001");
- checkFormat(fmt, -0.0001, "-0.0001");
- checkFormat(fmt, 0.001, "0.001");
- checkFormat(fmt, -0.01, "-0.01");
- checkFormat(fmt, 0.1, "0.1");
- checkFormat(fmt, -0.0, "-0.0");
- checkFormat(fmt, 0.0, "0.0");
- checkFormat(fmt, -1.0, "-1.0");
- checkFormat(fmt, 10.0, "10.0");
- checkFormat(fmt, -100.0, "-100.0");
- checkFormat(fmt, 1000.0, "1000.0");
- checkFormat(fmt, -10000.0, "-10000.0");
- checkFormat(fmt, 100000.0, "100000.0");
- checkFormat(fmt, -1000000.0, "-1000000.0");
- checkFormat(fmt, 10000000.0, "10000000.0");
- checkFormat(fmt, -100000000.0, "-100000000.0");
-
- checkFormat(fmt, 1.25e-3, "0.00125");
- checkFormat(fmt, -9.975e-4, "-0.0009975");
- checkFormat(fmt, 12345, "12345.0");
- checkFormat(fmt, -9_999_999, "-9999999.0");
- checkFormat(fmt, 1.00001e7, "10000100.0");
-
- checkFormat(fmt, Float.MAX_VALUE, "340282346638528860000000000000000000000.0");
- checkFormat(fmt, -Float.MIN_VALUE, "-0.000000000000000000000000000000000000000000001401298464324817");
- checkFormat(fmt, Float.MIN_NORMAL, "0.000000000000000000000000000000000000011754943508222875");
- checkFormat(fmt, Math.PI, "3.141592653589793");
- checkFormat(fmt, Math.E, "2.718281828459045");
+ checkFormat(plain, 9876543210.0, "jihgfedcba.a");
+ checkFormat(sci, 9876543210.0, "j.ihgfedcbEj");
+ checkFormat(eng, 9876543210.0, "j.ihgfedcbEj");
+ checkFormat(mixed, 9876543210.0, "j.ihgfedcbEj");
}
@Test
- void testPlain_custom() {
- // arrange
- final DoubleFunction<String> fmt = DoubleFormat.PLAIN.builder()
- .maxPrecision(3)
- .minDecimalExponent(-3)
- .allowSignedZero(false)
- .includeFractionPlaceholder(false)
- .decimalSeparator(',')
- .exponentSeparator("e")
- .infinity("inf")
- .nan("nan")
- .minusSign('!')
- .build();
+ void testEngineering_custom() {
+ // act
+ final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
+ .maxPrecision(3)
+ .minDecimalExponent(-3)
+ .allowSignedZero(false)
+ .includeFractionPlaceholder(false)
+ .decimalSeparator(',')
+ .exponentSeparator("e")
+ .infinity("inf")
+ .nan("nan")
+ .minusSign('!')
+ .build();
// act/assert
checkFormat(fmt, Double.NaN, "nan");
@@ -112,95 +218,103 @@ class DoubleFormatTest {
checkFormat(fmt, 0.00001, "0");
checkFormat(fmt, -0.0001, "0");
- checkFormat(fmt, 0.001, "0,001");
- checkFormat(fmt, -0.01, "!0,01");
- checkFormat(fmt, 0.1, "0,1");
+ checkFormat(fmt, 0.001, "1e!3");
+ checkFormat(fmt, -0.01, "!10e!3");
+ checkFormat(fmt, 0.1, "100e!3");
checkFormat(fmt, -0.0, "0");
checkFormat(fmt, 0.0, "0");
checkFormat(fmt, -1.0, "!1");
checkFormat(fmt, 10.0, "10");
checkFormat(fmt, -100.0, "!100");
- checkFormat(fmt, 1000.0, "1000");
- checkFormat(fmt, -10000.0, "!10000");
- checkFormat(fmt, 100000.0, "100000");
- checkFormat(fmt, -1000000.0, "!1000000");
- checkFormat(fmt, 10000000.0, "10000000");
- checkFormat(fmt, -100000000.0, "!100000000");
+ checkFormat(fmt, 1000.0, "1e3");
+ checkFormat(fmt, -10000.0, "!10e3");
+ checkFormat(fmt, 100000.0, "100e3");
+ checkFormat(fmt, -1000000.0, "!1e6");
+ checkFormat(fmt, 10000000.0, "10e6");
+ checkFormat(fmt, -100000000.0, "!100e6");
- checkFormat(fmt, 1.25e-3, "0,001");
- checkFormat(fmt, -9.975e-4, "!0,001");
- checkFormat(fmt, 12345, "12300");
- checkFormat(fmt, -9_999_999, "!10000000");
- checkFormat(fmt, 1.00001e7, "10000000");
+ checkFormat(fmt, 1.25e-3, "1e!3");
+ checkFormat(fmt, -9.975e-4, "!1e!3");
+ checkFormat(fmt, 12345, "12,3e3");
+ checkFormat(fmt, -9_999_999, "!10e6");
+ checkFormat(fmt, 1.00001e7, "10e6");
- checkFormat(fmt, Float.MAX_VALUE, "340000000000000000000000000000000000000");
- checkFormat(fmt, -Float.MIN_VALUE, "0");
- checkFormat(fmt, Float.MIN_NORMAL, "0");
+ checkFormat(fmt, Double.MAX_VALUE, "180e306");
+ checkFormat(fmt, Double.MIN_VALUE, "0");
+ checkFormat(fmt, Double.MIN_NORMAL, "0");
checkFormat(fmt, Math.PI, "3,14");
checkFormat(fmt, Math.E, "2,72");
}
@Test
- void testPlain_localeFormatComparison() {
- // act/assert
- checkLocalizedFormats("0.0##", loc -> DoubleFormat.PLAIN.builder()
- .minDecimalExponent(-3)
- .formatSymbols(DecimalFormatSymbols.getInstance(loc))
- .build());
- checkLocalizedFormats("#,##0.0##", loc -> DoubleFormat.PLAIN.builder()
- .minDecimalExponent(-3)
- .groupThousands(true)
- .formatSymbols(DecimalFormatSymbols.getInstance(loc))
- .build());
- }
-
- @Test
- void testScientific_defaults() {
- // arrange
- final DoubleFunction<String> fmt = DoubleFormat.SCIENTIFIC.builder().build();
+ void testEngineering_defaults() {
+ // act
+ final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
+ .build();
// act/assert
checkDefaultFormatSpecial(fmt);
- checkFormat(fmt, 0.00001, "1.0E-5");
- checkFormat(fmt, -0.0001, "-1.0E-4");
+ checkFormat(fmt, 0.00001, "10.0E-6");
+ checkFormat(fmt, -0.0001, "-100.0E-6");
checkFormat(fmt, 0.001, "1.0E-3");
- checkFormat(fmt, -0.01, "-1.0E-2");
- checkFormat(fmt, 0.1, "1.0E-1");
+ checkFormat(fmt, -0.01, "-10.0E-3");
+ checkFormat(fmt, 0.1, "100.0E-3");
checkFormat(fmt, -0.0, "-0.0");
checkFormat(fmt, 0.0, "0.0");
checkFormat(fmt, -1.0, "-1.0");
- checkFormat(fmt, 10.0, "1.0E1");
- checkFormat(fmt, -100.0, "-1.0E2");
+ checkFormat(fmt, 10.0, "10.0");
+ checkFormat(fmt, -100.0, "-100.0");
checkFormat(fmt, 1000.0, "1.0E3");
- checkFormat(fmt, -10000.0, "-1.0E4");
- checkFormat(fmt, 100000.0, "1.0E5");
+ checkFormat(fmt, -10000.0, "-10.0E3");
+ checkFormat(fmt, 100000.0, "100.0E3");
checkFormat(fmt, -1000000.0, "-1.0E6");
- checkFormat(fmt, 10000000.0, "1.0E7");
- checkFormat(fmt, -100000000.0, "-1.0E8");
+ checkFormat(fmt, 10000000.0, "10.0E6");
+ checkFormat(fmt, -100000000.0, "-100.0E6");
checkFormat(fmt, 1.25e-3, "1.25E-3");
- checkFormat(fmt, -9.975e-4, "-9.975E-4");
- checkFormat(fmt, 12345, "1.2345E4");
+ checkFormat(fmt, -9.975e-4, "-997.5E-6");
+ checkFormat(fmt, 12345, "12.345E3");
checkFormat(fmt, -9_999_999, "-9.999999E6");
- checkFormat(fmt, 1.00001e7, "1.00001E7");
+ checkFormat(fmt, 1.00001e7, "10.0001E6");
- checkFormat(fmt, Double.MAX_VALUE, "1.7976931348623157E308");
+ checkFormat(fmt, Double.MAX_VALUE, "179.76931348623157E306");
checkFormat(fmt, Double.MIN_VALUE, "4.9E-324");
- checkFormat(fmt, Double.MIN_NORMAL, "2.2250738585072014E-308");
+ checkFormat(fmt, Double.MIN_NORMAL, "22.250738585072014E-309");
checkFormat(fmt, Math.PI, "3.141592653589793");
checkFormat(fmt, Math.E, "2.718281828459045");
}
@Test
- void testScientific_custom() {
+ void testEngineering_localeFormatComparison() {
+ // act/assert
+ checkLocalizedFormats("##0.0##E0", loc -> DoubleFormat.ENGINEERING.builder()
+ .maxPrecision(6)
+ .alwaysIncludeExponent(true)
+ .formatSymbols(DecimalFormatSymbols.getInstance(loc))
+ .build());
+ }
+
+ @Test
+ void testFormatAccuracy() {
+ // act/assert
+ checkFormatAccuracyWithDefaults(DoubleFormat.PLAIN);
+ checkFormatAccuracyWithDefaults(DoubleFormat.MIXED);
+ checkFormatAccuracyWithDefaults(DoubleFormat.SCIENTIFIC);
+ checkFormatAccuracyWithDefaults(DoubleFormat.ENGINEERING);
+ }
+
+ @Test
+ void testMixed_custom() {
// arrange
- final DoubleFunction<String> fmt = DoubleFormat.SCIENTIFIC.builder()
+ final DoubleFunction<String> fmt = DoubleFormat.MIXED.builder()
.maxPrecision(3)
.minDecimalExponent(-3)
.allowSignedZero(false)
.includeFractionPlaceholder(false)
.decimalSeparator(',')
+ .plainFormatMaxDecimalExponent(4)
+ .plainFormatMinDecimalExponent(-1)
.exponentSeparator("e")
.infinity("inf")
.nan("nan")
@@ -216,14 +330,14 @@ class DoubleFormatTest {
checkFormat(fmt, -0.0001, "0");
checkFormat(fmt, 0.001, "1e!3");
checkFormat(fmt, -0.01, "!1e!2");
- checkFormat(fmt, 0.1, "1e!1");
+ checkFormat(fmt, 0.1, "0,1");
checkFormat(fmt, -0.0, "0");
checkFormat(fmt, 0.0, "0");
checkFormat(fmt, -1.0, "!1");
- checkFormat(fmt, 10.0, "1e1");
- checkFormat(fmt, -100.0, "!1e2");
- checkFormat(fmt, 1000.0, "1e3");
- checkFormat(fmt, -10000.0, "!1e4");
+ checkFormat(fmt, 10.0, "10");
+ checkFormat(fmt, -100.0, "!100");
+ checkFormat(fmt, 1000.0, "1000");
+ checkFormat(fmt, -10000.0, "!10000");
checkFormat(fmt, 100000.0, "1e5");
checkFormat(fmt, -1000000.0, "!1e6");
checkFormat(fmt, 10000000.0, "1e7");
@@ -231,7 +345,7 @@ class DoubleFormatTest {
checkFormat(fmt, 1.25e-3, "1e!3");
checkFormat(fmt, -9.975e-4, "!1e!3");
- checkFormat(fmt, 12345, "1,23e4");
+ checkFormat(fmt, 12345, "12300");
checkFormat(fmt, -9_999_999, "!1e7");
checkFormat(fmt, 1.00001e7, "1e7");
@@ -243,68 +357,57 @@ class DoubleFormatTest {
}
@Test
- void testScientific_localeFormatComparison() {
- // act/assert
- checkLocalizedFormats("0.0##E0", loc -> DoubleFormat.SCIENTIFIC.builder()
- .maxPrecision(4)
- .alwaysIncludeExponent(true)
- .formatSymbols(DecimalFormatSymbols.getInstance(loc))
- .build());
- }
-
- @Test
- void testEngineering_defaults() {
- // act
- final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
- .build();
+ void testMixed_defaults() {
+ // arrange
+ final DoubleFunction<String> fmt = DoubleFormat.MIXED.builder().build();
// act/assert
checkDefaultFormatSpecial(fmt);
- checkFormat(fmt, 0.00001, "10.0E-6");
- checkFormat(fmt, -0.0001, "-100.0E-6");
- checkFormat(fmt, 0.001, "1.0E-3");
- checkFormat(fmt, -0.01, "-10.0E-3");
- checkFormat(fmt, 0.1, "100.0E-3");
+ checkFormat(fmt, 0.00001, "1.0E-5");
+ checkFormat(fmt, -0.0001, "-1.0E-4");
+ checkFormat(fmt, 0.001, "0.001");
+ checkFormat(fmt, -0.01, "-0.01");
+ checkFormat(fmt, 0.1, "0.1");
checkFormat(fmt, -0.0, "-0.0");
checkFormat(fmt, 0.0, "0.0");
checkFormat(fmt, -1.0, "-1.0");
checkFormat(fmt, 10.0, "10.0");
checkFormat(fmt, -100.0, "-100.0");
- checkFormat(fmt, 1000.0, "1.0E3");
- checkFormat(fmt, -10000.0, "-10.0E3");
- checkFormat(fmt, 100000.0, "100.0E3");
- checkFormat(fmt, -1000000.0, "-1.0E6");
- checkFormat(fmt, 10000000.0, "10.0E6");
- checkFormat(fmt, -100000000.0, "-100.0E6");
+ checkFormat(fmt, 1000.0, "1000.0");
+ checkFormat(fmt, -10000.0, "-10000.0");
+ checkFormat(fmt, 100000.0, "100000.0");
+ checkFormat(fmt, -1000000.0, "-1000000.0");
+ checkFormat(fmt, 10000000.0, "1.0E7");
+ checkFormat(fmt, -100000000.0, "-1.0E8");
- checkFormat(fmt, 1.25e-3, "1.25E-3");
- checkFormat(fmt, -9.975e-4, "-997.5E-6");
- checkFormat(fmt, 12345, "12.345E3");
- checkFormat(fmt, -9_999_999, "-9.999999E6");
- checkFormat(fmt, 1.00001e7, "10.0001E6");
+ checkFormat(fmt, 1.25e-3, "0.00125");
+ checkFormat(fmt, -9.975e-4, "-9.975E-4");
+ checkFormat(fmt, 12345, "12345.0");
+ checkFormat(fmt, -9_999_999, "-9999999.0");
+ checkFormat(fmt, 1.00001e7, "1.00001E7");
- checkFormat(fmt, Double.MAX_VALUE, "179.76931348623157E306");
+ checkFormat(fmt, Double.MAX_VALUE, "1.7976931348623157E308");
checkFormat(fmt, Double.MIN_VALUE, "4.9E-324");
- checkFormat(fmt, Double.MIN_NORMAL, "22.250738585072014E-309");
+ checkFormat(fmt, Double.MIN_NORMAL, "2.2250738585072014E-308");
checkFormat(fmt, Math.PI, "3.141592653589793");
checkFormat(fmt, Math.E, "2.718281828459045");
}
@Test
- void testEngineering_custom() {
- // act
- final DoubleFunction<String> fmt = DoubleFormat.ENGINEERING.builder()
- .maxPrecision(3)
- .minDecimalExponent(-3)
- .allowSignedZero(false)
- .includeFractionPlaceholder(false)
- .decimalSeparator(',')
- .exponentSeparator("e")
- .infinity("inf")
- .nan("nan")
- .minusSign('!')
- .build();
+ void testPlain_custom() {
+ // arrange
+ final DoubleFunction<String> fmt = DoubleFormat.PLAIN.builder()
+ .maxPrecision(3)
+ .minDecimalExponent(-3)
+ .allowSignedZero(false)
+ .includeFractionPlaceholder(false)
+ .decimalSeparator(',')
+ .exponentSeparator("e")
+ .infinity("inf")
+ .nan("nan")
+ .minusSign('!')
+ .build();
// act/assert
checkFormat(fmt, Double.NaN, "nan");
@@ -313,54 +416,43 @@ class DoubleFormatTest {
checkFormat(fmt, 0.00001, "0");
checkFormat(fmt, -0.0001, "0");
- checkFormat(fmt, 0.001, "1e!3");
- checkFormat(fmt, -0.01, "!10e!3");
- checkFormat(fmt, 0.1, "100e!3");
+ checkFormat(fmt, 0.001, "0,001");
+ checkFormat(fmt, -0.01, "!0,01");
+ checkFormat(fmt, 0.1, "0,1");
checkFormat(fmt, -0.0, "0");
checkFormat(fmt, 0.0, "0");
checkFormat(fmt, -1.0, "!1");
checkFormat(fmt, 10.0, "10");
checkFormat(fmt, -100.0, "!100");
- checkFormat(fmt, 1000.0, "1e3");
- checkFormat(fmt, -10000.0, "!10e3");
- checkFormat(fmt, 100000.0, "100e3");
- checkFormat(fmt, -1000000.0, "!1e6");
- checkFormat(fmt, 10000000.0, "10e6");
- checkFormat(fmt, -100000000.0, "!100e6");
-
- checkFormat(fmt, 1.25e-3, "1e!3");
- checkFormat(fmt, -9.975e-4, "!1e!3");
- checkFormat(fmt, 12345, "12,3e3");
- checkFormat(fmt, -9_999_999, "!10e6");
- checkFormat(fmt, 1.00001e7, "10e6");
+ checkFormat(fmt, 1000.0, "1000");
+ checkFormat(fmt, -10000.0, "!10000");
+ checkFormat(fmt, 100000.0, "100000");
+ checkFormat(fmt, -1000000.0, "!1000000");
+ checkFormat(fmt, 10000000.0, "10000000");
+ checkFormat(fmt, -100000000.0, "!100000000");
- checkFormat(fmt, Double.MAX_VALUE, "180e306");
- checkFormat(fmt, Double.MIN_VALUE, "0");
- checkFormat(fmt, Double.MIN_NORMAL, "0");
+ checkFormat(fmt, 1.25e-3, "0,001");
+ checkFormat(fmt, -9.975e-4, "!0,001");
+ checkFormat(fmt, 12345, "12300");
+ checkFormat(fmt, -9_999_999, "!10000000");
+ checkFormat(fmt, 1.00001e7, "10000000");
+
+ checkFormat(fmt, Float.MAX_VALUE, "340000000000000000000000000000000000000");
+ checkFormat(fmt, -Float.MIN_VALUE, "0");
+ checkFormat(fmt, Float.MIN_NORMAL, "0");
checkFormat(fmt, Math.PI, "3,14");
checkFormat(fmt, Math.E, "2,72");
}
@Test
- void testEngineering_localeFormatComparison() {
- // act/assert
- checkLocalizedFormats("##0.0##E0", loc -> DoubleFormat.ENGINEERING.builder()
- .maxPrecision(6)
- .alwaysIncludeExponent(true)
- .formatSymbols(DecimalFormatSymbols.getInstance(loc))
- .build());
- }
-
- @Test
- void testMixed_defaults() {
+ void testPlain_defaults() {
// arrange
- final DoubleFunction<String> fmt = DoubleFormat.MIXED.builder().build();
+ final DoubleFunction<String> fmt = DoubleFormat.PLAIN.builder()
+ .build();
// act/assert
- checkDefaultFormatSpecial(fmt);
-
- checkFormat(fmt, 0.00001, "1.0E-5");
- checkFormat(fmt, -0.0001, "-1.0E-4");
+ checkFormat(fmt, 0.00001, "0.00001");
+ checkFormat(fmt, -0.0001, "-0.0001");
checkFormat(fmt, 0.001, "0.001");
checkFormat(fmt, -0.01, "-0.01");
checkFormat(fmt, 0.1, "0.1");
@@ -373,33 +465,45 @@ class DoubleFormatTest {
checkFormat(fmt, -10000.0, "-10000.0");
checkFormat(fmt, 100000.0, "100000.0");
checkFormat(fmt, -1000000.0, "-1000000.0");
- checkFormat(fmt, 10000000.0, "1.0E7");
- checkFormat(fmt, -100000000.0, "-1.0E8");
+ checkFormat(fmt, 10000000.0, "10000000.0");
+ checkFormat(fmt, -100000000.0, "-100000000.0");
checkFormat(fmt, 1.25e-3, "0.00125");
- checkFormat(fmt, -9.975e-4, "-9.975E-4");
+ checkFormat(fmt, -9.975e-4, "-0.0009975");
checkFormat(fmt, 12345, "12345.0");
checkFormat(fmt, -9_999_999, "-9999999.0");
- checkFormat(fmt, 1.00001e7, "1.00001E7");
+ checkFormat(fmt, 1.00001e7, "10000100.0");
- checkFormat(fmt, Double.MAX_VALUE, "1.7976931348623157E308");
- checkFormat(fmt, Double.MIN_VALUE, "4.9E-324");
- checkFormat(fmt, Double.MIN_NORMAL, "2.2250738585072014E-308");
+ checkFormat(fmt, Float.MAX_VALUE, "340282346638528860000000000000000000000.0");
+ checkFormat(fmt, -Float.MIN_VALUE, "-0.000000000000000000000000000000000000000000001401298464324817");
+ checkFormat(fmt, Float.MIN_NORMAL, "0.000000000000000000000000000000000000011754943508222875");
checkFormat(fmt, Math.PI, "3.141592653589793");
checkFormat(fmt, Math.E, "2.718281828459045");
}
@Test
- void testMixed_custom() {
+ void testPlain_localeFormatComparison() {
+ // act/assert
+ checkLocalizedFormats("0.0##", loc -> DoubleFormat.PLAIN.builder()
+ .minDecimalExponent(-3)
+ .formatSymbols(DecimalFormatSymbols.getInstance(loc))
+ .build());
+ checkLocalizedFormats("#,##0.0##", loc -> DoubleFormat.PLAIN.builder()
+ .minDecimalExponent(-3)
+ .groupThousands(true)
+ .formatSymbols(DecimalFormatSymbols.getInstance(loc))
+ .build());
+ }
+
+ @Test
+ void testScientific_custom() {
// arrange
- final DoubleFunction<String> fmt = DoubleFormat.MIXED.builder()
+ final DoubleFunction<String> fmt = DoubleFormat.SCIENTIFIC.builder()
.maxPrecision(3)
.minDecimalExponent(-3)
.allowSignedZero(false)
.includeFractionPlaceholder(false)
.decimalSeparator(',')
- .plainFormatMaxDecimalExponent(4)
- .plainFormatMinDecimalExponent(-1)
.exponentSeparator("e")
.infinity("inf")
.nan("nan")
@@ -415,14 +519,14 @@ class DoubleFormatTest {
checkFormat(fmt, -0.0001, "0");
checkFormat(fmt, 0.001, "1e!3");
checkFormat(fmt, -0.01, "!1e!2");
- checkFormat(fmt, 0.1, "0,1");
+ checkFormat(fmt, 0.1, "1e!1");
checkFormat(fmt, -0.0, "0");
checkFormat(fmt, 0.0, "0");
checkFormat(fmt, -1.0, "!1");
- checkFormat(fmt, 10.0, "10");
- checkFormat(fmt, -100.0, "!100");
- checkFormat(fmt, 1000.0, "1000");
- checkFormat(fmt, -10000.0, "!10000");
+ checkFormat(fmt, 10.0, "1e1");
+ checkFormat(fmt, -100.0, "!1e2");
+ checkFormat(fmt, 1000.0, "1e3");
+ checkFormat(fmt, -10000.0, "!1e4");
checkFormat(fmt, 100000.0, "1e5");
checkFormat(fmt, -1000000.0, "!1e6");
checkFormat(fmt, 10000000.0, "1e7");
@@ -430,7 +534,7 @@ class DoubleFormatTest {
checkFormat(fmt, 1.25e-3, "1e!3");
checkFormat(fmt, -9.975e-4, "!1e!3");
- checkFormat(fmt, 12345, "12300");
+ checkFormat(fmt, 12345, "1,23e4");
checkFormat(fmt, -9_999_999, "!1e7");
checkFormat(fmt, 1.00001e7, "1e7");
@@ -442,154 +546,50 @@ class DoubleFormatTest {
}
@Test
- void testCustomDigitString() {
+ void testScientific_defaults() {
// arrange
- final String digits = "abcdefghij";
- final DoubleFunction<String> plain = DoubleFormat.PLAIN.builder().digits(digits).build();
- final DoubleFunction<String> sci = DoubleFormat.SCIENTIFIC.builder().digits(digits).build();
- final DoubleFunction<String> eng = DoubleFormat.ENGINEERING.builder().digits(digits).build();
- final DoubleFunction<String> mixed = DoubleFormat.MIXED.builder().digits(digits).build();
+ final DoubleFunction<String> fmt = DoubleFormat.SCIENTIFIC.builder().build();
// act/assert
- checkFormat(plain, 9876543210.0, "jihgfedcba.a");
- checkFormat(sci, 9876543210.0, "j.ihgfedcbEj");
- checkFormat(eng, 9876543210.0, "j.ihgfedcbEj");
- checkFormat(mixed, 9876543210.0, "j.ihgfedcbEj");
- }
-
- /** Check that the given format type correctly formats doubles when using the
- * default configuration options. The format itself is not checked; only the
- * fact that the input double can be successfully recovered using {@link Double#parseDouble(String)}
- * is asserted.
- * @param type format type
- */
- private static void checkFormatAccuracyWithDefaults(final DoubleFormat type) {
- final DoubleFunction<String> fmt = type.builder().build();
-
checkDefaultFormatSpecial(fmt);
- checkFormatAccuracy(fmt, Double.MIN_VALUE);
- checkFormatAccuracy(fmt, -Double.MIN_VALUE);
-
- checkFormatAccuracy(fmt, Double.MIN_NORMAL);
- checkFormatAccuracy(fmt, -Double.MIN_NORMAL);
-
- checkFormatAccuracy(fmt, Double.MAX_VALUE);
- checkFormatAccuracy(fmt, -Double.MAX_VALUE);
-
- checkFormatAccuracy(fmt, Math.PI);
- checkFormatAccuracy(fmt, Math.E);
-
- final Random rnd = new Random(10L);
- final int cnt = 1000;
- for (int i = 0; i < cnt; ++i) {
- checkFormatAccuracy(fmt, randomDouble(rnd));
- }
- }
-
- /** Check that the given double value can be exactly recovered from formatted string representation
- * produced by the format instance.
- * @param fmt format instance
- * @param d input double value
- */
- private static void checkFormatAccuracy(final DoubleFunction<String> fmt, final double d) {
- final String str = fmt.apply(d);
- final double parsed = Double.parseDouble(str);
- Assertions.assertEquals(d, parsed, () -> "Formatted double string [" + str + "] did not match input value");
- }
-
- private static void checkFormat(final DoubleFunction<String> fmt, final double d, final String str) {
- Assertions.assertEquals(str, fmt.apply(d));
- }
-
- private static void checkDefaultFormatSpecial(final DoubleFunction<String> fmt) {
- checkFormat(fmt, 0.0, "0.0");
+ checkFormat(fmt, 0.00001, "1.0E-5");
+ checkFormat(fmt, -0.0001, "-1.0E-4");
+ checkFormat(fmt, 0.001, "1.0E-3");
+ checkFormat(fmt, -0.01, "-1.0E-2");
+ checkFormat(fmt, 0.1, "1.0E-1");
checkFormat(fmt, -0.0, "-0.0");
- checkFormat(fmt, Double.NaN, "NaN");
- checkFormat(fmt, Double.POSITIVE_INFINITY, "Infinity");
- checkFormat(fmt, Double.NEGATIVE_INFINITY, "-Infinity");
- }
-
- private static void checkLocalizedFormats(final String pattern,
- final Function<Locale, DoubleFunction<String>> factory) {
- for (final Locale loc : Locale.getAvailableLocales()) {
- checkLocalizedFormat(loc, pattern, factory);
- }
- }
-
- private static void checkLocalizedFormat(final Locale loc, final String pattern,
- final Function<Locale, DoubleFunction<String>> factory) {
- // arrange
- final DecimalFormat df = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(loc));
- final DoubleFunction<String> fmt = factory.apply(loc);
-
- // act/assert
- assertLocalizedFormatsAreEqual(0.0, df, fmt, loc);
- assertLocalizedFormatsAreEqual(Double.POSITIVE_INFINITY, df, fmt, loc);
- assertLocalizedFormatsAreEqual(Double.NEGATIVE_INFINITY, df, fmt, loc);
- assertLocalizedFormatsAreEqual(Double.NaN, df, fmt, loc);
-
- assertLocalizedFormatsAreEqual(1.0, df, fmt, loc);
- assertLocalizedFormatsAreEqual(-1.0, df, fmt, loc);
- assertLocalizedFormatsAreEqual(Math.PI, df, fmt, loc);
- assertLocalizedFormatsAreEqual(Math.E, df, fmt, loc);
-
- final Random rnd = new Random(12L);
- final int minExp = -100;
- final int maxExp = 100;
- final int cnt = 1000;
- for (int i = 0; i < cnt; ++i) {
- assertLocalizedFormatsAreEqual(randomDouble(minExp, maxExp, rnd), df, fmt, loc);
- }
- }
-
- private static void assertLocalizedFormatsAreEqual(final double d, final DecimalFormat df,
- final DoubleFunction<String> fmt, final Locale loc) {
- // NOTE: Perform the string comparison only on non-format characters. This is required because
- // JDK 16 adds directionality characters to strings for certain locales, such as Arabic, whereas
- // previous JDKs do not. We will match the behavior of the previous versions here and ignore formatting
- // for test purposes.
- final String dfStr = trimFormatChars(df.format(d));
- final String fmtStr = trimFormatChars(fmt.apply(d));
-
- Assertions.assertEquals(dfStr, fmtStr,
- () -> "Unexpected output for locale [" + loc.toLanguageTag() + "] and double value " + d);
- }
+ checkFormat(fmt, 0.0, "0.0");
+ checkFormat(fmt, -1.0, "-1.0");
+ checkFormat(fmt, 10.0, "1.0E1");
+ checkFormat(fmt, -100.0, "-1.0E2");
+ checkFormat(fmt, 1000.0, "1.0E3");
+ checkFormat(fmt, -10000.0, "-1.0E4");
+ checkFormat(fmt, 100000.0, "1.0E5");
+ checkFormat(fmt, -1000000.0, "-1.0E6");
+ checkFormat(fmt, 10000000.0, "1.0E7");
+ checkFormat(fmt, -100000000.0, "-1.0E8");
- /** Remove Unicode {@link Character#FORMAT format} characters from the given string.
- * @param str input string
- * @return input string with format characters removed
- */
- private static String trimFormatChars(final String str) {
- final StringBuilder sb = new StringBuilder();
- for (final char c : str.toCharArray()) {
- if (Character.getType(c) != Character.FORMAT) {
- sb.append(c);
- }
- }
- return sb.toString();
- }
+ checkFormat(fmt, 1.25e-3, "1.25E-3");
+ checkFormat(fmt, -9.975e-4, "-9.975E-4");
+ checkFormat(fmt, 12345, "1.2345E4");
+ checkFormat(fmt, -9_999_999, "-9.999999E6");
+ checkFormat(fmt, 1.00001e7, "1.00001E7");
- /** Create a random double value using the full range of exponent values.
- * @param rnd random number generator
- * @return random double
- */
- private static double randomDouble(final Random rnd) {
- return randomDouble(Double.MIN_EXPONENT, Double.MAX_EXPONENT, rnd);
+ checkFormat(fmt, Double.MAX_VALUE, "1.7976931348623157E308");
+ checkFormat(fmt, Double.MIN_VALUE, "4.9E-324");
+ checkFormat(fmt, Double.MIN_NORMAL, "2.2250738585072014E-308");
+ checkFormat(fmt, Math.PI, "3.141592653589793");
+ checkFormat(fmt, Math.E, "2.718281828459045");
}
- /** Create a random double value with exponent in the range {@code [minExp, maxExp]}.
- * @param minExp minimum exponent; must be less than {@code maxExp}
- * @param maxExp maximum exponent; must be greater than {@code minExp}
- * @param rnd random number generator
- * @return random double
- */
- private static double randomDouble(final int minExp, final int maxExp, final Random rnd) {
- // Create random doubles using random bits in the sign bit and the mantissa.
- final long mask = ((1L << 52) - 1) | 1L << 63;
- final long bits = rnd.nextLong() & mask;
- // The exponent must be unsigned so + 1023 to the signed exponent
- final long exp = rnd.nextInt(maxExp - minExp + 1) + minExp + 1023;
- return Double.longBitsToDouble(bits | (exp << 52));
+ @Test
+ void testScientific_localeFormatComparison() {
+ // act/assert
+ checkLocalizedFormats("0.0##E0", loc -> DoubleFormat.SCIENTIFIC.builder()
+ .maxPrecision(4)
+ .alwaysIncludeExponent(true)
+ .formatSymbols(DecimalFormatSymbols.getInstance(loc))
+ .build());
}
}
diff --git a/src/test/java/org/apache/commons/text/numbers/ParsedDecimalTest.java b/src/test/java/org/apache/commons/text/numbers/ParsedDecimalTest.java
index 89d1f605..21354585 100644
--- a/src/test/java/org/apache/commons/text/numbers/ParsedDecimalTest.java
+++ b/src/test/java/org/apache/commons/text/numbers/ParsedDecimalTest.java
@@ -29,6 +29,220 @@ import org.junit.jupiter.api.function.Executable;
class ParsedDecimalTest {
+ private static final class FormatOptionsImpl implements ParsedDecimal.FormatOptions {
+
+ private boolean includeFractionPlaceholder = true;
+
+ private boolean signedZero = true;
+
+ private char[] digits = "0123456789".toCharArray();
+
+ private char decimalSeparator = '.';
+
+ private char thousandsGroupingSeparator = ',';
+
+ private boolean groupThousands = false;
+
+ private char minusSign = '-';
+
+ private String exponentSeparator = "E";
+
+ private boolean alwaysIncludeExponent = false;
+
+ @Override
+ public char getDecimalSeparator() {
+ return decimalSeparator;
+ }
+
+ @Override
+ public char[] getDigits() {
+ return digits;
+ }
+
+ @Override
+ public char[] getExponentSeparatorChars() {
+ return exponentSeparator.toCharArray();
+ }
+
+ @Override
+ public char getGroupingSeparator() {
+ return thousandsGroupingSeparator;
+ }
+
+ @Override
+ public char getMinusSign() {
+ return minusSign;
+ }
+
+ @Override
+ public boolean isAlwaysIncludeExponent() {
+ return alwaysIncludeExponent;
+ }
+
+ @Override
+ public boolean isGroupThousands() {
+ return groupThousands;
+ }
+
+ @Override
+ public boolean isIncludeFractionPlaceholder() {
+ return includeFractionPlaceholder;
+ }
+
+ @Override
+ public boolean isSignedZero() {
+ return signedZero;
+ }
+
+ public void setAlwaysIncludeExponent(final boolean alwaysIncludeExponent) {
+ this.alwaysIncludeExponent = alwaysIncludeExponent;
+ }
+
+ public void setDecimalSeparator(final char decimalSeparator) {
+ this.decimalSeparator = decimalSeparator;
+ }
+
+ public void setDigitsFromString(final String digits) {
+ this.digits = digits.toCharArray();
+ }
+
+ public void setExponentSeparator(final String exponentSeparator) {
+ this.exponentSeparator = exponentSeparator;
+ }
+
+ public void setGroupThousands(final boolean groupThousands) {
+ this.groupThousands = groupThousands;
+ }
+
+ public void setIncludeFractionPlaceholder(final boolean includeFractionPlaceholder) {
+ this.includeFractionPlaceholder = includeFractionPlaceholder;
+ }
+
+ public void setMinusSign(final char minusSign) {
+ this.minusSign = minusSign;
+ }
+
+ public void setSignedZero(final boolean signedZero) {
+ this.signedZero = signedZero;
+ }
+
+ public void setThousandsGroupingSeparator(final char thousandsGroupingSeparator) {
+ this.thousandsGroupingSeparator = thousandsGroupingSeparator;
+ }
+ }
+
+ private static void assertMaxPrecision(final double d, final int maxPrecision,
+ final boolean negative, final String digits, final int exponent) {
+ final ParsedDecimal dec = ParsedDecimal.from(d);
+ dec.maxPrecision(maxPrecision);
+
+ assertSimpleDecimal(dec, negative, digits, exponent);
+ }
+
+ private static void assertRound(final double d, final int roundExponent,
+ final boolean negative, final String digits, final int exponent) {
+ final ParsedDecimal dec = ParsedDecimal.from(d);
+ dec.round(roundExponent);
+
+ assertSimpleDecimal(dec, negative, digits, exponent);
+ }
+
+ private static void assertSimpleDecimal(final ParsedDecimal parsed, final boolean negative, final String digits,
+ final int exponent) {
+ Assertions.assertEquals(negative, parsed.negative);
+ Assertions.assertEquals(digits, digitString(parsed));
+ Assertions.assertEquals(exponent, parsed.getExponent());
+ Assertions.assertEquals(digits.length(), parsed.digitCount);
+ Assertions.assertEquals(exponent, parsed.getScientificExponent() - digits.length() + 1);
+ }
+
+ private static void assertThrowsWithMessage(final Executable fn, final Class<? extends Throwable> type,
+ final String msg) {
+ final Throwable exc = Assertions.assertThrows(type, fn);
+ Assertions.assertEquals(msg, exc.getMessage());
+ }
+
+ private static void checkFrom(final double d, final String digits, final int exponent) {
+ final boolean negative = Math.signum(d) < 0;
+
+ assertSimpleDecimal(ParsedDecimal.from(d), negative, digits, exponent);
+ assertSimpleDecimal(ParsedDecimal.from(-d), !negative, digits, exponent);
+ }
+
+ private static void checkToEngineeringString(final double d, final String expected,
+ final ParsedDecimal.FormatOptions opts) {
+ checkToStringMethod(d, expected, ParsedDecimal::toEngineeringString, opts);
+
+ // check the exponent value to make sure it is a multiple of 3
+ final String pos = ParsedDecimal.from(d).toEngineeringString(opts);
+ Assertions.assertEquals(0, parseExponent(pos, opts) % 3);
+
+ final String neg = ParsedDecimal.from(-d).toEngineeringString(opts);
+ Assertions.assertEquals(0, parseExponent(neg, opts) % 3);
+ }
+
+ private static void checkToPlainString(final double d, final String expected,
+ final ParsedDecimal.FormatOptions opts) {
+ checkToStringMethod(d, expected, ParsedDecimal::toPlainString, opts);
+ }
+
+ private static void checkToScientificString(final double d, final String expected,
+ final ParsedDecimal.FormatOptions opts) {
+ checkToStringMethod(d, expected, ParsedDecimal::toScientificString, opts);
+ }
+
+ private static void checkToStringMethod(final double d, final String expected,
+ final BiFunction<ParsedDecimal, ParsedDecimal.FormatOptions, String> fn,
+ final ParsedDecimal.FormatOptions opts) {
+
+ final ParsedDecimal pos = ParsedDecimal.from(d);
+ final String actual = fn.apply(pos, opts);
+
+ Assertions.assertEquals(expected, actual);
+ }
+
+ private static double createRandomDouble(final UniformRandomProvider rng) {
+ final long mask = ((1L << 52) - 1) | 1L << 63;
+ final long bits = rng.nextLong() & mask;
+ final long exp = rng.nextInt(2045) + 1;
+ return Double.longBitsToDouble(bits | (exp << 52));
+ }
+
+ /** Get the raw digits in the given decimal as a string.
+ * @param dec decimal instancE
+ * @return decimal digits as a string
+ */
+ private static String digitString(final ParsedDecimal dec) {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < dec.digitCount; ++i) {
+ sb.append(dec.digits[i]);
+ }
+ return sb.toString();
+ }
+
+ private static int parseExponent(final String str, final ParsedDecimal.FormatOptions opts) {
+ final char[] expSep = opts.getExponentSeparatorChars();
+
+ final int expStartIdx = str.indexOf(String.valueOf(expSep));
+ if (expStartIdx > -1) {
+ int expIdx = expStartIdx + expSep.length;
+
+ boolean neg = false;
+ if (str.charAt(expIdx) == opts.getMinusSign()) {
+ ++expIdx;
+ neg = true;
+ }
+
+ final String expStr = str.substring(expIdx);
+ final int val = Integer.parseInt(expStr);
+ return neg
+ ? -val
+ : val;
+ }
+
+ return 0;
+ }
+
@Test
void testFrom() {
// act/assert
@@ -102,103 +316,29 @@ class ParsedDecimalTest {
}
@Test
- void testRound_one() {
+ void testMaxPrecision() {
// arrange
- final double a = 1e-10;
- final double b = -1;
- final double c = 1e10;
-
- // act/assert
- assertRound(a, -11, false, "1", -10);
- assertRound(a, -10, false, "1", -10);
- assertRound(a, -9, false, "0", 0);
+ final double d = 1.02576552;
- assertRound(b, -1, true, "1", 0);
- assertRound(b, 0, true, "1", 0);
- assertRound(b, 1, true, "0", 0);
+ // act
+ assertMaxPrecision(d, 10, false, "102576552", -8);
+ assertMaxPrecision(d, 9, false, "102576552", -8);
+ assertMaxPrecision(d, 8, false, "10257655", -7);
+ assertMaxPrecision(d, 7, false, "1025766", -6);
+ assertMaxPrecision(d, 6, false, "102577", -5);
+ assertMaxPrecision(d, 5, false, "10258", -4);
+ assertMaxPrecision(d, 4, false, "1026", -3);
+ assertMaxPrecision(d, 3, false, "103", -2);
+ assertMaxPrecision(d, 2, false, "1", 0);
+ assertMaxPrecision(d, 1, false, "1", 0);
- assertRound(c, 9, false, "1", 10);
- assertRound(c, 10, false, "1", 10);
- assertRound(c, 11, false, "0", 0);
+ assertMaxPrecision(d, 0, false, "102576552", -8);
}
@Test
- void testRound_nine() {
+ void testMaxPrecision_carry() {
// arrange
- final double a = 9e-10;
- final double b = -9;
- final double c = 9e10;
-
- // act/assert
- assertRound(a, -11, false, "9", -10);
- assertRound(a, -10, false, "9", -10);
- assertRound(a, -9, false, "1", -9);
-
- assertRound(b, -1, true, "9", 0);
- assertRound(b, 0, true, "9", 0);
- assertRound(b, 1, true, "1", 1);
-
- assertRound(c, 9, false, "9", 10);
- assertRound(c, 10, false, "9", 10);
- assertRound(c, 11, false, "1", 11);
- }
-
- @Test
- void testRound_mixed() {
- // arrange
- final double a = 9.94e-10;
- final double b = -3.1415;
- final double c = 5.55e10;
-
- // act/assert
- assertRound(a, -13, false, "994", -12);
- assertRound(a, -12, false, "994", -12);
- assertRound(a, -11, false, "99", -11);
- assertRound(a, -10, false, "1", -9);
- assertRound(a, -9, false, "1", -9);
- assertRound(a, -8, false, "0", 0);
-
- assertRound(b, -5, true, "31415", -4);
- assertRound(b, -4, true, "31415", -4);
- assertRound(b, -3, true, "3142", -3);
- assertRound(b, -2, true, "314", -2);
- assertRound(b, -1, true, "31", -1);
- assertRound(b, 0, true, "3", 0);
- assertRound(b, 1, true, "0", 0);
- assertRound(b, 2, true, "0", 0);
-
- assertRound(c, 7, false, "555", 8);
- assertRound(c, 8, false, "555", 8);
- assertRound(c, 9, false, "56", 9);
- assertRound(c, 10, false, "6", 10);
- assertRound(c, 11, false, "1", 11);
- assertRound(c, 12, false, "0", 0);
- }
-
- @Test
- void testMaxPrecision() {
- // arrange
- final double d = 1.02576552;
-
- // act
- assertMaxPrecision(d, 10, false, "102576552", -8);
- assertMaxPrecision(d, 9, false, "102576552", -8);
- assertMaxPrecision(d, 8, false, "10257655", -7);
- assertMaxPrecision(d, 7, false, "1025766", -6);
- assertMaxPrecision(d, 6, false, "102577", -5);
- assertMaxPrecision(d, 5, false, "10258", -4);
- assertMaxPrecision(d, 4, false, "1026", -3);
- assertMaxPrecision(d, 3, false, "103", -2);
- assertMaxPrecision(d, 2, false, "1", 0);
- assertMaxPrecision(d, 1, false, "1", 0);
-
- assertMaxPrecision(d, 0, false, "102576552", -8);
- }
-
- @Test
- void testMaxPrecision_carry() {
- // arrange
- final double d = -999.0999e50;
+ final double d = -999.0999e50;
// act
assertMaxPrecision(d, 8, true, "9990999", 46);
@@ -230,17 +370,6 @@ class ParsedDecimalTest {
assertMaxPrecision(-5.5, 1, true, "6", 0);
}
- @Test
- void testMaxPrecision_singleDigits() {
- // act
- assertMaxPrecision(9.0, 1, false, "9", 0);
- assertMaxPrecision(1.0, 1, false, "1", 0);
- assertMaxPrecision(0.0, 1, false, "0", 0);
- assertMaxPrecision(-0.0, 1, true, "0", 0);
- assertMaxPrecision(-1.0, 1, true, "1", 0);
- assertMaxPrecision(-9.0, 1, true, "9", 0);
- }
-
@Test
void testMaxPrecision_random() {
// arrange
@@ -264,177 +393,141 @@ class ParsedDecimalTest {
}
@Test
- void testToPlainString_defaults() {
+ void testMaxPrecision_singleDigits() {
+ // act
+ assertMaxPrecision(9.0, 1, false, "9", 0);
+ assertMaxPrecision(1.0, 1, false, "1", 0);
+ assertMaxPrecision(0.0, 1, false, "0", 0);
+ assertMaxPrecision(-0.0, 1, true, "0", 0);
+ assertMaxPrecision(-1.0, 1, true, "1", 0);
+ assertMaxPrecision(-9.0, 1, true, "9", 0);
+ }
+
+ @Test
+ void testRound_mixed() {
// arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
+ final double a = 9.94e-10;
+ final double b = -3.1415;
+ final double c = 5.55e10;
// act/assert
- checkToPlainString(0.0, "0.0", opts);
- checkToPlainString(-0.0, "-0.0", opts);
- checkToPlainString(1.0, "1.0", opts);
- checkToPlainString(1.5, "1.5", opts);
-
- checkToPlainString(12, "12.0", opts);
- checkToPlainString(123, "123.0", opts);
- checkToPlainString(1234, "1234.0", opts);
- checkToPlainString(12345, "12345.0", opts);
- checkToPlainString(123456, "123456.0", opts);
- checkToPlainString(1234567, "1234567.0", opts);
- checkToPlainString(12345678, "12345678.0", opts);
- checkToPlainString(123456789, "123456789.0", opts);
- checkToPlainString(1234567890, "1234567890.0", opts);
-
- checkToPlainString(-0.000123, "-0.000123", opts);
- checkToPlainString(12301, "12301.0", opts);
+ assertRound(a, -13, false, "994", -12);
+ assertRound(a, -12, false, "994", -12);
+ assertRound(a, -11, false, "99", -11);
+ assertRound(a, -10, false, "1", -9);
+ assertRound(a, -9, false, "1", -9);
+ assertRound(a, -8, false, "0", 0);
- checkToPlainString(Math.PI, "3.141592653589793", opts);
- checkToPlainString(Math.E, "2.718281828459045", opts);
+ assertRound(b, -5, true, "31415", -4);
+ assertRound(b, -4, true, "31415", -4);
+ assertRound(b, -3, true, "3142", -3);
+ assertRound(b, -2, true, "314", -2);
+ assertRound(b, -1, true, "31", -1);
+ assertRound(b, 0, true, "3", 0);
+ assertRound(b, 1, true, "0", 0);
+ assertRound(b, 2, true, "0", 0);
- checkToPlainString(-12345.6789, "-12345.6789", opts);
- checkToPlainString(1.23e12, "1230000000000.0", opts);
- checkToPlainString(1.23e-12, "0.00000000000123", opts);
+ assertRound(c, 7, false, "555", 8);
+ assertRound(c, 8, false, "555", 8);
+ assertRound(c, 9, false, "56", 9);
+ assertRound(c, 10, false, "6", 10);
+ assertRound(c, 11, false, "1", 11);
+ assertRound(c, 12, false, "0", 0);
}
@Test
- void testToPlainString_altFormat() {
+ void testRound_nine() {
// arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
- opts.setIncludeFractionPlaceholder(false);
- opts.setSignedZero(false);
- opts.setDecimalSeparator(',');
- opts.setMinusSign('!');
- opts.setThousandsGroupingSeparator('_');
- opts.setGroupThousands(true);
+ final double a = 9e-10;
+ final double b = -9;
+ final double c = 9e10;
// act/assert
- checkToPlainString(0.0, "0", opts);
- checkToPlainString(-0.0, "0", opts);
- checkToPlainString(1.0, "1", opts);
- checkToPlainString(1.5, "1,5", opts);
-
- checkToPlainString(12, "12", opts);
- checkToPlainString(123, "123", opts);
- checkToPlainString(1234, "1_234", opts);
- checkToPlainString(12345, "12_345", opts);
- checkToPlainString(123456, "123_456", opts);
- checkToPlainString(1234567, "1_234_567", opts);
- checkToPlainString(12345678, "12_345_678", opts);
- checkToPlainString(123456789, "123_456_789", opts);
- checkToPlainString(1234567890, "1_234_567_890", opts);
-
- checkToPlainString(-0.000123, "!0,000123", opts);
- checkToPlainString(12301, "12_301", opts);
+ assertRound(a, -11, false, "9", -10);
+ assertRound(a, -10, false, "9", -10);
+ assertRound(a, -9, false, "1", -9);
- checkToPlainString(Math.PI, "3,141592653589793", opts);
- checkToPlainString(Math.E, "2,718281828459045", opts);
+ assertRound(b, -1, true, "9", 0);
+ assertRound(b, 0, true, "9", 0);
+ assertRound(b, 1, true, "1", 1);
- checkToPlainString(-12345.6789, "!12_345,6789", opts);
- checkToPlainString(1.23e12, "1_230_000_000_000", opts);
- checkToPlainString(1.23e-12, "0,00000000000123", opts);
+ assertRound(c, 9, false, "9", 10);
+ assertRound(c, 10, false, "9", 10);
+ assertRound(c, 11, false, "1", 11);
}
@Test
- void testToScientificString_defaults() {
+ void testRound_one() {
// arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
+ final double a = 1e-10;
+ final double b = -1;
+ final double c = 1e10;
// act/assert
- checkToScientificString(0.0, "0.0", opts);
- checkToScientificString(-0.0, "-0.0", opts);
- checkToScientificString(1.0, "1.0", opts);
- checkToScientificString(1.5, "1.5", opts);
-
- checkToScientificString(-0.000123, "-1.23E-4", opts);
- checkToScientificString(12301, "1.2301E4", opts);
+ assertRound(a, -11, false, "1", -10);
+ assertRound(a, -10, false, "1", -10);
+ assertRound(a, -9, false, "0", 0);
- checkToScientificString(Math.PI, "3.141592653589793", opts);
- checkToScientificString(Math.E, "2.718281828459045", opts);
+ assertRound(b, -1, true, "1", 0);
+ assertRound(b, 0, true, "1", 0);
+ assertRound(b, 1, true, "0", 0);
- checkToScientificString(-Double.MAX_VALUE, "-1.7976931348623157E308", opts);
- checkToScientificString(Double.MIN_VALUE, "4.9E-324", opts);
- checkToScientificString(Double.MIN_NORMAL, "2.2250738585072014E-308", opts);
+ assertRound(c, 9, false, "1", 10);
+ assertRound(c, 10, false, "1", 10);
+ assertRound(c, 11, false, "0", 0);
}
@Test
- void testToScientificString_altFormats() {
+ void testStringMethodAccuracy_random() {
// arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
- opts.setIncludeFractionPlaceholder(false);
- opts.setSignedZero(false);
- opts.setDecimalSeparator(',');
- opts.setMinusSign('!');
- opts.setExponentSeparator("x10^");
- opts.setAlwaysIncludeExponent(true);
+ final UniformRandomProvider rand = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP, 0L);
- // act/assert
- checkToScientificString(0.0, "0x10^0", opts);
- checkToScientificString(-0.0, "0x10^0", opts);
- checkToScientificString(1.0, "1x10^0", opts);
- checkToScientificString(1.5, "1,5x10^0", opts);
+ final FormatOptionsImpl stdOpts = new FormatOptionsImpl();
+ final FormatOptionsImpl altOpts = new FormatOptionsImpl();
+ altOpts.setExponentSeparator("e");
+ altOpts.setIncludeFractionPlaceholder(false);
- checkToScientificString(-0.000123, "!1,23x10^!4", opts);
- checkToScientificString(12301, "1,2301x10^4", opts);
+ double d;
+ for (int i = 0; i < 10_000; ++i) {
+ d = createRandomDouble(rand);
- checkToScientificString(Math.PI, "3,141592653589793x10^0", opts);
- checkToScientificString(Math.E, "2,718281828459045x10^0", opts);
+ // act/assert
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(altOpts)));
- checkToScientificString(-Double.MAX_VALUE, "!1,7976931348623157x10^308", opts);
- checkToScientificString(Double.MIN_VALUE, "4,9x10^!324", opts);
- checkToScientificString(Double.MIN_NORMAL, "2,2250738585072014x10^!308", opts);
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(altOpts)));
+
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(altOpts)));
+ }
}
@Test
- void testToEngineeringString_defaults() {
+ void testStringMethodAccuracy_sequence() {
// arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
-
- // act/assert
- checkToEngineeringString(0.0, "0.0", opts);
- checkToEngineeringString(-0.0, "-0.0", opts);
- checkToEngineeringString(1.0, "1.0", opts);
- checkToEngineeringString(1.5, "1.5", opts);
-
- checkToEngineeringString(10, "10.0", opts);
+ final double min = -1000;
+ final double max = 1000;
+ final double delta = 0.1;
- checkToEngineeringString(-0.000000123, "-123.0E-9", opts);
- checkToEngineeringString(12300000, "12.3E6", opts);
-
- checkToEngineeringString(Math.PI, "3.141592653589793", opts);
- checkToEngineeringString(Math.E, "2.718281828459045", opts);
-
- checkToEngineeringString(-Double.MAX_VALUE, "-179.76931348623157E306", opts);
- checkToEngineeringString(Double.MIN_VALUE, "4.9E-324", opts);
- checkToEngineeringString(Double.MIN_NORMAL, "22.250738585072014E-309", opts);
- }
-
- @Test
- void testToEngineeringString_altFormat() {
- // arrange
- final FormatOptionsImpl opts = new FormatOptionsImpl();
- opts.setIncludeFractionPlaceholder(false);
- opts.setSignedZero(false);
- opts.setDecimalSeparator(',');
- opts.setMinusSign('!');
- opts.setExponentSeparator("x10^");
- opts.setAlwaysIncludeExponent(true);
-
- // act/assert
- checkToEngineeringString(0.0, "0x10^0", opts);
- checkToEngineeringString(-0.0, "0x10^0", opts);
- checkToEngineeringString(1.0, "1x10^0", opts);
- checkToEngineeringString(1.5, "1,5x10^0", opts);
+ final FormatOptionsImpl stdOpts = new FormatOptionsImpl();
+ final FormatOptionsImpl altOpts = new FormatOptionsImpl();
+ altOpts.setExponentSeparator("e");
+ altOpts.setIncludeFractionPlaceholder(false);
- checkToEngineeringString(10, "10x10^0", opts);
+ Assertions.assertEquals(10.0, Double.parseDouble(ParsedDecimal.from(10.0).toScientificString(stdOpts)));
- checkToEngineeringString(-0.000000123, "!123x10^!9", opts);
- checkToEngineeringString(12300000, "12,3x10^6", opts);
+ for (double d = min; d <= max; d += delta) {
+ // act/assert
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(altOpts)));
- checkToEngineeringString(Math.PI, "3,141592653589793x10^0", opts);
- checkToEngineeringString(Math.E, "2,718281828459045x10^0", opts);
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(altOpts)));
- checkToEngineeringString(-Double.MAX_VALUE, "!179,76931348623157x10^306", opts);
- checkToEngineeringString(Double.MIN_VALUE, "4,9x10^!324", opts);
- checkToEngineeringString(Double.MIN_NORMAL, "22,250738585072014x10^!309", opts);
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(stdOpts)));
+ Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(altOpts)));
+ }
}
@Test
@@ -464,269 +557,176 @@ class ParsedDecimalTest {
}
@Test
- void testStringMethodAccuracy_sequence() {
+ void testToEngineeringString_altFormat() {
// arrange
- final double min = -1000;
- final double max = 1000;
- final double delta = 0.1;
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
+ opts.setIncludeFractionPlaceholder(false);
+ opts.setSignedZero(false);
+ opts.setDecimalSeparator(',');
+ opts.setMinusSign('!');
+ opts.setExponentSeparator("x10^");
+ opts.setAlwaysIncludeExponent(true);
- final FormatOptionsImpl stdOpts = new FormatOptionsImpl();
- final FormatOptionsImpl altOpts = new FormatOptionsImpl();
- altOpts.setExponentSeparator("e");
- altOpts.setIncludeFractionPlaceholder(false);
+ // act/assert
+ checkToEngineeringString(0.0, "0x10^0", opts);
+ checkToEngineeringString(-0.0, "0x10^0", opts);
+ checkToEngineeringString(1.0, "1x10^0", opts);
+ checkToEngineeringString(1.5, "1,5x10^0", opts);
- Assertions.assertEquals(10.0, Double.parseDouble(ParsedDecimal.from(10.0).toScientificString(stdOpts)));
+ checkToEngineeringString(10, "10x10^0", opts);
- for (double d = min; d <= max; d += delta) {
- // act/assert
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(altOpts)));
+ checkToEngineeringString(-0.000000123, "!123x10^!9", opts);
+ checkToEngineeringString(12300000, "12,3x10^6", opts);
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(altOpts)));
+ checkToEngineeringString(Math.PI, "3,141592653589793x10^0", opts);
+ checkToEngineeringString(Math.E, "2,718281828459045x10^0", opts);
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(altOpts)));
- }
+ checkToEngineeringString(-Double.MAX_VALUE, "!179,76931348623157x10^306", opts);
+ checkToEngineeringString(Double.MIN_VALUE, "4,9x10^!324", opts);
+ checkToEngineeringString(Double.MIN_NORMAL, "22,250738585072014x10^!309", opts);
}
@Test
- void testStringMethodAccuracy_random() {
+ void testToEngineeringString_defaults() {
// arrange
- final UniformRandomProvider rand = RandomSource.create(RandomSource.XO_RO_SHI_RO_128_PP, 0L);
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
- final FormatOptionsImpl stdOpts = new FormatOptionsImpl();
- final FormatOptionsImpl altOpts = new FormatOptionsImpl();
- altOpts.setExponentSeparator("e");
- altOpts.setIncludeFractionPlaceholder(false);
+ // act/assert
+ checkToEngineeringString(0.0, "0.0", opts);
+ checkToEngineeringString(-0.0, "-0.0", opts);
+ checkToEngineeringString(1.0, "1.0", opts);
+ checkToEngineeringString(1.5, "1.5", opts);
- double d;
- for (int i = 0; i < 10_000; ++i) {
- d = createRandomDouble(rand);
+ checkToEngineeringString(10, "10.0", opts);
- // act/assert
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toScientificString(altOpts)));
+ checkToEngineeringString(-0.000000123, "-123.0E-9", opts);
+ checkToEngineeringString(12300000, "12.3E6", opts);
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toEngineeringString(altOpts)));
+ checkToEngineeringString(Math.PI, "3.141592653589793", opts);
+ checkToEngineeringString(Math.E, "2.718281828459045", opts);
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(stdOpts)));
- Assertions.assertEquals(d, Double.parseDouble(ParsedDecimal.from(d).toPlainString(altOpts)));
- }
+ checkToEngineeringString(-Double.MAX_VALUE, "-179.76931348623157E306", opts);
+ checkToEngineeringString(Double.MIN_VALUE, "4.9E-324", opts);
+ checkToEngineeringString(Double.MIN_NORMAL, "22.250738585072014E-309", opts);
}
- private static void checkFrom(final double d, final String digits, final int exponent) {
- final boolean negative = Math.signum(d) < 0;
-
- assertSimpleDecimal(ParsedDecimal.from(d), negative, digits, exponent);
- assertSimpleDecimal(ParsedDecimal.from(-d), !negative, digits, exponent);
- }
+ @Test
+ void testToPlainString_altFormat() {
+ // arrange
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
+ opts.setIncludeFractionPlaceholder(false);
+ opts.setSignedZero(false);
+ opts.setDecimalSeparator(',');
+ opts.setMinusSign('!');
+ opts.setThousandsGroupingSeparator('_');
+ opts.setGroupThousands(true);
- private static void checkToPlainString(final double d, final String expected,
- final ParsedDecimal.FormatOptions opts) {
- checkToStringMethod(d, expected, ParsedDecimal::toPlainString, opts);
- }
+ // act/assert
+ checkToPlainString(0.0, "0", opts);
+ checkToPlainString(-0.0, "0", opts);
+ checkToPlainString(1.0, "1", opts);
+ checkToPlainString(1.5, "1,5", opts);
- private static void checkToScientificString(final double d, final String expected,
- final ParsedDecimal.FormatOptions opts) {
- checkToStringMethod(d, expected, ParsedDecimal::toScientificString, opts);
- }
+ checkToPlainString(12, "12", opts);
+ checkToPlainString(123, "123", opts);
+ checkToPlainString(1234, "1_234", opts);
+ checkToPlainString(12345, "12_345", opts);
+ checkToPlainString(123456, "123_456", opts);
+ checkToPlainString(1234567, "1_234_567", opts);
+ checkToPlainString(12345678, "12_345_678", opts);
+ checkToPlainString(123456789, "123_456_789", opts);
+ checkToPlainString(1234567890, "1_234_567_890", opts);
- private static void checkToEngineeringString(final double d, final String expected,
- final ParsedDecimal.FormatOptions opts) {
- checkToStringMethod(d, expected, ParsedDecimal::toEngineeringString, opts);
+ checkToPlainString(-0.000123, "!0,000123", opts);
+ checkToPlainString(12301, "12_301", opts);
- // check the exponent value to make sure it is a multiple of 3
- final String pos = ParsedDecimal.from(d).toEngineeringString(opts);
- Assertions.assertEquals(0, parseExponent(pos, opts) % 3);
+ checkToPlainString(Math.PI, "3,141592653589793", opts);
+ checkToPlainString(Math.E, "2,718281828459045", opts);
- final String neg = ParsedDecimal.from(-d).toEngineeringString(opts);
- Assertions.assertEquals(0, parseExponent(neg, opts) % 3);
+ checkToPlainString(-12345.6789, "!12_345,6789", opts);
+ checkToPlainString(1.23e12, "1_230_000_000_000", opts);
+ checkToPlainString(1.23e-12, "0,00000000000123", opts);
}
- private static int parseExponent(final String str, final ParsedDecimal.FormatOptions opts) {
- final char[] expSep = opts.getExponentSeparatorChars();
-
- final int expStartIdx = str.indexOf(String.valueOf(expSep));
- if (expStartIdx > -1) {
- int expIdx = expStartIdx + expSep.length;
-
- boolean neg = false;
- if (str.charAt(expIdx) == opts.getMinusSign()) {
- ++expIdx;
- neg = true;
- }
-
- final String expStr = str.substring(expIdx);
- final int val = Integer.parseInt(expStr);
- return neg
- ? -val
- : val;
- }
-
- return 0;
- }
+ @Test
+ void testToPlainString_defaults() {
+ // arrange
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
- private static void checkToStringMethod(final double d, final String expected,
- final BiFunction<ParsedDecimal, ParsedDecimal.FormatOptions, String> fn,
- final ParsedDecimal.FormatOptions opts) {
+ // act/assert
+ checkToPlainString(0.0, "0.0", opts);
+ checkToPlainString(-0.0, "-0.0", opts);
+ checkToPlainString(1.0, "1.0", opts);
+ checkToPlainString(1.5, "1.5", opts);
- final ParsedDecimal pos = ParsedDecimal.from(d);
- final String actual = fn.apply(pos, opts);
+ checkToPlainString(12, "12.0", opts);
+ checkToPlainString(123, "123.0", opts);
+ checkToPlainString(1234, "1234.0", opts);
+ checkToPlainString(12345, "12345.0", opts);
+ checkToPlainString(123456, "123456.0", opts);
+ checkToPlainString(1234567, "1234567.0", opts);
+ checkToPlainString(12345678, "12345678.0", opts);
+ checkToPlainString(123456789, "123456789.0", opts);
+ checkToPlainString(1234567890, "1234567890.0", opts);
- Assertions.assertEquals(expected, actual);
- }
+ checkToPlainString(-0.000123, "-0.000123", opts);
+ checkToPlainString(12301, "12301.0", opts);
- private static void assertRound(final double d, final int roundExponent,
- final boolean negative, final String digits, final int exponent) {
- final ParsedDecimal dec = ParsedDecimal.from(d);
- dec.round(roundExponent);
+ checkToPlainString(Math.PI, "3.141592653589793", opts);
+ checkToPlainString(Math.E, "2.718281828459045", opts);
- assertSimpleDecimal(dec, negative, digits, exponent);
+ checkToPlainString(-12345.6789, "-12345.6789", opts);
+ checkToPlainString(1.23e12, "1230000000000.0", opts);
+ checkToPlainString(1.23e-12, "0.00000000000123", opts);
}
- private static void assertMaxPrecision(final double d, final int maxPrecision,
- final boolean negative, final String digits, final int exponent) {
- final ParsedDecimal dec = ParsedDecimal.from(d);
- dec.maxPrecision(maxPrecision);
-
- assertSimpleDecimal(dec, negative, digits, exponent);
- }
+ @Test
+ void testToScientificString_altFormats() {
+ // arrange
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
+ opts.setIncludeFractionPlaceholder(false);
+ opts.setSignedZero(false);
+ opts.setDecimalSeparator(',');
+ opts.setMinusSign('!');
+ opts.setExponentSeparator("x10^");
+ opts.setAlwaysIncludeExponent(true);
- private static void assertSimpleDecimal(final ParsedDecimal parsed, final boolean negative, final String digits,
- final int exponent) {
- Assertions.assertEquals(negative, parsed.negative);
- Assertions.assertEquals(digits, digitString(parsed));
- Assertions.assertEquals(exponent, parsed.getExponent());
- Assertions.assertEquals(digits.length(), parsed.digitCount);
- Assertions.assertEquals(exponent, parsed.getScientificExponent() - digits.length() + 1);
- }
+ // act/assert
+ checkToScientificString(0.0, "0x10^0", opts);
+ checkToScientificString(-0.0, "0x10^0", opts);
+ checkToScientificString(1.0, "1x10^0", opts);
+ checkToScientificString(1.5, "1,5x10^0", opts);
- private static void assertThrowsWithMessage(final Executable fn, final Class<? extends Throwable> type,
- final String msg) {
- final Throwable exc = Assertions.assertThrows(type, fn);
- Assertions.assertEquals(msg, exc.getMessage());
- }
+ checkToScientificString(-0.000123, "!1,23x10^!4", opts);
+ checkToScientificString(12301, "1,2301x10^4", opts);
- private static double createRandomDouble(final UniformRandomProvider rng) {
- final long mask = ((1L << 52) - 1) | 1L << 63;
- final long bits = rng.nextLong() & mask;
- final long exp = rng.nextInt(2045) + 1;
- return Double.longBitsToDouble(bits | (exp << 52));
- }
+ checkToScientificString(Math.PI, "3,141592653589793x10^0", opts);
+ checkToScientificString(Math.E, "2,718281828459045x10^0", opts);
- /** Get the raw digits in the given decimal as a string.
- * @param dec decimal instancE
- * @return decimal digits as a string
- */
- private static String digitString(final ParsedDecimal dec) {
- final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < dec.digitCount; ++i) {
- sb.append(dec.digits[i]);
- }
- return sb.toString();
+ checkToScientificString(-Double.MAX_VALUE, "!1,7976931348623157x10^308", opts);
+ checkToScientificString(Double.MIN_VALUE, "4,9x10^!324", opts);
+ checkToScientificString(Double.MIN_NORMAL, "2,2250738585072014x10^!308", opts);
}
- private static final class FormatOptionsImpl implements ParsedDecimal.FormatOptions {
-
- private boolean includeFractionPlaceholder = true;
-
- private boolean signedZero = true;
-
- private char[] digits = "0123456789".toCharArray();
-
- private char decimalSeparator = '.';
-
- private char thousandsGroupingSeparator = ',';
-
- private boolean groupThousands = false;
-
- private char minusSign = '-';
-
- private String exponentSeparator = "E";
-
- private boolean alwaysIncludeExponent = false;
-
- @Override
- public boolean isIncludeFractionPlaceholder() {
- return includeFractionPlaceholder;
- }
-
- public void setIncludeFractionPlaceholder(final boolean includeFractionPlaceholder) {
- this.includeFractionPlaceholder = includeFractionPlaceholder;
- }
-
- @Override
- public boolean isSignedZero() {
- return signedZero;
- }
-
- public void setSignedZero(final boolean signedZero) {
- this.signedZero = signedZero;
- }
-
- @Override
- public char[] getDigits() {
- return digits;
- }
-
- public void setDigitsFromString(final String digits) {
- this.digits = digits.toCharArray();
- }
-
- @Override
- public char getDecimalSeparator() {
- return decimalSeparator;
- }
-
- public void setDecimalSeparator(final char decimalSeparator) {
- this.decimalSeparator = decimalSeparator;
- }
-
- @Override
- public char getGroupingSeparator() {
- return thousandsGroupingSeparator;
- }
-
- public void setThousandsGroupingSeparator(final char thousandsGroupingSeparator) {
- this.thousandsGroupingSeparator = thousandsGroupingSeparator;
- }
-
- @Override
- public boolean isGroupThousands() {
- return groupThousands;
- }
-
- public void setGroupThousands(final boolean groupThousands) {
- this.groupThousands = groupThousands;
- }
-
- @Override
- public char getMinusSign() {
- return minusSign;
- }
-
- public void setMinusSign(final char minusSign) {
- this.minusSign = minusSign;
- }
+ @Test
+ void testToScientificString_defaults() {
+ // arrange
+ final FormatOptionsImpl opts = new FormatOptionsImpl();
- @Override
- public char[] getExponentSeparatorChars() {
- return exponentSeparator.toCharArray();
- }
+ // act/assert
+ checkToScientificString(0.0, "0.0", opts);
+ checkToScientificString(-0.0, "-0.0", opts);
+ checkToScientificString(1.0, "1.0", opts);
+ checkToScientificString(1.5, "1.5", opts);
- public void setExponentSeparator(final String exponentSeparator) {
- this.exponentSeparator = exponentSeparator;
- }
+ checkToScientificString(-0.000123, "-1.23E-4", opts);
+ checkToScientificString(12301, "1.2301E4", opts);
- @Override
- public boolean isAlwaysIncludeExponent() {
- return alwaysIncludeExponent;
- }
+ checkToScientificString(Math.PI, "3.141592653589793", opts);
+ checkToScientificString(Math.E, "2.718281828459045", opts);
- public void setAlwaysIncludeExponent(final boolean alwaysIncludeExponent) {
- this.alwaysIncludeExponent = alwaysIncludeExponent;
- }
+ checkToScientificString(-Double.MAX_VALUE, "-1.7976931348623157E308", opts);
+ checkToScientificString(Double.MIN_VALUE, "4.9E-324", opts);
+ checkToScientificString(Double.MIN_NORMAL, "2.2250738585072014E-308", opts);
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
index 62a76196..609cf689 100644
--- a/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/CosineDistanceTest.java
@@ -42,6 +42,18 @@ public class CosineDistanceTest {
cosineDistance = new CosineDistance();
}
+ /**
+ * 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();
+ }
+
+ // --- Utility methods
+
/**
* Tests the cosine distance with several inputs.
*/
@@ -56,16 +68,4 @@ public class CosineDistanceTest {
.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
index b7e06854..ffc82468 100644
--- a/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/CosineSimilarityTest.java
@@ -30,14 +30,11 @@ import org.junit.jupiter.api.Test;
public class CosineSimilarityTest {
@Test
- public void testCosineSimilarityWithNonEmptyMap() {
+ public void testCosineSimilarityReturningDoubleWhereByteValueIsZero() {
final CosineSimilarity cosineSimilarity = new CosineSimilarity();
final Map<CharSequence, Integer> hashMap = new HashMap<>();
- final Integer integer = -397;
- hashMap.put("3J/$3.L", integer);
- final Map<CharSequence, Integer> hashMapTwo = new HashMap<>();
- assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMapTwo)).isEqualTo(0.0, within(0.01));
+ assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMap)).isEqualTo(0.0, within(0.01));
}
@Test
@@ -49,6 +46,17 @@ public class CosineSimilarityTest {
});
}
+ @Test
+ public void testCosineSimilarityWithNonEmptyMap() {
+ final CosineSimilarity cosineSimilarity = new CosineSimilarity();
+ final Map<CharSequence, Integer> hashMap = new HashMap<>();
+ final Integer integer = -397;
+ hashMap.put("3J/$3.L", integer);
+ final Map<CharSequence, Integer> hashMapTwo = new HashMap<>();
+
+ assertThat(cosineSimilarity.cosineSimilarity(hashMap, hashMapTwo)).isEqualTo(0.0, within(0.01));
+ }
+
@Test
public void testCosineSimilarityWithNull() {
assertThatIllegalArgumentException().isThrownBy(() -> {
@@ -57,12 +65,4 @@ public class CosineSimilarityTest {
});
}
- @Test
- public void testCosineSimilarityReturningDoubleWhereByteValueIsZero() {
- final CosineSimilarity cosineSimilarity = new CosineSimilarity();
- final Map<CharSequence, Integer> 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
index 20e98eb0..a8cf990f 100644
--- a/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/FuzzyScoreTest.java
@@ -42,8 +42,8 @@ public class FuzzyScoreTest {
}
@Test
- public void testGetFuzzyScore_StringNullLocale() {
- assertThatIllegalArgumentException().isThrownBy(() -> ENGLISH_SCORE.fuzzyScore("not null", null));
+ public void testGetFuzzyScore_NullNullLocale() {
+ assertThatIllegalArgumentException().isThrownBy(() -> ENGLISH_SCORE.fuzzyScore(null, null));
}
@Test
@@ -52,13 +52,8 @@ public class FuzzyScoreTest {
}
@Test
- public void testGetFuzzyScore_NullNullLocale() {
- assertThatIllegalArgumentException().isThrownBy(() -> ENGLISH_SCORE.fuzzyScore(null, null));
- }
-
- @Test
- public void testMissingLocale() {
- assertThatIllegalArgumentException().isThrownBy(() -> new FuzzyScore((Locale) null));
+ public void testGetFuzzyScore_StringNullLocale() {
+ assertThatIllegalArgumentException().isThrownBy(() -> ENGLISH_SCORE.fuzzyScore("not null", null));
}
@Test
@@ -70,4 +65,9 @@ public class FuzzyScoreTest {
assertThat(localeTwo).isSameAs(locale);
}
+ @Test
+ public void testMissingLocale() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new FuzzyScore((Locale) null));
+ }
+
}
diff --git a/src/test/java/org/apache/commons/text/similarity/IntersectionResultTest.java b/src/test/java/org/apache/commons/text/similarity/IntersectionResultTest.java
index 29131aac..5e1d268e 100644
--- a/src/test/java/org/apache/commons/text/similarity/IntersectionResultTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/IntersectionResultTest.java
@@ -27,11 +27,59 @@ import org.junit.jupiter.api.Test;
*/
public class IntersectionResultTest {
@Test
- public void testNewIntersectionResult_WithZeros() {
+ public void testEquals() {
+ final IntersectionResult[] results = {
+ new IntersectionResult(0, 0, 0),
+ new IntersectionResult(10, 0, 0),
+ new IntersectionResult(10, 10, 0),
+ new IntersectionResult(10, 10, 10),
+ };
+
+ // Test a different instance with same values
+ Assertions.assertEquals(results[0], new IntersectionResult(0, 0, 0));
+
+ final Object something = new Object();
+ for (int i = 0; i < results.length; i++) {
+ Assertions.assertNotEquals(results[i], something);
+ Assertions.assertNotEquals(null, results[i]);
+ for (int j = 0; j < results.length; j++) {
+ Assertions.assertEquals(results[i].equals(results[j]), (i == j));
+ }
+ }
+ }
+
+ @Test
+ public void testHashCode() {
+ final IntersectionResult[] results = {
+ new IntersectionResult(10, 0, 0),
+ new IntersectionResult(10, 10, 0),
+ new IntersectionResult(10, 10, 10),
+ };
+ final HashMap<IntersectionResult, Integer> map = new HashMap<>();
+ final int offset = 123;
+ for (int i = 0; i < results.length; i++) {
+ map.put(results[i], i + offset);
+ }
+ for (int i = 0; i < results.length; i++) {
+ Assertions.assertEquals(i + offset, map.get(results[i]));
+ }
+ }
+
+ @Test
+ public void testNewIntersectionResult_WithIntersectionAboveSizeAorB() {
+ final int sizeA = 1;
+ final int sizeB = 2;
+ final int intersection = Math.max(sizeA, sizeB) + 1;
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeA, sizeB, intersection));
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeB, sizeA, intersection));
+ }
+
+ @Test
+ public void testNewIntersectionResult_WithNegativeIntersection() {
final int sizeA = 0;
final int sizeB = 0;
- final int intersection = 0;
- new IntersectionResult(sizeA, sizeB, intersection);
+ final int intersection = -1;
+ Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeA, sizeB, intersection));
}
@Test
@@ -51,20 +99,11 @@ public class IntersectionResultTest {
}
@Test
- public void testNewIntersectionResult_WithNegativeIntersection() {
+ public void testNewIntersectionResult_WithZeros() {
final int sizeA = 0;
final int sizeB = 0;
- final int intersection = -1;
- Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeA, sizeB, intersection));
- }
-
- @Test
- public void testNewIntersectionResult_WithIntersectionAboveSizeAorB() {
- final int sizeA = 1;
- final int sizeB = 2;
- final int intersection = Math.max(sizeA, sizeB) + 1;
- Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeA, sizeB, intersection));
- Assertions.assertThrows(IllegalArgumentException.class, () -> new IntersectionResult(sizeB, sizeA, intersection));
+ final int intersection = 0;
+ new IntersectionResult(sizeA, sizeB, intersection);
}
@Test
@@ -83,45 +122,6 @@ public class IntersectionResultTest {
}
}
- @Test
- public void testEquals() {
- final IntersectionResult[] results = {
- new IntersectionResult(0, 0, 0),
- new IntersectionResult(10, 0, 0),
- new IntersectionResult(10, 10, 0),
- new IntersectionResult(10, 10, 10),
- };
-
- // Test a different instance with same values
- Assertions.assertEquals(results[0], new IntersectionResult(0, 0, 0));
-
- final Object something = new Object();
- for (int i = 0; i < results.length; i++) {
- Assertions.assertNotEquals(results[i], something);
- Assertions.assertNotEquals(null, results[i]);
- for (int j = 0; j < results.length; j++) {
- Assertions.assertEquals(results[i].equals(results[j]), (i == j));
- }
- }
- }
-
- @Test
- public void testHashCode() {
- final IntersectionResult[] results = {
- new IntersectionResult(10, 0, 0),
- new IntersectionResult(10, 10, 0),
- new IntersectionResult(10, 10, 10),
- };
- final HashMap<IntersectionResult, Integer> map = new HashMap<>();
- final int offset = 123;
- for (int i = 0; i < results.length; i++) {
- map.put(results[i], i + offset);
- }
- for (int i = 0; i < results.length; i++) {
- Assertions.assertEquals(i + offset, map.get(results[i]));
- }
- }
-
@Test
public void testToString() {
final ThreadLocalRandom rand = ThreadLocalRandom.current();
diff --git a/src/test/java/org/apache/commons/text/similarity/IntersectionSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/IntersectionSimilarityTest.java
index b5deda14..b54529f9 100644
--- a/src/test/java/org/apache/commons/text/similarity/IntersectionSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/IntersectionSimilarityTest.java
@@ -35,149 +35,31 @@ import org.junit.jupiter.api.Test;
* Unit tests for {@link IntersectionSimilarity}.
*/
public class IntersectionSimilarityTest {
- @Test
- public void testIntersectionUsingSetCharacter() {
- // Compute using single characters.
- // This test uses a set and so should not allow duplicates.
- final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toCharacterSet);
-
- // Expected:
- // size A or B = count of unique characters (exclude duplicates)
- // intersection = count of unique matching characters (exclude duplicates)
- assertIntersection(similarity, "", "", 0, 0, 0);
- assertIntersection(similarity, "a", "", 1, 0, 0);
- assertIntersection(similarity, "a", "a", 1, 1, 1);
- assertIntersection(similarity, "a", "b", 1, 1, 0);
- assertIntersection(similarity, "aa", "ab", 1, 2, 1);
- assertIntersection(similarity, "ab", "ab", 2, 2, 2);
- assertIntersection(similarity, "aaba", "abaa", 2, 2, 2);
- assertIntersection(similarity, "aaaa", "aa", 1, 1, 1);
- assertIntersection(similarity, "aa", "aaaa", 1, 1, 1);
- assertIntersection(similarity, "aaaa", "aaa", 1, 1, 1);
- assertIntersection(similarity, "aabab", "ababa", 2, 2, 2);
- assertIntersection(similarity, "the same", "the same", 7, 7, 7);
- assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 13, 13, 11);
- }
-
- @Test
- public void testIntersectionUsingListCharacter() {
- // Compute using single characters.
- // This test uses a list and so duplicates should be matched.
- final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toCharacterList);
-
- // Expected:
- // size A or B = sequence length
- // intersection = count of matching characters (include duplicates)
- assertIntersection(similarity, "", "", 0, 0, 0);
- assertIntersection(similarity, "a", "", 1, 0, 0);
- assertIntersection(similarity, "a", "a", 1, 1, 1);
- assertIntersection(similarity, "a", "b", 1, 1, 0);
- assertIntersection(similarity, "aa", "ab", 2, 2, 1);
- assertIntersection(similarity, "ab", "ab", 2, 2, 2);
- assertIntersection(similarity, "aaba", "abaa", 4, 4, 4);
- assertIntersection(similarity, "aaaa", "aa", 4, 2, 2);
- assertIntersection(similarity, "aa", "aaaa", 2, 4, 2);
- assertIntersection(similarity, "aaaa", "aaa", 4, 3, 3);
- assertIntersection(similarity, "aabab", "ababa", 5, 5, 5);
- assertIntersection(similarity, "the same", "the same", 8, 8, 8);
- assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 13, 13, 11);
- }
-
- @Test
- public void testIntersectionUsingSetBigrams() {
- // Compute using pairs of characters (bigrams).
- // This can be done using a 32-bit int to store two 16-bit characters.
- // This test uses a set and so should not allow duplicates.
- final IntersectionSimilarity<Integer> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toBigramSet);
-
- // Expected:
- // size A or B = count of unique bigrams (exclude duplicates)
- // intersection = count of unique matching bigrams (exclude duplicates)
- assertIntersection(similarity, "", "", 0, 0, 0);
- assertIntersection(similarity, "a", "", 0, 0, 0);
- assertIntersection(similarity, "a", "a", 0, 0, 0);
- assertIntersection(similarity, "a", "b", 0, 0, 0);
- assertIntersection(similarity, "aa", "ab", 1, 1, 0);
- assertIntersection(similarity, "ab", "ab", 1, 1, 1);
- assertIntersection(similarity, "aaba", "abaa", 3, 3, 3);
- assertIntersection(similarity, "aaaa", "aa", 1, 1, 1);
- assertIntersection(similarity, "aa", "aaaa", 1, 1, 1);
- assertIntersection(similarity, "aaaa", "aaa", 1, 1, 1);
- assertIntersection(similarity, "aabab", "ababa", 3, 2, 2);
- assertIntersection(similarity, "the same", "the same", 7, 7, 7);
- assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 12, 12, 8);
- }
-
- @Test
- public void testIntersectionUsingListBigrams() {
- // Compute using pairs of characters (bigrams).
- // This can be done using a 32-bit int to store two 16-bit characters.
- // This test uses a list and so duplicates should be matched.
- final IntersectionSimilarity<Integer> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toBigramList);
-
- // Expected:
- // size A or B = sequence length - 1
- // intersection = count of matching bigrams (include duplicates)
- assertIntersection(similarity, "", "", 0, 0, 0);
- assertIntersection(similarity, "a", "", 0, 0, 0);
- assertIntersection(similarity, "a", "a", 0, 0, 0);
- assertIntersection(similarity, "a", "b", 0, 0, 0);
- assertIntersection(similarity, "aa", "ab", 1, 1, 0);
- assertIntersection(similarity, "ab", "ab", 1, 1, 1);
- assertIntersection(similarity, "aaba", "abaa", 3, 3, 3);
- assertIntersection(similarity, "aaaa", "aa", 3, 1, 1);
- assertIntersection(similarity, "aa", "aaaa", 1, 3, 1);
- assertIntersection(similarity, "aaaa", "aaa", 3, 2, 2);
- assertIntersection(similarity, "aabab", "ababa", 4, 4, 3);
- assertIntersection(similarity, "the same", "the same", 7, 7, 7);
- assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 12, 12, 8);
- }
-
- @Test
- public void testIntersectionUsingSetCharacterListCharacter() {
- // Compute using a custom converter that returns a Set and a List.
- // This is an edge-case test.
- final HashMap<CharSequence, Collection<Character>> converter = new HashMap<>();
- final String sequence1 = "aabbccdd";
- final String sequence2 = "aaaaaabbbfffff";
- converter.put(sequence1, toCharacterSet(sequence1));
- converter.put(sequence2, toCharacterList(sequence2));
- final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(converter::get);
-
- // Expected:
- // size A = count of unique characters (exclude duplicates)
- // size B = sequence length
- // intersection = count of matching characters (exclude duplicates)
- assertIntersection(similarity, sequence1, sequence2, 4, sequence2.length(), 2);
- assertIntersection(similarity, sequence2, sequence1, sequence2.length(), 4, 2);
- }
-
- /**
- * Convert the {@link CharSequence} to a {@link Set} of {@link Character}s.
- *
- * @param sequence the sequence
- * @return the set
- */
- private static Set<Character> toCharacterSet(final CharSequence sequence) {
- final int length = sequence.length();
- final Set<Character> set = new HashSet<>(length);
- for (int i = 0; i < length; i++) {
- set.add(sequence.charAt(i));
- }
- return set;
+ private static <T> void assertIntersection(final IntersectionSimilarity<T> similarity, final CharSequence cs1, final CharSequence cs2, final int sizeA,
+ final int sizeB, final int intersection) {
+ final IntersectionResult result = similarity.apply(cs1, cs2);
+ assertEquals(sizeA, result.getSizeA(), "Size A error");
+ assertEquals(sizeB, result.getSizeB(), "Size B error");
+ assertEquals(intersection, result.getIntersection(), "Intersection error");
}
/**
- * Convert the {@link CharSequence} to a {@link List} of {@link Character}s.
+ * Convert the {@link CharSequence} to a {@link List} of bigrams (pairs of characters). These are represented using 2
+ * 16-bit chars packed into a 32-bit int.
*
* @param sequence the sequence
* @return the list
*/
- private static List<Character> toCharacterList(final CharSequence sequence) {
+ private static List<Integer> toBigramList(final CharSequence sequence) {
final int length = sequence.length();
- final List<Character> list = new ArrayList<>(length);
- for (int i = 0; i < length; i++) {
- list.add(sequence.charAt(i));
+ final List<Integer> list = new ArrayList<>(length);
+ if (length > 1) {
+ char ch2 = sequence.charAt(0);
+ for (int i = 1; i < length; i++) {
+ final char ch1 = ch2;
+ ch2 = sequence.charAt(i);
+ list.add(Integer.valueOf((ch1 << 16) | ch2));
+ }
}
return list;
}
@@ -204,32 +86,62 @@ public class IntersectionSimilarityTest {
}
/**
- * Convert the {@link CharSequence} to a {@link List} of bigrams (pairs of characters). These are represented using 2
- * 16-bit chars packed into a 32-bit int.
+ * Convert the {@link CharSequence} to a {@link List} of {@link Character}s.
*
* @param sequence the sequence
* @return the list
*/
- private static List<Integer> toBigramList(final CharSequence sequence) {
+ private static List<Character> toCharacterList(final CharSequence sequence) {
final int length = sequence.length();
- final List<Integer> list = new ArrayList<>(length);
- if (length > 1) {
- char ch2 = sequence.charAt(0);
- for (int i = 1; i < length; i++) {
- final char ch1 = ch2;
- ch2 = sequence.charAt(i);
- list.add(Integer.valueOf((ch1 << 16) | ch2));
- }
+ final List<Character> list = new ArrayList<>(length);
+ for (int i = 0; i < length; i++) {
+ list.add(sequence.charAt(i));
}
return list;
}
- private static <T> void assertIntersection(final IntersectionSimilarity<T> similarity, final CharSequence cs1, final CharSequence cs2, final int sizeA,
- final int sizeB, final int intersection) {
- final IntersectionResult result = similarity.apply(cs1, cs2);
- assertEquals(sizeA, result.getSizeA(), "Size A error");
- assertEquals(sizeB, result.getSizeB(), "Size B error");
- assertEquals(intersection, result.getIntersection(), "Intersection error");
+ /**
+ * Convert the {@link CharSequence} to a {@link Set} of {@link Character}s.
+ *
+ * @param sequence the sequence
+ * @return the set
+ */
+ private static Set<Character> toCharacterSet(final CharSequence sequence) {
+ final int length = sequence.length();
+ final Set<Character> set = new HashSet<>(length);
+ for (int i = 0; i < length; i++) {
+ set.add(sequence.charAt(i));
+ }
+ return set;
+ }
+
+ private static int toF1ScorePercent(final IntersectionResult result) {
+ final double value = 2.0 * result.getIntersection() / (result.getSizeA() + result.getSizeB());
+ // Convert to percentage
+ return (int) Math.round(value * 100);
+ }
+
+ @Test
+ public void testApplyNullNull() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply(null, null));
+ }
+
+ @Test
+ public void testApplyNullString() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply(null, "right"));
+ }
+
+ @Test
+ public void testApplyStringNull() {
+ assertThatIllegalArgumentException()
+ .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply("left", null));
+ }
+
+ @Test
+ public void testConstructorWithNullConverterThrows() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new IntersectionSimilarity<>(null));
}
@Test
@@ -299,32 +211,120 @@ public class IntersectionSimilarityTest {
assertEquals(12, toF1ScorePercent(similarity.apply(bookTitle, search3)));
}
- private static int toF1ScorePercent(final IntersectionResult result) {
- final double value = 2.0 * result.getIntersection() / (result.getSizeA() + result.getSizeB());
- // Convert to percentage
- return (int) Math.round(value * 100);
+ @Test
+ public void testIntersectionUsingListBigrams() {
+ // Compute using pairs of characters (bigrams).
+ // This can be done using a 32-bit int to store two 16-bit characters.
+ // This test uses a list and so duplicates should be matched.
+ final IntersectionSimilarity<Integer> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toBigramList);
+
+ // Expected:
+ // size A or B = sequence length - 1
+ // intersection = count of matching bigrams (include duplicates)
+ assertIntersection(similarity, "", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "a", 0, 0, 0);
+ assertIntersection(similarity, "a", "b", 0, 0, 0);
+ assertIntersection(similarity, "aa", "ab", 1, 1, 0);
+ assertIntersection(similarity, "ab", "ab", 1, 1, 1);
+ assertIntersection(similarity, "aaba", "abaa", 3, 3, 3);
+ assertIntersection(similarity, "aaaa", "aa", 3, 1, 1);
+ assertIntersection(similarity, "aa", "aaaa", 1, 3, 1);
+ assertIntersection(similarity, "aaaa", "aaa", 3, 2, 2);
+ assertIntersection(similarity, "aabab", "ababa", 4, 4, 3);
+ assertIntersection(similarity, "the same", "the same", 7, 7, 7);
+ assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 12, 12, 8);
}
@Test
- public void testConstructorWithNullConverterThrows() {
- assertThatIllegalArgumentException().isThrownBy(() -> new IntersectionSimilarity<>(null));
+ public void testIntersectionUsingListCharacter() {
+ // Compute using single characters.
+ // This test uses a list and so duplicates should be matched.
+ final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toCharacterList);
+
+ // Expected:
+ // size A or B = sequence length
+ // intersection = count of matching characters (include duplicates)
+ assertIntersection(similarity, "", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "", 1, 0, 0);
+ assertIntersection(similarity, "a", "a", 1, 1, 1);
+ assertIntersection(similarity, "a", "b", 1, 1, 0);
+ assertIntersection(similarity, "aa", "ab", 2, 2, 1);
+ assertIntersection(similarity, "ab", "ab", 2, 2, 2);
+ assertIntersection(similarity, "aaba", "abaa", 4, 4, 4);
+ assertIntersection(similarity, "aaaa", "aa", 4, 2, 2);
+ assertIntersection(similarity, "aa", "aaaa", 2, 4, 2);
+ assertIntersection(similarity, "aaaa", "aaa", 4, 3, 3);
+ assertIntersection(similarity, "aabab", "ababa", 5, 5, 5);
+ assertIntersection(similarity, "the same", "the same", 8, 8, 8);
+ assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 13, 13, 11);
}
@Test
- public void testApplyNullNull() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply(null, null));
+ public void testIntersectionUsingSetBigrams() {
+ // Compute using pairs of characters (bigrams).
+ // This can be done using a 32-bit int to store two 16-bit characters.
+ // This test uses a set and so should not allow duplicates.
+ final IntersectionSimilarity<Integer> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toBigramSet);
+
+ // Expected:
+ // size A or B = count of unique bigrams (exclude duplicates)
+ // intersection = count of unique matching bigrams (exclude duplicates)
+ assertIntersection(similarity, "", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "a", 0, 0, 0);
+ assertIntersection(similarity, "a", "b", 0, 0, 0);
+ assertIntersection(similarity, "aa", "ab", 1, 1, 0);
+ assertIntersection(similarity, "ab", "ab", 1, 1, 1);
+ assertIntersection(similarity, "aaba", "abaa", 3, 3, 3);
+ assertIntersection(similarity, "aaaa", "aa", 1, 1, 1);
+ assertIntersection(similarity, "aa", "aaaa", 1, 1, 1);
+ assertIntersection(similarity, "aaaa", "aaa", 1, 1, 1);
+ assertIntersection(similarity, "aabab", "ababa", 3, 2, 2);
+ assertIntersection(similarity, "the same", "the same", 7, 7, 7);
+ assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 12, 12, 8);
}
@Test
- public void testApplyStringNull() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply("left", null));
+ public void testIntersectionUsingSetCharacter() {
+ // Compute using single characters.
+ // This test uses a set and so should not allow duplicates.
+ final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(IntersectionSimilarityTest::toCharacterSet);
+
+ // Expected:
+ // size A or B = count of unique characters (exclude duplicates)
+ // intersection = count of unique matching characters (exclude duplicates)
+ assertIntersection(similarity, "", "", 0, 0, 0);
+ assertIntersection(similarity, "a", "", 1, 0, 0);
+ assertIntersection(similarity, "a", "a", 1, 1, 1);
+ assertIntersection(similarity, "a", "b", 1, 1, 0);
+ assertIntersection(similarity, "aa", "ab", 1, 2, 1);
+ assertIntersection(similarity, "ab", "ab", 2, 2, 2);
+ assertIntersection(similarity, "aaba", "abaa", 2, 2, 2);
+ assertIntersection(similarity, "aaaa", "aa", 1, 1, 1);
+ assertIntersection(similarity, "aa", "aaaa", 1, 1, 1);
+ assertIntersection(similarity, "aaaa", "aaa", 1, 1, 1);
+ assertIntersection(similarity, "aabab", "ababa", 2, 2, 2);
+ assertIntersection(similarity, "the same", "the same", 7, 7, 7);
+ assertIntersection(similarity, "abcdefghijklm", "ab_defg ijklm", 13, 13, 11);
}
@Test
- public void testApplyNullString() {
- assertThatIllegalArgumentException()
- .isThrownBy(() -> new IntersectionSimilarity<>(cs -> new HashSet<>(Collections.singletonList(cs))).apply(null, "right"));
+ public void testIntersectionUsingSetCharacterListCharacter() {
+ // Compute using a custom converter that returns a Set and a List.
+ // This is an edge-case test.
+ final HashMap<CharSequence, Collection<Character>> converter = new HashMap<>();
+ final String sequence1 = "aabbccdd";
+ final String sequence2 = "aaaaaabbbfffff";
+ converter.put(sequence1, toCharacterSet(sequence1));
+ converter.put(sequence2, toCharacterList(sequence2));
+ final IntersectionSimilarity<Character> similarity = new IntersectionSimilarity<>(converter::get);
+
+ // Expected:
+ // size A = count of unique characters (exclude duplicates)
+ // size B = sequence length
+ // intersection = count of matching characters (exclude duplicates)
+ assertIntersection(similarity, sequence1, sequence2, 4, sequence2.length(), 2);
+ assertIntersection(similarity, sequence2, sequence1, sequence2.length(), 4, 2);
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
index 80171b84..83830078 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaccardDistanceTest.java
@@ -60,12 +60,12 @@ public class JaccardDistanceTest {
}
@Test
- public void testGettingJaccardDistanceStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(" ", null));
+ public void testGettingJaccardDistanceNullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(null, "right"));
}
@Test
- public void testGettingJaccardDistanceNullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(null, "right"));
+ public void testGettingJaccardDistanceStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(" ", null));
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
index 727376b0..5e3bb3c3 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaccardSimilarityTest.java
@@ -60,12 +60,12 @@ public class JaccardSimilarityTest {
}
@Test
- public void testGettingJaccardSimilarityStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(" ", null));
+ public void testGettingJaccardSimilarityNullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(null, "right"));
}
@Test
- public void testGettingJaccardSimilarityNullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(null, "right"));
+ public void testGettingJaccardSimilarityStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> classBeingTested.apply(" ", null));
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
index bf313541..104b6e30 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaroWinklerDistanceTest.java
@@ -34,6 +34,21 @@ public class JaroWinklerDistanceTest {
distance = new JaroWinklerDistance();
}
+ @Test
+ public void testGetJaroWinklerDistance_NullNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> distance.apply(null, null));
+ }
+
+ @Test
+ public void testGetJaroWinklerDistance_NullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> distance.apply(null, "clear"));
+ }
+
+ @Test
+ public void testGetJaroWinklerDistance_StringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> distance.apply(" ", null));
+ }
+
@Test
public void testGetJaroWinklerDistance_StringString() {
assertEquals(0.07501d, distance.apply("frog", "fog"), 0.00001d);
@@ -54,19 +69,4 @@ public class JaroWinklerDistanceTest {
assertEquals(1 - 0.51111d, distance.apply("foo", " foo"), 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/JaroWinklerSimilarityTest.java b/src/test/java/org/apache/commons/text/similarity/JaroWinklerSimilarityTest.java
index 4fb50e9e..e69fb51f 100644
--- a/src/test/java/org/apache/commons/text/similarity/JaroWinklerSimilarityTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/JaroWinklerSimilarityTest.java
@@ -34,27 +34,6 @@ public class JaroWinklerSimilarityTest {
similarity = new JaroWinklerSimilarity();
}
- @Test
- public void testGetJaroWinklerSimilarity_StringString() {
- assertEquals(1d, similarity.apply(wrap(""), ""), 0.00001d);
- assertEquals(1d, similarity.apply(wrap("foo"), "foo"), 0.00001d);
- assertEquals(0.94166d, similarity.apply(wrap("foo"), "foo "), 0.00001d);
- assertEquals(0.90666d, similarity.apply(wrap("foo"), "foo "), 0.00001d);
- assertEquals(0.86666d, similarity.apply(wrap("foo"), " foo "), 0.00001d);
- assertEquals(0.51111d, similarity.apply(wrap("foo"), " foo"), 0.00001d);
- assertEquals(0.92499d, similarity.apply(wrap("frog"), "fog"), 0.00001d);
- assertEquals(0.0d, similarity.apply(wrap("fly"), "ant"), 0.00000000000000000001d);
- assertEquals(0.44166d, similarity.apply(wrap("elephant"), "hippo"), 0.00001d);
- assertEquals(0.90666d, similarity.apply(wrap("ABC Corporation"), "ABC Corp"), 0.00001d);
- assertEquals(0.95251d, similarity.apply(wrap("D N H Enterprises Inc"), "D & H Enterprises, Inc."), 0.00001d);
- assertEquals(0.942d,
- similarity.apply(wrap("My Gym Children's Fitness Center"), "My Gym. Childrens Fitness"), 0.00001d);
- assertEquals(0.898018d, similarity.apply(wrap("PENNSYLVANIA"), "PENNCISYLVNIA"), 0.00001d);
- assertEquals(0.971428d, similarity.apply(wrap("/opt/software1"), "/opt/software2"), 0.00001d);
- assertEquals(0.941666d, similarity.apply(wrap("aaabcd"), "aaacdb"), 0.00001d);
- assertEquals(0.911111d, similarity.apply(wrap("John Horn"), "John Hopkins"), 0.00001d);
- }
-
/**
* Wrap the string to a {@link CharSequence}. This ensures that using the
* {@link Object#equals(Object)} method on the input CharSequence to test for
@@ -65,15 +44,15 @@ public class JaroWinklerSimilarityTest {
*/
private static CharSequence wrap(final String string) {
return new CharSequence() {
- @Override
- public int length() {
- return string.length();
- }
@Override
public char charAt(final int index) {
return string.charAt(index);
}
@Override
+ public int length() {
+ return string.length();
+ }
+ @Override
public CharSequence subSequence(final int start, final int end) {
return string.subSequence(start, end);
}
@@ -85,14 +64,35 @@ public class JaroWinklerSimilarityTest {
assertThatIllegalArgumentException().isThrownBy(() -> similarity.apply(null, null));
}
+ @Test
+ public void testGetJaroWinklerSimilarity_NullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> similarity.apply(null, "clear"));
+ }
+
@Test
public void testGetJaroWinklerSimilarity_StringNull() {
assertThatIllegalArgumentException().isThrownBy(() -> similarity.apply(" ", null));
}
@Test
- public void testGetJaroWinklerSimilarity_NullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> similarity.apply(null, "clear"));
+ public void testGetJaroWinklerSimilarity_StringString() {
+ assertEquals(1d, similarity.apply(wrap(""), ""), 0.00001d);
+ assertEquals(1d, similarity.apply(wrap("foo"), "foo"), 0.00001d);
+ assertEquals(0.94166d, similarity.apply(wrap("foo"), "foo "), 0.00001d);
+ assertEquals(0.90666d, similarity.apply(wrap("foo"), "foo "), 0.00001d);
+ assertEquals(0.86666d, similarity.apply(wrap("foo"), " foo "), 0.00001d);
+ assertEquals(0.51111d, similarity.apply(wrap("foo"), " foo"), 0.00001d);
+ assertEquals(0.92499d, similarity.apply(wrap("frog"), "fog"), 0.00001d);
+ assertEquals(0.0d, similarity.apply(wrap("fly"), "ant"), 0.00000000000000000001d);
+ assertEquals(0.44166d, similarity.apply(wrap("elephant"), "hippo"), 0.00001d);
+ assertEquals(0.90666d, similarity.apply(wrap("ABC Corporation"), "ABC Corp"), 0.00001d);
+ assertEquals(0.95251d, similarity.apply(wrap("D N H Enterprises Inc"), "D & H Enterprises, Inc."), 0.00001d);
+ assertEquals(0.942d,
+ similarity.apply(wrap("My Gym Children's Fitness Center"), "My Gym. Childrens Fitness"), 0.00001d);
+ assertEquals(0.898018d, similarity.apply(wrap("PENNSYLVANIA"), "PENNCISYLVNIA"), 0.00001d);
+ assertEquals(0.971428d, similarity.apply(wrap("/opt/software1"), "/opt/software2"), 0.00001d);
+ assertEquals(0.941666d, similarity.apply(wrap("aaabcd"), "aaacdb"), 0.00001d);
+ assertEquals(0.911111d, similarity.apply(wrap("John Horn"), "John Hopkins"), 0.00001d);
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
index 1641cbb3..010659ef 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinDetailedDistanceTest.java
@@ -26,6 +26,98 @@ public class LevenshteinDetailedDistanceTest {
private static final LevenshteinDetailedDistance UNLIMITED_DISTANCE = new LevenshteinDetailedDistance();
+ @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 testConstructorWithNegativeThreshold() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(-1));
+ }
+
+ @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 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 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 testGetLevenshteinDetailedDistance_NullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
+ }
+
+ @Test
+ public void testGetLevenshteinDetailedDistance_NullStringInt() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
+ }
+
+ @Test
+ public void testGetLevenshteinDetailedDistance_StringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
+ }
+
+ @Test
+ public void testGetLevenshteinDetailedDistance_StringNullInt() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
+ }
+
@Test
public void testGetLevenshteinDetailedDistance_StringString() {
LevenshteinResults result = UNLIMITED_DISTANCE.apply("", "");
@@ -89,65 +181,6 @@ public class LevenshteinDetailedDistanceTest {
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() {
@@ -388,75 +421,42 @@ public class LevenshteinDetailedDistanceTest {
}
@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() {
+ public void testGetThreshold() {
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);
+ assertThat(levenshteinDetailedDistance.getThreshold()).isEqualTo(0);
}
@Test
- public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDetailedDistanceTakingInteger() {
- assertThatIllegalArgumentException().isThrownBy(() -> {
- final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0);
- final CharSequence charSequence = new TextStringBuilder();
+ 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());
- levenshteinDetailedDistance.apply(charSequence, null);
- });
- }
+ actualResult = classBeingTested.apply("frog", "fog");
+ expectedResult = new LevenshteinResults(1, 0, 1, 0);
+ assertThat(expectedResult.hashCode()).isEqualTo(actualResult.hashCode());
- @Test
- public void testApplyWithNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDetailedDistance(0).apply(null, null));
+ actualResult = classBeingTested.apply("elephant", "hippo");
+ expectedResult = new LevenshteinResults(7, 0, 3, 4);
+ assertThat(expectedResult.hashCode()).isEqualTo(actualResult.hashCode());
}
@Test
- public void testGetThreshold() {
- final LevenshteinDetailedDistance levenshteinDetailedDistance = new LevenshteinDetailedDistance(0);
+ 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());
- assertThat(levenshteinDetailedDistance.getThreshold()).isEqualTo(0);
+ 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());
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java b/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
index 86a8251d..66178060 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinDistanceTest.java
@@ -28,6 +28,36 @@ public class LevenshteinDistanceTest {
private static final LevenshteinDistance UNLIMITED_DISTANCE = new LevenshteinDistance();
+ @Test
+ public void testApplyThrowsIllegalArgumentExceptionAndCreatesLevenshteinDistanceTakingInteger() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(0).apply(null, null));
+ }
+
+ @Test
+ public void testConstructorWithNegativeThreshold() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new LevenshteinDistance(-1));
+ }
+
+ @Test
+ public void testGetLevenshteinDistance_NullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
+ }
+
+ @Test
+ public void testGetLevenshteinDistance_NullStringInt() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
+ }
+
+ @Test
+ public void testGetLevenshteinDistance_StringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply(null, "a"));
+ }
+
+ @Test
+ public void testGetLevenshteinDistance_StringNullInt() {
+ assertThatIllegalArgumentException().isThrownBy(() -> UNLIMITED_DISTANCE.apply("a", null));
+ }
+
@Test
public void testGetLevenshteinDistance_StringString() {
assertThat(UNLIMITED_DISTANCE.apply("", "")).isEqualTo(0);
@@ -42,16 +72,6 @@ public class LevenshteinDistanceTest {
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
@@ -117,26 +137,6 @@ public class LevenshteinDistanceTest {
assertThat(new LevenshteinDistance(1).apply("abc", "acb")).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
index 48363bbe..68046561 100644
--- a/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LevenshteinResultsTest.java
@@ -22,6 +22,15 @@ import org.junit.jupiter.api.Test;
public class LevenshteinResultsTest {
+ @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 testEqualsReturningFalse() {
final Integer integerOne = 1662;
@@ -34,6 +43,14 @@ public class LevenshteinResultsTest {
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();
+ }
+
@Test
public void testEqualsWithNonNull() {
final Integer integer = 1;
@@ -51,21 +68,4 @@ public class LevenshteinResultsTest {
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
index 0c53a93a..741bf587 100644
--- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceDistanceTest.java
@@ -57,13 +57,13 @@ public class LongestCommonSubsequenceDistanceTest {
}
@Test
- public void testGettingLongestCommonSubsequenceDistanceStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
+ public void testGettingLongestCommonSubsequenceDistanceNullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right"));
}
@Test
- public void testGettingLongestCommonSubsequenceDistanceNullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, "right"));
+ public void testGettingLongestCommonSubsequenceDistanceStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
index bd6824da..eb8598f6 100644
--- a/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/LongestCommonSubsequenceTest.java
@@ -35,30 +35,26 @@ public class LongestCommonSubsequenceTest {
}
@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);
+ @SuppressWarnings("deprecation")
+ public void testGettingLogestCommonSubsequenceNullNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, null));
}
@Test
- public void testGettingLongestCommonSubsequenceApplyNullNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null));
+ @SuppressWarnings("deprecation")
+ public void testGettingLogestCommonSubsequenceNullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, "right"));
}
@Test
- public void testGettingLongestCommonSubsequenceApplyStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
+ @SuppressWarnings("deprecation")
+ public void testGettingLogestCommonSubsequenceStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(" ", null));
+ }
+
+ @Test
+ public void testGettingLongestCommonSubsequenceApplyNullNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(null, null));
}
@Test
@@ -67,22 +63,8 @@ public class LongestCommonSubsequenceTest {
}
@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");
+ public void testGettingLongestCommonSubsequenceApplyStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.apply(" ", null));
}
@Test
@@ -91,13 +73,13 @@ public class LongestCommonSubsequenceTest {
}
@Test
- public void testGettingLongestCommonSubsequenceStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(" ", null));
+ public void testGettingLongestCommonSubsequenceNullString() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, "right"));
}
@Test
- public void testGettingLongestCommonSubsequenceNullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(null, "right"));
+ public void testGettingLongestCommonSubsequenceStringNull() {
+ assertThatIllegalArgumentException().isThrownBy(() -> subject.longestCommonSubsequence(" ", null));
}
@Test
@@ -121,20 +103,38 @@ public class LongestCommonSubsequenceTest {
}
@Test
- @SuppressWarnings("deprecation")
- public void testGettingLogestCommonSubsequenceNullNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, null));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void testGettingLogestCommonSubsequenceStringNull() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(" ", null));
+ 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
- @SuppressWarnings("deprecation")
- public void testGettingLogestCommonSubsequenceNullString() {
- assertThatIllegalArgumentException().isThrownBy(() -> subject.logestCommonSubsequence(null, "right"));
+ 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);
}
}
diff --git a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java b/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
index 59ad8d0a..24eac1d0 100644
--- a/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
+++ b/src/test/java/org/apache/commons/text/similarity/SimilarityScoreFromTest.java
@@ -24,11 +24,6 @@ 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();
@@ -38,4 +33,9 @@ public class SimilarityScoreFromTest {
assertThat(similarityScoreFrom.apply("s")).isEqualTo(1);
}
+ @Test
+ public void testFailsToCreateSimilarityScoreFromThrowsIllegalArgumentException() {
+ assertThatIllegalArgumentException().isThrownBy(() -> new SimilarityScoreFrom<>(null, ""));
+ }
+
}
diff --git a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
index 6bf8b209..90e1d4b4 100644
--- a/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/AggregateTranslatorTest.java
@@ -30,20 +30,6 @@ import org.junit.jupiter.api.Test;
*/
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<CharSequence, CharSequence> oneTwoMap = new HashMap<>();
@@ -63,4 +49,18 @@ public class AggregateTranslatorTest {
assertThat(out2.toString()).as("Incorrect value").isEqualTo("four");
}
+ @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);
+ }
+
}
diff --git a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java b/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
index ab7393fc..49b1db7b 100644
--- a/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
+++ b/src/test/java/org/apache/commons/text/translate/CsvTranslatorsTest.java
@@ -28,53 +28,53 @@ import org.junit.jupiter.api.Test;
public class CsvTranslatorsTest {
@Test
- public void csvEscaperPlaneTextTest() throws IOException {
+ public void csvEscaperCommaTest() 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!";
+ final String input = "hi,this,is,a,test";
escaper.translateWhole(input, writer);
final String data = writer.toString();
- assertThat(input).isEqualTo(data);
+ assertThat(data).isEqualTo("\"hi,this,is,a,test\"");
}
@Test
- public void csvEscaperCommaTest() throws IOException {
+ public void csvEscaperCRTest() throws IOException {
final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper();
final Writer writer = new StringWriter();
- final String input = "hi,this,is,a,test";
+ 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,test\"");
+ assertThat(data).isEqualTo("\"hi,this,is,a,CR,test" + String.valueOf(CharUtils.CR) + "\"");
}
@Test
- public void csvEscaperQuoteTest() throws IOException {
+ public void csvEscaperLFTest() throws IOException {
final CsvTranslators.CsvEscaper escaper = new CsvTranslators.CsvEscaper();
final Writer writer = new StringWriter();
- final String input = "hi,this,is,a,\"quote,test";
+ 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,\"\"quote,test\"");
+ assertThat(data).isEqualTo("\"hi,this,is,a,LF,test" + String.valueOf(CharUtils.LF) + "\"");
}
@Test
- public void csvEscaperCRTest() throws IOException {
+ public void csvEscaperPlaneTextTest() 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);
+ 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(data).isEqualTo("\"hi,this,is,a,CR,test" + String.valueOf(CharUtils.CR) + "\"");
+ assertThat(input).isEqualTo(data);
}
@Test
- public void csvEscaperLFTest() throws IOException {
+ public void csvEscaperQuoteTest() 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);
+ 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,LF,test" + String.valueOf(CharUtils.LF) + "\"");
+ assertThat(data).isEqualTo("\"hi,this,is,a,\"\"quote,test\"");
}
@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
index 3361e8e5..b57bd451 100644
--- a/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
+++ b/src/test/java/org/apache/commons/text/translate/EntityArraysTest.java
@@ -30,11 +30,32 @@ import org.junit.jupiter.api.Test;
*/
public class EntityArraysTest {
+ @Test
+ public void testAposMap() {
+ testEscapeVsUnescapeMaps(EntityArrays.APOS_ESCAPE, EntityArrays.APOS_UNESCAPE);
+ }
+
+ @Test
+ public void testBasicMap() {
+ testEscapeVsUnescapeMaps(EntityArrays.BASIC_ESCAPE, EntityArrays.BASIC_UNESCAPE);
+ }
+
@Test
public void testConstructorExists() {
new EntityArrays();
}
+ private void testEscapeVsUnescapeMaps(final Map<CharSequence, CharSequence> escapeMap,
+ final Map<CharSequence, CharSequence> unescapeMap) {
+ for (final CharSequence escapeKey : escapeMap.keySet()) {
+ for (final CharSequence unescapeKey : unescapeMap.keySet()) {
+ if (escapeKey == unescapeMap.get(unescapeKey)) {
+ assertThat(unescapeKey).isEqualTo(escapeMap.get(escapeKey));
+ }
+ }
+ }
+ }
+
// LANG-659, LANG-658 - avoid duplicate entries
@Test
public void testForDuplicatedDeclaredMapKeys() throws Exception {
@@ -64,14 +85,15 @@ public class EntityArraysTest {
}
@Test
- public void testForDuplicateDeclaredMapValuesISO8859Map() {
- assertThat(EntityArrays.ISO8859_1_ESCAPE.keySet()).hasSameSizeAs(
- EntityArrays.ISO8859_1_UNESCAPE.keySet());
+ public void testForDuplicateDeclaredMapValuesAposMap() {
+ assertThat(EntityArrays.APOS_ESCAPE.keySet()).hasSameSizeAs(
+ EntityArrays.APOS_UNESCAPE.keySet());
}
@Test
- public void testISO8859Map() {
- testEscapeVsUnescapeMaps(EntityArrays.ISO8859_1_ESCAPE, EntityArrays.ISO8859_1_UNESCAPE);
+ public void testForDuplicateDeclaredMapValuesBasicMap() {
+ assertThat(EntityArrays.BASIC_ESCAPE.keySet()).hasSameSizeAs(
+ EntityArrays.BASIC_UNESCAPE.keySet());
}
@Test
@@ -81,36 +103,25 @@ public class EntityArraysTest {
}
@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);
+ public void testForDuplicateDeclaredMapValuesISO8859Map() {
+ assertThat(EntityArrays.ISO8859_1_ESCAPE.keySet()).hasSameSizeAs(
+ EntityArrays.ISO8859_1_UNESCAPE.keySet());
}
@Test
- public void testForDuplicateDeclaredMapValuesBasicMap() {
- assertThat(EntityArrays.BASIC_ESCAPE.keySet()).hasSameSizeAs(
- EntityArrays.BASIC_UNESCAPE.keySet());
+ public void testForDuplicateDeclaredMapValuesJavaCtrlCharsMap() {
+ assertThat(EntityArrays.JAVA_CTRL_CHARS_ESCAPE.keySet()).hasSameSizeAs(
+ EntityArrays.JAVA_CTRL_CHARS_UNESCAPE.keySet());
}
@Test
- public void testBasicMap() {
- testEscapeVsUnescapeMaps(EntityArrays.BASIC_ESCAPE, EntityArrays.BASIC_UNESCAPE);
+ public void testHtml40ExtendedMap() {
+ testEscapeVsUnescapeMaps(EntityArrays.HTML40_EXTENDED_ESCAPE, EntityArrays.HTML40_EXTENDED_UNESCAPE);
}
@Test
- public void testForDuplicateDeclaredMapValuesJavaCtrlCharsMap() {
- assertThat(EntityArrays.JAVA_CTRL_CHARS_ESCAPE.keySet()).hasSameSizeAs(
- EntityArrays.JAVA_CTRL_CHARS_UNESCAPE.keySet());
+ public void testISO8859Map() {
+ testEscapeVsUnescapeMaps(EntityArrays.ISO8859_1_ESCAPE, EntityArrays.ISO8859_1_UNESCAPE);
}
@Test
@@ -118,15 +129,4 @@ public class EntityArraysTest {
testEscapeVsUnescapeMaps(EntityArrays.JAVA_CTRL_CHARS_ESCAPE, EntityArrays.JAVA_CTRL_CHARS_UNESCAPE);
}
- private void testEscapeVsUnescapeMaps(final Map<CharSequence, CharSequence> escapeMap,
- final Map<CharSequence, CharSequence> 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
index dfa28a42..dd6a1adb 100644
--- a/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/JavaUnicodeEscaperTest.java
@@ -25,6 +25,16 @@ import org.junit.jupiter.api.Test;
*/
public class JavaUnicodeEscaperTest {
+ @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 testBelow() {
final JavaUnicodeEscaper jue = JavaUnicodeEscaper.below('F');
@@ -45,16 +55,6 @@ public class JavaUnicodeEscaperTest {
.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() {
final JavaUnicodeEscaper jue = JavaUnicodeEscaper.below('F');
diff --git a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java b/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
index 2024f732..324146cb 100644
--- a/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
+++ b/src/test/java/org/apache/commons/text/translate/LookupTranslatorTest.java
@@ -44,6 +44,11 @@ public class LookupTranslatorTest {
assertThat(out.toString()).as("Incorrect value").isEqualTo("two");
}
+ @Test
+ public void testFailsToCreateLookupTranslatorThrowsInvalidParameterException() {
+ assertThatExceptionOfType(InvalidParameterException.class).isThrownBy(() -> new LookupTranslator(null));
+ }
+
// Tests: https://issues.apache.org/jira/browse/LANG-882
@Test
public void testLang882() throws IOException {
@@ -56,11 +61,6 @@ public class LookupTranslatorTest {
assertThat(out.toString()).as("Incorrect value").isEqualTo("two");
}
- @Test
- public void testFailsToCreateLookupTranslatorThrowsInvalidParameterException() {
- assertThatExceptionOfType(InvalidParameterException.class).isThrownBy(() -> new LookupTranslator(null));
- }
-
@Test
public void testTranslateSupplementaryCharacter() {
/* Key: string with Mathematical double-struck capital A (U+1D538) */
diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
index c3d0c5cd..51f2c49d 100644
--- a/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/NumericEntityEscaperTest.java
@@ -27,30 +27,30 @@ import org.junit.jupiter.api.Test;
public class NumericEntityEscaperTest {
@Test
- public void testBelow() {
- final NumericEntityEscaper nee = NumericEntityEscaper.below('F');
+ 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 below method").isEqualTo("ADFGZ");
+ assertThat(result).as("Failed to escape numeric entities via the above method").isEqualTo("ADFGZ");
}
@Test
- public void testBetween() {
- final NumericEntityEscaper nee = NumericEntityEscaper.between('F', 'L');
+ 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 between method").isEqualTo("ADFGZ");
+ assertThat(result).as("Failed to escape numeric entities via the below method").isEqualTo("ADFGZ");
}
@Test
- public void testAbove() {
- final NumericEntityEscaper nee = NumericEntityEscaper.above('F');
+ 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 above method").isEqualTo("ADFGZ");
+ assertThat(result).as("Failed to escape numeric entities via the between method").isEqualTo("ADFGZ");
}
// See LANG-617
diff --git a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java b/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
index 1204f885..4ce546a9 100644
--- a/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/NumericEntityUnescaperTest.java
@@ -28,13 +28,21 @@ import org.junit.jupiter.api.Test;
public class NumericEntityUnescaperTest {
@Test
- public void testSupplementaryUnescaping() {
- final NumericEntityUnescaper neu = new NumericEntityUnescaper();
- final String input = "𐰢";
- final String expected = "\uD803\uDC22";
+ public void testCreatesNumericEntityUnescaperOne() {
+ final NumericEntityUnescaper.OPTION[] numericEntityUnescaperOPTIONArray = {};
+ final NumericEntityUnescaper numericEntityUnescaper =
+ new NumericEntityUnescaper(numericEntityUnescaperOPTIONArray);
- final String result = neu.translate(input);
- assertThat(result).as("Failed to unescape numeric entities supplementary characters").isEqualTo(expected);
+ assertThat(numericEntityUnescaper.translate("2|y|O7y`&#uVWj")).isEqualTo("2|y|O7y`&#uVWj");
+ }
+
+ @Test
+ public void testCreatesNumericEntityUnescaperTwo() {
+ final NumericEntityUnescaper.OPTION[] numericEntityUnescaperOPTIONArray = {};
+ final NumericEntityUnescaper numericEntityUnescaper =
+ new NumericEntityUnescaper(numericEntityUnescaperOPTIONArray);
+
+ assertThat(numericEntityUnescaper.translate("Ws2v8|O=7NR&#cB")).isEqualTo("Ws2v8|O=7NR&#cB");
}
@Test
@@ -47,6 +55,16 @@ public class NumericEntityUnescaperTest {
assertThat(neu.translate("Test &#X")).as("Failed to ignore when last character is &").isEqualTo("Test &#X");
}
+ @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 testUnfinishedEntity() {
// parse it
@@ -77,22 +95,4 @@ public class NumericEntityUnescaperTest {
}
}
- @Test
- public void testCreatesNumericEntityUnescaperOne() {
- final NumericEntityUnescaper.OPTION[] numericEntityUnescaperOPTIONArray = {};
- 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 = {};
- 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/UnicodeEscaperTest.java b/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
index b8c75db0..b610955e 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeEscaperTest.java
@@ -26,6 +26,16 @@ import org.junit.jupiter.api.Test;
*/
public class UnicodeEscaperTest {
+ @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");
+ }
+
@Test
public void testBelow() {
final UnicodeEscaper ue = UnicodeEscaper.below('F');
@@ -45,14 +55,4 @@ public class UnicodeEscaperTest {
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
index b329c989..2e1c1216 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeUnescaperTest.java
@@ -27,6 +27,14 @@ import org.junit.jupiter.api.Test;
*/
public class UnicodeUnescaperTest {
+ @Test
+ public void testLessThanFour() {
+ final UnicodeUnescaper uu = new UnicodeUnescaper();
+
+ final String input = "\\0047\\u006";
+ assertThrows(IllegalArgumentException.class, () -> uu.translate(input));
+ }
+
// Requested in LANG-507
@Test
public void testUPlus() {
@@ -44,12 +52,4 @@ public class UnicodeUnescaperTest {
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
index 6fdfdbca..a6f53714 100644
--- a/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
+++ b/src/test/java/org/apache/commons/text/translate/UnicodeUnpairedSurrogateRemoverTest.java
@@ -31,16 +31,16 @@ public class UnicodeUnpairedSurrogateRemoverTest {
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();
+ public void testInvalidCharacters() throws IOException {
+ assertThat(subject.translate(0xd800, writer)).isTrue();
+ assertThat(subject.translate(0xdfff, writer)).isTrue();
assertThat(writer.size()).isZero();
}
@Test
- public void testInvalidCharacters() throws IOException {
- assertThat(subject.translate(0xd800, writer)).isTrue();
- assertThat(subject.translate(0xdfff, writer)).isTrue();
+ public void testValidCharacters() throws IOException {
+ assertThat(subject.translate(0xd7ff, writer)).isFalse();
+ assertThat(subject.translate(0xe000, writer)).isFalse();
assertThat(writer.size()).isZero();
}
}