diff --git a/application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java b/application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java index 5e3c03931c..cc3a132993 100644 --- a/application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java +++ b/application/src/main/java/org/thingsboard/server/utils/CalculatedFieldUtils.java @@ -263,10 +263,10 @@ public class CalculatedFieldUtils { proto.getSingleValueArgumentsList().forEach(argProto -> state.getArguments().put(argProto.getArgName(), fromSingleValueArgumentProto(argProto))); + proto.getRollingValueArgumentsList().forEach(argProto -> + state.getArguments().put(argProto.getKey(), fromRollingArgumentProto(argProto))); switch (type) { - case SCRIPT -> proto.getRollingValueArgumentsList().forEach(argProto -> - state.getArguments().put(argProto.getKey(), fromRollingArgumentProto(argProto))); case GEOFENCING -> proto.getGeofencingArgumentsList().forEach(argProto -> state.getArguments().put(argProto.getArgName(), fromGeofencingArgumentProto(argProto))); case PROPAGATION -> { diff --git a/application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java index b0188fc21f..7495b90404 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/AbstractNotificationApiTest.java @@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.notification.rule.DefaultNotificationR import org.thingsboard.server.common.data.notification.rule.NotificationRule; import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerConfig; +import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType; import org.thingsboard.server.common.data.notification.settings.NotificationDeliveryMethodConfig; import org.thingsboard.server.common.data.notification.settings.NotificationSettings; import org.thingsboard.server.common.data.notification.template.NotificationTemplate; @@ -43,14 +44,17 @@ import org.thingsboard.server.dao.notification.NotificationTargetService; import org.thingsboard.server.dao.notification.NotificationTemplateService; import org.thingsboard.server.dao.secret.SecretService; import org.thingsboard.server.dao.sqlts.insert.sql.SqlPartitioningRepository; +import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; public abstract class AbstractNotificationApiTest extends AbstractControllerTest { @@ -64,6 +68,8 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest @Autowired protected NotificationRuleService notificationRuleService; @Autowired + protected DefaultNotificationRulesCache notificationRulesCache; + @Autowired protected NotificationTemplateService notificationTemplateService; @Autowired protected NotificationTargetService notificationTargetService; @@ -192,7 +198,16 @@ public abstract class AbstractNotificationApiTest extends AbstractControllerTest } protected NotificationRule saveNotificationRule(NotificationRule notificationRule) { - return doPost("/api/notification/rule", notificationRule, NotificationRule.class); + NotificationRule savedRule = doPost("/api/notification/rule", notificationRule, NotificationRule.class); + awaitNotificationRulesCacheUpdate(savedRule.getTenantId(), savedRule.getTriggerType()); + return savedRule; + } + + // saving a rule evicts the rules cache asynchronously + protected void awaitNotificationRulesCacheUpdate(TenantId tenantId, NotificationRuleTriggerType triggerType) { + await().atMost(TIMEOUT, TimeUnit.SECONDS).pollInterval(10, TimeUnit.MILLISECONDS) + .until(() -> Set.copyOf(notificationRulesCache.getEnabled(tenantId, triggerType)) + .equals(Set.copyOf(notificationRuleService.findEnabledNotificationRulesByTenantIdAndTriggerType(tenantId, triggerType)))); } protected PageData findNotificationRules() throws Exception { diff --git a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java index c42f8f634e..93bf08af0a 100644 --- a/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java +++ b/application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java @@ -13,6 +13,7 @@ import org.mockito.MockedStatic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.data.util.Pair; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.context.TestPropertySource; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.SystemUtil; @@ -54,6 +55,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestInfo; import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.notification.info.AlarmNotificationInfo; import org.thingsboard.server.common.data.notification.info.RateLimitsNotificationInfo; +import org.thingsboard.server.common.data.notification.info.ResourcesShortageNotificationInfo; import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig; import org.thingsboard.server.common.data.notification.rule.EscalatedNotificationRuleRecipientsConfig; import org.thingsboard.server.common.data.notification.rule.NotificationRule; @@ -89,12 +91,10 @@ import org.thingsboard.server.dao.notification.NotificationRequestService; import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.queue.notification.DefaultNotificationDeduplicationService; -import org.thingsboard.server.service.notification.rule.cache.DefaultNotificationRulesCache; import org.thingsboard.server.service.state.DeviceStateService; import org.thingsboard.server.service.system.DefaultSystemInfoService; import org.thingsboard.server.service.telemetry.AlarmSubscriptionService; -import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -122,7 +122,9 @@ import static org.thingsboard.server.common.data.notification.rule.trigger.confi @TestPropertySource(properties = { "transport.http.enabled=true", "notification_system.rules.deduplication_durations=RATE_LIMITS:10000", - "edges.enabled=true" + "edges.enabled=true", + // the real system info job reports resource shortages only once, at startup + "metrics.system_info.persist_frequency=3600" }) public class NotificationRuleApiTest extends AbstractNotificationApiTest { @@ -139,8 +141,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { @Autowired private NotificationRuleProcessor notificationRuleProcessor; @Autowired - private DefaultNotificationRulesCache notificationRulesCache; - @Autowired private DeviceStateService deviceStateService; @Before @@ -271,7 +271,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { Device device = createDevice("Device with alarm", "233"); NotificationTarget target = createNotificationTarget(tenantAdminUserId); defaultNotifications.create(tenantId, DefaultNotifications.newAlarm, target.getId()); - notificationRulesCache.evict(tenantId); + awaitNotificationRulesCacheUpdate(tenantId, NotificationRuleTriggerType.ALARM); Alarm alarm = new Alarm(); alarm.setSeverity(AlarmSeverity.CRITICAL); @@ -448,7 +448,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimitsForSysadmin, sysadmins.getId()); defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededRateLimits, affectedTenantAdmins.getId()); defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.exceededPerEntityRateLimits, affectedTenantAdmins.getId()); - notificationRulesCache.evict(TenantId.SYS_TENANT_ID); + awaitNotificationRulesCacheUpdate(TenantId.SYS_TENANT_ID, NotificationRuleTriggerType.RATE_LIMITS); int n = 10; updateDefaultTenantProfileConfig(profileConfiguration -> { @@ -787,14 +787,8 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", createNotificationTarget(tenantAdminUserId).getId()); loginTenantAdmin(); - // Mock SystemUtil to return 15% memory usage (exceeds 1% threshold) - try (MockedStatic mockedSystemUtil = mockStatic(SystemUtil.class)) { - mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15)); - - Method method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo"); - method.setAccessible(true); - method.invoke(systemInfoService); - } + // 15% RAM exceeds the 1% threshold, CPU and storage stay below 100% + saveMonolithSystemInfo(15); await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1); Notification notification = getMyNotifications(false, 100).get(0); @@ -813,29 +807,32 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { .build(); createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId()); - assertThat(getMyNotifications(false, 100)).size().isZero(); + // the real system info job reports RAM under this node's service id, so count only this test's + String serviceId = "test-service-" + UUID.randomUUID(); for (int i = 0; i < 10; i++) { notificationRuleProcessor.process(ResourcesShortageTrigger.builder() .resource(Resource.RAM) .usage(15L) .serviceType("serviceType") - .serviceId("serviceId") + .serviceId(serviceId) .build()); TimeUnit.MILLISECONDS.sleep(300); } - await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1); - Notification notification = getMyNotifications(false, 100).get(0); + List notifications = await().atMost(TIMEOUT, TimeUnit.SECONDS) + .until(() -> getResourcesShortageNotifications(serviceId), list -> list.size() == 1); + Notification notification = notifications.get(0); assertThat(notification.getSubject()).isEqualTo("Warning: RAM shortage"); assertThat(notification.getText()).isEqualTo("RAM shortage"); - // deduplication is 1 minute, no new message is exp + // deduplication is 1 hour, no new message is expected notificationRuleProcessor.process(ResourcesShortageTrigger.builder() .resource(Resource.RAM) .usage(5L) .serviceType("serviceType") - .serviceId("serviceId") + .serviceId(serviceId) .build()); - await("").atMost(TIMEOUT, TimeUnit.SECONDS).untilAsserted(() -> assertThat(getMyNotifications(false, 100)).size().isOne()); + await().during(3, TimeUnit.SECONDS).atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> assertThat(getResourcesShortageNotifications(serviceId)).hasSize(1)); } @Test @@ -850,16 +847,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { NotificationRule rule = createNotificationRule(triggerConfig, "Warning: ${resource} shortage", "${resource} shortage", sysadmins.getId()); // Mock SystemUtil to return 15% usages (not exceeds 99% threshold) - Method method; - try (MockedStatic mockedSystemUtil = mockStatic(SystemUtil.class)) { - mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(15)); - mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(15)); - mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(15)); - - method = DefaultSystemInfoService.class.getDeclaredMethod("saveCurrentMonolithSystemInfo"); - method.setAccessible(true); - method.invoke(systemInfoService); - } + saveMonolithSystemInfo(15); TimeUnit.SECONDS.sleep(5); assertThat(getMyNotifications(false, 100)).size().isZero(); @@ -872,7 +860,7 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { rule.setTriggerConfig(triggerConfig); saveNotificationRule(rule); - method.invoke(systemInfoService); + saveMonolithSystemInfo(15); await().atMost(TIMEOUT, TimeUnit.SECONDS).until(() -> getMyNotifications(false, 100).size() == 1); Notification notification = getMyNotifications(false, 100).get(0); @@ -886,7 +874,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE)); triggerConfig.setCreated(true); NotificationRule rule = createNotificationRule(triggerConfig, "Created", "Created", createNotificationTarget(tenantAdminUserId).getId()); - notificationRulesCache.evict(tenantId); assertThat(getMyNotifications(false, 100)).size().isZero(); createDevice("Device 1", "default", "111"); @@ -897,7 +884,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { rule.setEnabled(false); saveNotificationRule(rule); - notificationRulesCache.evict(tenantId); createDevice("Device 2", "default", "222"); TimeUnit.SECONDS.sleep(5); @@ -905,7 +891,6 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { rule.setEnabled(true); saveNotificationRule(rule); - notificationRulesCache.evict(tenantId); createDevice("Device 3", "default", "333"); await().atMost(TIMEOUT, TimeUnit.SECONDS) @@ -936,6 +921,22 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest { }, (notification, r) -> check.accept(notification)); } + private void saveMonolithSystemInfo(int usagePercent) { + try (MockedStatic mockedSystemUtil = mockStatic(SystemUtil.class)) { + mockedSystemUtil.when(SystemUtil::getMemoryUsage).thenReturn(Optional.of(usagePercent)); + mockedSystemUtil.when(SystemUtil::getCpuUsage).thenReturn(Optional.of(usagePercent)); + mockedSystemUtil.when(SystemUtil::getDiscSpaceUsage).thenReturn(Optional.of(usagePercent)); + ReflectionTestUtils.invokeMethod(systemInfoService, "saveCurrentMonolithSystemInfo"); + } + } + + private List getResourcesShortageNotifications(String serviceId) throws Exception { + return getMyNotifications(false, 100).stream() + .filter(notification -> notification.getInfo() instanceof ResourcesShortageNotificationInfo info + && serviceId.equals(info.getServiceId())) + .toList(); + } + private PageData findNotificationRequests(EntityType originatorType) { return notificationRequestService.findNotificationRequestsInfosByTenantIdAndOriginatorType(tenantId, originatorType, new PageLink(100)); } diff --git a/application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java b/application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java index dd0283ebcc..059d7b8d31 100644 --- a/application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java +++ b/application/src/test/java/org/thingsboard/server/utils/CalculatedFieldUtilsTest.java @@ -4,7 +4,10 @@ package org.thingsboard.server.utils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingPresenceStatus; import org.thingsboard.server.common.data.id.AssetId; import org.thingsboard.server.common.data.id.CalculatedFieldId; @@ -19,7 +22,9 @@ import org.thingsboard.server.service.cf.ctx.CalculatedFieldEntityCtxId; import org.thingsboard.server.service.cf.ctx.state.ArgumentEntry; import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldCtx; import org.thingsboard.server.service.cf.ctx.state.CalculatedFieldState; +import org.thingsboard.server.service.cf.ctx.state.ScriptCalculatedFieldState; import org.thingsboard.server.service.cf.ctx.state.SingleValueArgumentEntry; +import org.thingsboard.server.service.cf.ctx.state.TsRollingArgumentEntry; import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingArgumentEntry; import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingCalculatedFieldState; import org.thingsboard.server.service.cf.ctx.state.geofencing.GeofencingZoneState; @@ -29,6 +34,7 @@ import org.thingsboard.server.service.cf.ctx.state.propagation.PropagationCalcul import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.TreeMap; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -151,4 +157,35 @@ class CalculatedFieldUtilsTest { assertThat(propagationState.getReadinessStatus()).isNull(); } + @ParameterizedTest + @EnumSource(value = CalculatedFieldType.class, names = {"SCRIPT", "PROPAGATION"}) + void toProtoAndFromProto_shouldRestoreTsRollingArgument(CalculatedFieldType type) { + // given + CalculatedFieldEntityCtxId stateId = mock(CalculatedFieldEntityCtxId.class); + given(stateId.tenantId()).willReturn(TENANT_ID); + given(stateId.cfId()).willReturn(CF_ID); + given(stateId.entityId()).willReturn(DEVICE_ID); + + TsRollingArgumentEntry rollingArgumentEntry = new TsRollingArgumentEntry(new TreeMap<>(Map.of(1000L, 1.0, 2000L, 0.0)), 2, 604800000L); + + CalculatedFieldState state = switch (type) { + case SCRIPT -> new ScriptCalculatedFieldState(DEVICE_ID); + case PROPAGATION -> new PropagationCalculatedFieldState(DEVICE_ID); + default -> throw new IllegalArgumentException("Unexpected CF type: " + type); + }; + state.getArguments().put("rollingArgument", rollingArgumentEntry); + + // when + CalculatedFieldState restored = CalculatedFieldUtils.fromProto(stateId, toProto(stateId, state)); + + // then + assertThat(restored).isInstanceOf(state.getClass()); + ArgumentEntry restoredArgument = restored.getArguments().get("rollingArgument"); + assertThat(restoredArgument).isInstanceOf(TsRollingArgumentEntry.class); + TsRollingArgumentEntry restoredRollingArgument = (TsRollingArgumentEntry) restoredArgument; + assertThat(restoredRollingArgument.getLimit()).isEqualTo(2); + assertThat(restoredRollingArgument.getTimeWindow()).isEqualTo(604800000L); + assertThat(restoredRollingArgument.getTsRecords()).isEqualTo(rollingArgumentEntry.getTsRecords()); + } + } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java index 8b13339cc2..aedcef6bc0 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfiguration.java @@ -46,6 +46,13 @@ public class AlarmCalculatedFieldConfiguration implements ArgumentsBasedCalculat return CalculatedFieldType.ALARM; } + @Override + public void validate() { + if (arguments != null && arguments.values().stream().anyMatch(Argument::hasTsRollingArgument)) { + throw new IllegalArgumentException("Calculated field with type: '" + getType() + "' doesn't support TS_ROLLING arguments."); + } + } + @Override public Output getOutput() { return null; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java index 96b93ce534..a28803723e 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/Argument.java @@ -35,7 +35,7 @@ public class Argument { } public boolean hasTsRollingArgument() { - return ArgumentType.TS_ROLLING.equals(refEntityKey.getType()); + return refEntityKey != null && ArgumentType.TS_ROLLING.equals(refEntityKey.getType()); } } diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java index aeea719730..85034dfb5a 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfiguration.java @@ -19,4 +19,12 @@ public class SimpleCalculatedFieldConfiguration extends BaseCalculatedFieldConfi return CalculatedFieldType.SIMPLE; } + @Override + public void validate() { + super.validate(); + if (arguments.values().stream().anyMatch(Argument::hasTsRollingArgument)) { + throw new IllegalArgumentException("Calculated field with type: '" + getType() + "' doesn't support TS_ROLLING arguments."); + } + } + } diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfigurationTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfigurationTest.java new file mode 100644 index 0000000000..bfa485ef59 --- /dev/null +++ b/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/AlarmCalculatedFieldConfigurationTest.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.cf.configuration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class AlarmCalculatedFieldConfigurationTest { + + @Test + void validateShouldThrowWhenTsRollingArgumentIsUsed() { + var cfg = new AlarmCalculatedFieldConfiguration(); + Argument argument = new Argument(); + argument.setRefEntityKey(new ReferencedEntityKey("key", ArgumentType.TS_ROLLING, null)); + cfg.setArguments(Map.of("arg", argument)); + + assertThatThrownBy(cfg::validate) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Calculated field with type: '" + CalculatedFieldType.ALARM + "' doesn't support TS_ROLLING arguments."); + } + + @ParameterizedTest + @EnumSource(value = ArgumentType.class, names = {"ATTRIBUTE", "TS_LATEST"}) + void validateShouldPassWhenNonRollingArgumentIsUsed(ArgumentType argumentType) { + var cfg = new AlarmCalculatedFieldConfiguration(); + Argument argument = new Argument(); + argument.setRefEntityKey(new ReferencedEntityKey("key", argumentType, null)); + cfg.setArguments(Map.of("arg", argument)); + + assertThatCode(cfg::validate).doesNotThrowAnyException(); + } + +} diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfigurationTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfigurationTest.java new file mode 100644 index 0000000000..337aaa6905 --- /dev/null +++ b/common/data/src/test/java/org/thingsboard/server/common/data/cf/configuration/SimpleCalculatedFieldConfigurationTest.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.common.data.cf.configuration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.thingsboard.server.common.data.cf.CalculatedFieldType; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class SimpleCalculatedFieldConfigurationTest { + + @Test + void validateShouldThrowWhenTsRollingArgumentIsUsed() { + var cfg = new SimpleCalculatedFieldConfiguration(); + Argument argument = new Argument(); + argument.setRefEntityKey(new ReferencedEntityKey("key", ArgumentType.TS_ROLLING, null)); + cfg.setArguments(Map.of("arg", argument)); + + assertThatThrownBy(cfg::validate) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Calculated field with type: '" + CalculatedFieldType.SIMPLE + "' doesn't support TS_ROLLING arguments."); + } + + @ParameterizedTest + @EnumSource(value = ArgumentType.class, names = {"ATTRIBUTE", "TS_LATEST"}) + void validateShouldPassWhenNonRollingArgumentIsUsed(ArgumentType argumentType) { + var cfg = new SimpleCalculatedFieldConfiguration(); + Argument argument = new Argument(); + argument.setRefEntityKey(new ReferencedEntityKey("key", argumentType, null)); + cfg.setArguments(Map.of("arg", argument)); + + assertThatCode(cfg::validate).doesNotThrowAnyException(); + } + +}