Fix division-by-zero error in Persistence average (#3556)

* Fix division-by-zero error in Persistence average
* Add test

Signed-off-by: Jimmy Tanagra <jcode@tanagra.id.au>
This commit is contained in:
jimtng
2023-04-15 16:03:45 +02:00
committed by GitHub
parent 9e334497f9
commit 7a9b76dfdf
2 changed files with 12 additions and 1 deletions
@@ -824,7 +824,8 @@ public class PersistenceExtensions {
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;
@@ -18,6 +18,7 @@ import static org.hamcrest.CoreMatchers.notNullValue;
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;
@@ -680,6 +681,15 @@ public class PersistenceExtensionsTest {
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,