Merge pull request #33669 from Seungpang

* pr/33669:
  Polish "Reject empty strings in DurationFormatterUtils"
  Reject empty strings in DurationFormatterUtils

Closes gh-33669
This commit is contained in:
Stéphane Nicoll
2024-10-09 15:27:58 +02:00
2 changed files with 21 additions and 1 deletions

View File

@@ -62,6 +62,7 @@ public abstract class DurationFormatterUtils {
* @return a duration
*/
public static Duration parse(String value, DurationFormat.Style style, @Nullable DurationFormat.Unit unit) {
Assert.hasText(value, () -> "Value must not be empty");
return switch (style) {
case ISO8601 -> parseIso8601(value);
case SIMPLE -> parseSimple(value, unit);
@@ -149,7 +150,7 @@ public abstract class DurationFormatterUtils {
try {
return Duration.parse(value);
}
catch (Throwable ex) {
catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
}
}

View File

@@ -23,7 +23,10 @@ import java.util.Arrays;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.format.annotation.DurationFormat;
import org.springframework.format.annotation.DurationFormat.Unit;
import static org.assertj.core.api.Assertions.assertThat;
@@ -38,6 +41,22 @@ import static org.springframework.format.annotation.DurationFormat.Style.SIMPLE;
*/
class DurationFormatterUtilsTests {
@ParameterizedTest
@EnumSource(DurationFormat.Style.class)
void parseEmptyStringFailsWithDedicatedException(DurationFormat.Style style) {
assertThatIllegalArgumentException()
.isThrownBy(() -> DurationFormatterUtils.parse("", style))
.withMessage("Value must not be empty");
}
@ParameterizedTest
@EnumSource(DurationFormat.Style.class)
void parseNullStringFailsWithDedicatedException(DurationFormat.Style style) {
assertThatIllegalArgumentException()
.isThrownBy(() -> DurationFormatterUtils.parse(null, style))
.withMessage("Value must not be empty");
}
@Test
void parseSimpleWithUnits() {
Duration nanos = DurationFormatterUtils.parse("1ns", SIMPLE, Unit.SECONDS);