Skip to content

Commit

Permalink
Fix division-by-zero error in Persistence average (openhab#3556)
Browse files Browse the repository at this point in the history
* Fix division-by-zero error in Persistence average
* Add test

Signed-off-by: Jimmy Tanagra <jcode@tanagra.id.au>
GitOrigin-RevId: 7a9b76d
  • Loading branch information
jimtng authored and splatch committed Jul 12, 2023
1 parent 2947189 commit 6aaaef7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -824,7 +824,8 @@ public static boolean updatedBetween(Item item, ZonedDateTime begin, ZonedDateTi

if (firstTimestamp != null) {
BigDecimal totalDuration = BigDecimal.valueOf(Duration.between(firstTimestamp, endTime).toMillis());
return new DecimalType(sum.divide(totalDuration, MathContext.DECIMAL64));
return totalDuration.signum() == 0 ? null
: new DecimalType(sum.divide(totalDuration, MathContext.DECIMAL64));
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.closeTo;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
Expand Down Expand Up @@ -680,6 +681,15 @@ public void testAverageSinceSwitch() {
assertThat(average, is(nullValue()));
}

@Test
public void testAverageBetweenZeroDuration() {
ZonedDateTime now = ZonedDateTime.now();
assertDoesNotThrow(
() -> PersistenceExtensions.averageBetween(quantityItem, now, now, TestPersistenceService.ID));
assertThat(PersistenceExtensions.averageBetween(quantityItem, now, now, TestPersistenceService.ID),
is(nullValue()));
}

@Test
public void testSumSinceDecimalType() {
DecimalType sum = PersistenceExtensions.sumSince(numberItem,
Expand Down

0 comments on commit 6aaaef7

Please sign in to comment.