This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit c54ceb95058b6bbe41173756da0a64da07023a7d Author: Gary Gregory <[email protected]> AuthorDate: Sun Nov 15 09:25:11 2026 -0500 Complete Fraction test coverage Add tests for integer-string parsing, negation overflow, GCD boundaries, and double-conversion limits. Preserve existing underflow and overflow coverage, remove redundant iteration guards, and update Javadoc and changes.xml. Achieve 100% instruction, line, branch, and method coverage. Verify unchanged conversion results across 31.9 million inputs and pass the full Maven build. Assisted-By: OpenAI Codex --- src/changes/changes.xml | 1 + .../org/apache/commons/lang3/math/Fraction.java | 22 ++- .../apache/commons/lang3/math/FractionTest.java | 180 +++++++++++++++++---- 3 files changed, 156 insertions(+), 47 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 58e512187..a2810c813 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -62,6 +62,7 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory">Parameterize Fraction factory and unary-operation tests while preserving expected representations, invalid inputs, and reduction identity checks.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Improve Fraction double-conversion test diagnostics and verify preserved ArithmeticException causes for all six unrepresentable-string regression cases.</action> <action type="fix" dev="ggregory" due-to="Gary Gregory">Fix premature overflow in Fraction.getFraction(double) and decimal-string parsing for representable Integer.MIN_VALUE numerators, with boundary tests for every denominator from 1 through 10,000.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Complete Fraction coverage for integer-string parsing, negation overflow, GCD boundaries, and double-conversion limits; remove redundant iteration guards.</action> <!-- ADD --> <!-- UPDATE --> </release> diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java b/src/main/java/org/apache/commons/lang3/math/Fraction.java index 9b82b93fa..0ee42c6ab 100644 --- a/src/main/java/org/apache/commons/lang3/math/Fraction.java +++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java @@ -121,7 +121,7 @@ private static void checkDenominator(final int denominator) { * * <p> * This method uses the <a href="https://web.archive.org/web/20210516065058/http%3A//archives.math.utk.edu/articles/atuyl/confrac/"> continued fraction - * algorithm</a>, computing a maximum of 25 convergents and bounding the denominator by 10,000. + * algorithm</a>, bounding the denominator by 10,000 and stopping when the approximation no longer improves. * </p> * * @param value The double value to convert @@ -129,7 +129,6 @@ private static void checkDenominator(final int denominator) { * @throws ArithmeticException Thrown if {@code |value| > Integer.MAX_VALUE} or {@code value = NaN}. * @throws ArithmeticException Thrown if the calculated numerator cannot be represented as an {@code int}. * @throws ArithmeticException Thrown if the calculated denominator is {@code zero}. - * @throws ArithmeticException Thrown if the algorithm does not converge. */ public static Fraction getFraction(double value) { final int sign = value < 0 ? -1 : 1; @@ -154,7 +153,8 @@ public static Fraction getFraction(double value) { double delta1; double delta2 = Double.MAX_VALUE; double fraction; - int i = 1; + // Positive convergent denominators grow at least as fast as Fibonacci numbers, + // so the denominator bound also bounds the number of iterations. do { delta1 = delta2; a2 = (int) (x1 / y1); @@ -171,11 +171,7 @@ public static Fraction getFraction(double value) { denom0 = denom1; numer1 = numer2; denom1 = denom2; - i++; - } while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25); - if (i == 25) { - throw new ArithmeticException("Unable to convert double to fraction"); - } + } while (denom2 > 0 && denom2 <= 10000 && delta1 > delta2); // Use long arithmetic and apply the sign before narrowing so that Integer.MIN_VALUE remains representable. final long numerator = (numer0 + (long) wholeNumber * denom0) * sign; return getReducedFraction(Math.toIntExact(numerator), denom0); @@ -355,9 +351,10 @@ public static Fraction getReducedFraction(int numerator, int denominator) { * division and modulo operations. See Knuth 4.5.2 algorithm B. * This algorithm is due to Josef Stein (1961). * - * @param u A non-zero number - * @param v A non-zero number - * @return The greatest common divisor, never zero + * @param u A number + * @param v A number + * @return The non-negative greatest common divisor, or zero if both arguments are zero. + * @throws ArithmeticException Thrown if the greatest common divisor cannot be represented as an {@code int}. */ private static int greatestCommonDivisor(int u, int v) { // From Commons Math: @@ -383,7 +380,8 @@ private static int greatestCommonDivisor(int u, int v) { } // make v negative // B1. [Find power of 2] int k = 0; - while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are both even... + // Non-zero ints become odd after at most 31 halvings, so no separate iteration bound is needed. + while ((u & 1) == 0 && (v & 1) == 0) { // while u and v are both even... u /= 2; v /= 2; k++; // cast out twos. diff --git a/src/test/java/org/apache/commons/lang3/math/FractionTest.java b/src/test/java/org/apache/commons/lang3/math/FractionTest.java index abfdfca46..172a8a14a 100644 --- a/src/test/java/org/apache/commons/lang3/math/FractionTest.java +++ b/src/test/java/org/apache/commons/lang3/math/FractionTest.java @@ -27,6 +27,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; @@ -108,6 +110,34 @@ private static LongStream factoryDoubleBoundaryValues() { return LongStream.of(numerators); } + private static Stream<Arguments> factoryDoubleConvergentValues() { + // The golden ratio's fractional part has the slowest denominator growth: successive Fibonacci numbers. + final double goldenRatioFractionalPart = (Math.sqrt(5) - 1) / 2; + return Stream.of( + Arguments.of(Math.nextDown(0.0d), 0, 1), + Arguments.of(0.0d, 0, 1), + Arguments.of(Math.nextUp(0.0d), 0, 1), + Arguments.of(Math.nextDown(Double.MIN_NORMAL), 0, 1), + Arguments.of(Double.MIN_NORMAL, 0, 1), + Arguments.of(Math.nextUp(Double.MIN_NORMAL), 0, 1), + Arguments.of(Math.nextDown(0.5d), 1, 2), + Arguments.of(0.5d, 1, 2), + Arguments.of(Math.nextUp(0.5d), 1, 2), + Arguments.of(Math.nextDown(1.0d / 10000), 1, 10000), + Arguments.of(1.0d / 10000, 1, 10000), + Arguments.of(Math.nextUp(1.0d / 10000), 1, 10000), + Arguments.of(Math.nextDown(1.0d / 10001), 0, 1), + Arguments.of(1.0d / 10001, 0, 1), + Arguments.of(Math.nextUp(1.0d / 10001), 1, 10000), + // The next denominator overflows to zero or a small signed value; retain the previous convergent. + Arguments.of(Math.nextDown(1431655766d / 4294967299L), 1, 3), + Arguments.of(1431655766d / 4294967299L, 1, 3), + Arguments.of(Math.nextUp(1431655766d / 4294967299L), 1, 3), + Arguments.of(Math.nextDown(goldenRatioFractionalPart), 4181, 6765), + Arguments.of(goldenRatioFractionalPart, 4181, 6765), + Arguments.of(Math.nextUp(goldenRatioFractionalPart), 4181, 6765)); + } + private static Stream<Arguments> factoryDoubleValues() { return Stream.of( Arguments.of(0.0d, 0, 1), @@ -656,11 +686,16 @@ void testFactory_doubleAndStringBoundaryValues(final long numerator) { } } - @ParameterizedTest(name = "[{index}] getFraction({0}) throws") - @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, (double) Integer.MAX_VALUE + 1, 2147483646.5d, 1073741824.5d}) - void testFactory_doubleInvalid(final double value) { - // The fractional boundary values must throw instead of overflowing the numerator to a negative value. - assertThrows(ArithmeticException.class, () -> Fraction.getFraction(value)); + @ParameterizedTest(name = "[{index}] convergents near {0}") + @MethodSource("factoryDoubleConvergentValues") + void testFactory_doubleConvergents(final double value, final int expectedNumerator, final int expectedDenominator) { + for (final int sign : new int[] {-1, 1}) { + final double input = sign * value; + final String message = "getFraction(" + Double.toHexString(input) + ")"; + final Fraction result = assertDoesNotThrow(() -> Fraction.getFraction(input), message); + assertEquals(sign * expectedNumerator, result.getNumerator(), message); + assertEquals(expectedDenominator, result.getDenominator(), message); + } } @ParameterizedTest(name = "[{index}] getFraction(-2147483648/{0})") @@ -671,6 +706,13 @@ void testFactory_doubleIntegerMinValue(final int denominator) { assertEquals(denominator, result.getDenominator()); } + @ParameterizedTest(name = "[{index}] getFraction({0}) throws") + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, (double) Integer.MAX_VALUE + 1, 2147483646.5d, 1073741824.5d}) + void testFactory_doubleInvalid(final double value) { + // The fractional boundary values must throw instead of overflowing the numerator to a negative value. + assertThrows(ArithmeticException.class, () -> Fraction.getFraction(value)); + } + @Test void testFactory_doubleRoundTrip() { Fraction f; @@ -709,7 +751,9 @@ void testFactory_doubleRoundTrip() { "22, 7, 22, 7", "-6, 10, -6, 10", "6, -10, -6, 10", - "-6, -10, 6, 10" + "-6, -10, 6, 10", + "-2147483648, 1, -2147483648, 1", + "-2147483647, -1, 2147483647, 1" }) void testFactory_int_int(final int numerator, final int denominator, final int expectedNumerator, final int expectedDenominator) { final Fraction result = Fraction.getFraction(numerator, denominator); @@ -717,18 +761,6 @@ void testFactory_int_int(final int numerator, final int denominator, final int e assertEquals(expectedDenominator, result.getDenominator()); } - @ParameterizedTest(name = "[{index}] getFraction({0}, {1}) throws") - @CsvSource({ - "1, 0", - "2, 0", - "-3, 0", - "4, -2147483648", - "1, -2147483648" - }) - void testFactory_int_intInvalid(final int numerator, final int denominator) { - assertThrows(ArithmeticException.class, () -> Fraction.getFraction(numerator, denominator)); - } - @ParameterizedTest(name = "[{index}] getFraction({0}, {1}, {2})") @CsvSource({ "0, 0, 2, 0, 2", @@ -763,6 +795,21 @@ void testFactory_int_int_intInvalid(final int whole, final int numerator, final assertThrows(ArithmeticException.class, () -> Fraction.getFraction(whole, numerator, denominator)); } + @ParameterizedTest(name = "[{index}] getFraction({0}, {1}) throws") + @CsvSource({ + "1, 0", + "2, 0", + "-3, 0", + "4, -2147483648", + "1, -2147483648", + "-2147483648, -1", + "-2147483648, -2", + "-2147483648, -2147483648" + }) + void testFactory_int_intInvalid(final int numerator, final int denominator) { + assertThrows(ArithmeticException.class, () -> Fraction.getFraction(numerator, denominator)); + } + @Test void testFactory_String() { assertNullPointerException(() -> Fraction.getFraction(null)); @@ -782,7 +829,7 @@ void testFactory_String_double(final String value, final int expectedNumerator, } @ParameterizedTest(name = "[{index}] getFraction({0}) throws") - @ValueSource(strings = {"2.3R", "2147483648", "."}) + @ValueSource(strings = {"2.3R", "."}) void testFactory_String_doubleInvalid(final String value) { assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value)); } @@ -808,6 +855,28 @@ void testFactory_String_improperInvalid(final String value) { assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value)); } + @ParameterizedTest(name = "[{index}] getFraction({0})") + @CsvSource({ + "'0', 0", + "'-0', 0", + "'1', 1", + "'+1', 1", + "'-1', -1", + "'2147483647', 2147483647", + "'-2147483648', -2147483648" + }) + void testFactory_String_integer(final String value, final int expectedNumerator) { + final Fraction result = Fraction.getFraction(value); + assertEquals(expectedNumerator, result.getNumerator()); + assertEquals(1, result.getDenominator()); + } + + @ParameterizedTest(name = "[{index}] getFraction({0}) throws") + @ValueSource(strings = {"2147483648", "-2147483649", "", "+", "-", "1e3"}) + void testFactory_String_integerInvalid(final String value) { + assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value)); + } + @ParameterizedTest(name = "[{index}] getFraction({0})") @CsvSource({ "'0 0/1', 0, 1", @@ -872,6 +941,47 @@ void testGets() { assertEquals(1, f.getDenominator()); } + @ParameterizedTest(name = "[{index}] gcd({0}, {1})") + @CsvSource({ + "0, 0", + "0, 6", + "0, -6", + "6, 0", + "-6, 0", + "0, 2147483647", + "2147483647, 0", + "-6, -10", + "6, -10", + "-6, 10", + "1, -2147483648", + "-2147483648, -1", + "-2147483648, -2", + "-2147483648, -1073741824", + "1073741824, -1073741824", + "2147483647, -2147483647", + "-2147483648, 2147483647" + }) + void testGreatestCommonDivisor(final int left, final int right) throws ReflectiveOperationException { + // Public fraction operations exclude some inputs supported by this defensive helper. + final Method method = Fraction.class.getDeclaredMethod("greatestCommonDivisor", int.class, int.class); + method.setAccessible(true); + final int expected = BigInteger.valueOf(left).gcd(BigInteger.valueOf(right)).intValueExact(); + assertEquals(expected, method.invoke(null, left, right)); + } + + @ParameterizedTest(name = "[{index}] gcd({0}, {1}) overflows") + @CsvSource({ + "-2147483648, 0", + "0, -2147483648", + "-2147483648, -2147483648" + }) + void testGreatestCommonDivisorOverflow(final int left, final int right) throws ReflectiveOperationException { + final Method method = Fraction.class.getDeclaredMethod("greatestCommonDivisor", int.class, int.class); + method.setAccessible(true); + final InvocationTargetException exception = assertThrows(InvocationTargetException.class, () -> method.invoke(null, left, right)); + assertInstanceOf(ArithmeticException.class, exception.getCause()); + } + @Test void testHashCode() { final Fraction f1 = Fraction.getFraction(3, 5); @@ -1252,22 +1362,6 @@ void testReduce(final int numerator, final int denominator, final int expectedNu assertEquals(expectedDenominator, result.getDenominator()); } - @ParameterizedTest(name = "[{index}] reduce({0}/{1}) preserves identity") - @CsvSource({ - "-2, 3", - "2, 3", - "0, 1" - }) - void testReduceIdentity(final int numerator, final int denominator) { - final Fraction fraction = Fraction.getFraction(numerator, denominator); - assertSame(fraction, fraction.reduce()); - } - - @Test - void testReduceZero() { - assertSame(Fraction.ZERO, Fraction.getFraction(0, 100).reduce()); - } - @ParameterizedTest(name = "[{index}] getReducedFraction({0}, {1})") @CsvSource({ "0, 1, 0, 1", @@ -1325,6 +1419,22 @@ void testReducedFactoryIntegerMinValueInvalid(final int numerator, final int den assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(numerator, denominator)); } + @ParameterizedTest(name = "[{index}] reduce({0}/{1}) preserves identity") + @CsvSource({ + "-2, 3", + "2, 3", + "0, 1" + }) + void testReduceIdentity(final int numerator, final int denominator) { + final Fraction fraction = Fraction.getFraction(numerator, denominator); + assertSame(fraction, fraction.reduce()); + } + + @Test + void testReduceZero() { + assertSame(Fraction.ZERO, Fraction.getFraction(0, 100).reduce()); + } + @Test void testSubtract() { Fraction f;
