Skip to content

Commit

Permalink
Merge pull request #33669 from Seungpang
Browse files Browse the repository at this point in the history
* pr/33669:
  Polish "Reject empty strings in DurationFormatterUtils"
  Reject empty strings in DurationFormatterUtils

Closes gh-33669
  • Loading branch information
snicoll committed Oct 9, 2024
2 parents 7f7f65c + e2238c0 commit f54faba
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public static Duration parse(String value, DurationFormat.Style style) {
* @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);
Expand Down Expand Up @@ -149,7 +150,7 @@ private static Duration parseIso8601(String value) {
try {
return Duration.parse(value);
}
catch (Throwable ex) {
catch (Exception ex) {
throw new IllegalArgumentException("'" + value + "' is not a valid ISO-8601 duration", ex);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@

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;
Expand All @@ -38,6 +41,22 @@
*/
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);
Expand Down

0 comments on commit f54faba

Please sign in to comment.