Skip to content

Commit 1ae6b6b

Browse files
kluevercopybara-github
authored andcommitted
Validate Duration instances produced by the static factories.
PiperOrigin-RevId: 792163897
1 parent 3315083 commit 1ae6b6b

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

java/util/src/main/java/com/google/protobuf/util/Durations.java

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -301,28 +301,19 @@ public static Duration parseUnchecked(@CompileTimeConstant String value) {
301301
/** Create a Duration from the number of days. */
302302
@SuppressWarnings("GoodTime") // this is a legacy conversion API
303303
public static Duration fromDays(long days) {
304-
return Duration.newBuilder()
305-
.setSeconds(multiplyExact(days, SECONDS_PER_DAY))
306-
.setNanos(0)
307-
.build();
304+
return Durations.fromSeconds(multiplyExact(days, SECONDS_PER_DAY));
308305
}
309306

310307
/** Create a Duration from the number of hours. */
311308
@SuppressWarnings("GoodTime") // this is a legacy conversion API
312309
public static Duration fromHours(long hours) {
313-
return Duration.newBuilder()
314-
.setSeconds(multiplyExact(hours, SECONDS_PER_HOUR))
315-
.setNanos(0)
316-
.build();
310+
return Durations.fromSeconds(multiplyExact(hours, SECONDS_PER_HOUR));
317311
}
318312

319313
/** Create a Duration from the number of minutes. */
320314
@SuppressWarnings("GoodTime") // this is a legacy conversion API
321315
public static Duration fromMinutes(long minutes) {
322-
return Duration.newBuilder()
323-
.setSeconds(multiplyExact(minutes, SECONDS_PER_MINUTE))
324-
.setNanos(0)
325-
.build();
316+
return Durations.fromSeconds(multiplyExact(minutes, SECONDS_PER_MINUTE));
326317
}
327318

328319
/** Create a Duration from the number of seconds. */

java/util/src/test/java/com/google/protobuf/util/DurationsTest.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,18 @@ public void testStaticFactories() {
146146

147147
@Test
148148
public void testLargeDuration() {
149-
// TODO: kak - this should throw an exception
150-
assertThat(Durations.isValid(Durations.fromHours(Integer.MAX_VALUE))).isFalse();
149+
try {
150+
Durations.fromHours(Integer.MAX_VALUE);
151+
fail();
152+
} catch (IllegalArgumentException expected) {
153+
assertThat(expected)
154+
.hasMessageThat()
155+
.isEqualTo(
156+
"Duration is not valid. See proto definition for valid values. Seconds"
157+
+ " (7730941129200) must be in range [-315,576,000,000, +315,576,000,000]. Nanos"
158+
+ " (0) must be in range [-999,999,999, +999,999,999]. Nanos must have the same"
159+
+ " sign as seconds");
160+
}
151161
}
152162

153163
@Test

0 commit comments

Comments
 (0)