committed by
GitHub
100 changed files with 1661 additions and 535 deletions
@ -0,0 +1,30 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.solutions.data; |
|||
|
|||
import lombok.AccessLevel; |
|||
import lombok.Getter; |
|||
import lombok.RequiredArgsConstructor; |
|||
|
|||
/** |
|||
* The outcome of validating a solution template before anything is created: either the install can go ahead, or the |
|||
* entities of the tenant the template clashes with, reported as the markdown the install dialog renders. |
|||
*/ |
|||
@Getter |
|||
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) |
|||
public class SolutionValidationResult { |
|||
|
|||
private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); |
|||
|
|||
private final boolean passed; |
|||
private final String conflictReport; |
|||
|
|||
public static SolutionValidationResult passed() { |
|||
return PASSED; |
|||
} |
|||
|
|||
public static SolutionValidationResult conflictsFound(String conflictReport) { |
|||
return new SolutionValidationResult(false, conflictReport); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,208 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.edge.rpc; |
|||
|
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentMatcher; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.rule.engine.api.AttributesSaveRequest; |
|||
import org.thingsboard.server.cache.SimpleTbCacheValueWrapper; |
|||
import org.thingsboard.server.cache.TbTransactionalCache; |
|||
import org.thingsboard.server.cluster.TbClusterService; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.EdgeId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.msg.queue.ServiceType; |
|||
import org.thingsboard.server.queue.discovery.PartitionService; |
|||
import org.thingsboard.server.queue.discovery.TbServiceInfoProvider; |
|||
import org.thingsboard.server.service.edge.EdgeContextComponent; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ConcurrentMap; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.argThat; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.when; |
|||
import static org.thingsboard.server.service.state.DefaultDeviceStateService.ACTIVITY_STATE; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
public class EdgeGrpcServiceTest { |
|||
|
|||
private static final String THIS_NODE = "tb-core-1"; |
|||
private static final String OTHER_NODE = "tb-core-2"; |
|||
|
|||
@Mock |
|||
private TbTransactionalCache<EdgeId, String> edgeIdServiceIdCache; |
|||
|
|||
@Mock |
|||
private TbServiceInfoProvider serviceInfoProvider; |
|||
|
|||
@Mock |
|||
private PartitionService partitionService; |
|||
|
|||
@Mock |
|||
private TelemetrySubscriptionService tsSubService; |
|||
|
|||
@Mock |
|||
private TbClusterService clusterService; |
|||
|
|||
@Mock |
|||
private EdgeContextComponent ctx; |
|||
|
|||
@InjectMocks |
|||
private EdgeGrpcService edgeGrpcService; |
|||
|
|||
private EdgeId edgeId; |
|||
private Edge edge; |
|||
|
|||
@BeforeEach |
|||
public void setUp() { |
|||
edgeId = new EdgeId(UUID.randomUUID()); |
|||
edge = new Edge(edgeId); |
|||
edge.setTenantId(TenantId.fromUUID(UUID.randomUUID())); |
|||
edge.setName("test-edge"); |
|||
} |
|||
|
|||
// --- activity-state write guard on disconnect ---
|
|||
|
|||
@Test |
|||
public void givenEdgeReconnectedToAnotherNode_whenDisconnect_thenInactiveStateNotPersisted() { |
|||
// A newer session on another node already set active=true. This stale session's disconnect must not
|
|||
// clobber it - otherwise the edge stays marked inactive while connected, and the server silently
|
|||
// drops every assignment event for it.
|
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); |
|||
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); |
|||
} |
|||
|
|||
@Test |
|||
public void givenEdgeOwnedByThisNode_whenDisconnect_thenInactiveStateIsPersisted() { |
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); |
|||
} |
|||
|
|||
@Test |
|||
public void givenNoCacheEntry_whenDisconnect_thenInactiveStateIsPersisted() { |
|||
// Ownership unknown (entry absent or expired): keep the pre-guard behaviour, otherwise a genuinely
|
|||
// disconnected edge would stay marked active forever.
|
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(null); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); |
|||
} |
|||
|
|||
@Test |
|||
public void givenOwnerNodeNoLongerInCluster_whenDisconnect_thenInactiveStateIsPersisted() { |
|||
// The recorded owner died without evicting its claim. The edge sessions cache has no TTL by default
|
|||
// and only the owner ever evicts, so honouring a dead claim would leave the edge active forever.
|
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); |
|||
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE)); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(tsSubService, times(1)).saveAttributes(argThat(inactiveStateWrite())); |
|||
} |
|||
|
|||
@Test |
|||
public void givenSessionReplacedDuringDisconnect_whenStaleCallbackRuns_thenLiveSessionKept() { |
|||
// Reproduces the get()/remove() interleaving on a single node: onEdgeConnect swaps in a new session
|
|||
// right after the stale callback's id check passes. The stale callback must not evict or tear down
|
|||
// the live session, nor clear the activity state.
|
|||
UUID staleSessionId = UUID.randomUUID(); |
|||
EdgeGrpcSession live = mock(EdgeGrpcSession.class); |
|||
EdgeGrpcSession stale = mock(EdgeGrpcSession.class); |
|||
when(stale.getSessionId()).thenAnswer(invocation -> { |
|||
sessions().put(edgeId, live); |
|||
return staleSessionId; |
|||
}); |
|||
sessions().put(edgeId, stale); |
|||
|
|||
onEdgeDisconnect(staleSessionId); |
|||
|
|||
assertThat(sessions().get(edgeId)).isSameAs(live); |
|||
verify(tsSubService, never()).saveAttributes(argThat(inactiveStateWrite())); |
|||
} |
|||
|
|||
// --- service-id cache eviction guard ---
|
|||
|
|||
@Test |
|||
public void givenCacheOwnedByThisNode_whenDisconnect_thenEntryIsEvicted() { |
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(THIS_NODE)); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(edgeIdServiceIdCache, times(1)).evict(edgeId); |
|||
} |
|||
|
|||
@Test |
|||
public void givenCacheOwnedByAnotherNode_whenDisconnect_thenEntryIsKept() { |
|||
// The edge already reconnected elsewhere: wiping the live owner's claim would defeat the
|
|||
// activity-state guard for any later disconnect callback.
|
|||
UUID sessionId = UUID.randomUUID(); |
|||
sessions().put(edgeId, sessionFor(sessionId)); |
|||
when(serviceInfoProvider.getServiceId()).thenReturn(THIS_NODE); |
|||
when(edgeIdServiceIdCache.get(edgeId)).thenReturn(SimpleTbCacheValueWrapper.wrap(OTHER_NODE)); |
|||
when(partitionService.getAllServiceIds(ServiceType.TB_CORE)).thenReturn(Set.of(THIS_NODE, OTHER_NODE)); |
|||
|
|||
onEdgeDisconnect(sessionId); |
|||
|
|||
verify(edgeIdServiceIdCache, never()).evict(edgeId); |
|||
} |
|||
|
|||
private void onEdgeDisconnect(UUID sessionId) { |
|||
ReflectionTestUtils.invokeMethod(edgeGrpcService, "onEdgeDisconnect", edge, sessionId); |
|||
} |
|||
|
|||
private EdgeGrpcSession sessionFor(UUID sessionId) { |
|||
EdgeGrpcSession session = mock(EdgeGrpcSession.class); |
|||
when(session.getSessionId()).thenReturn(sessionId); |
|||
when(session.getEdge()).thenReturn(edge); |
|||
return session; |
|||
} |
|||
|
|||
@SuppressWarnings("unchecked") |
|||
private ConcurrentMap<EdgeId, EdgeGrpcSession> sessions() { |
|||
return (ConcurrentMap<EdgeId, EdgeGrpcSession>) ReflectionTestUtils.getField(edgeGrpcService, "sessions"); |
|||
} |
|||
|
|||
private ArgumentMatcher<AttributesSaveRequest> inactiveStateWrite() { |
|||
return request -> request != null |
|||
&& edgeId.equals(request.getEntityId()) |
|||
&& request.getEntries().stream().anyMatch(entry -> |
|||
ACTIVITY_STATE.equals(entry.getKey()) |
|||
&& Boolean.FALSE.equals(entry.getBooleanValue().orElse(null))); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,294 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.solutions; |
|||
|
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.junit.jupiter.api.io.TempDir; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.server.common.data.Customer; |
|||
import org.thingsboard.server.common.data.DashboardInfo; |
|||
import org.thingsboard.server.common.data.Device; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.asset.Asset; |
|||
import org.thingsboard.server.common.data.asset.AssetProfile; |
|||
import org.thingsboard.server.common.data.edge.Edge; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.common.data.rule.RuleChainType; |
|||
import org.thingsboard.server.dao.asset.AssetProfileService; |
|||
import org.thingsboard.server.dao.asset.AssetService; |
|||
import org.thingsboard.server.dao.customer.CustomerService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.device.DeviceService; |
|||
import org.thingsboard.server.dao.edge.EdgeService; |
|||
import org.thingsboard.server.dao.rule.RuleChainService; |
|||
import org.thingsboard.server.service.solutions.data.SolutionValidationResult; |
|||
|
|||
import java.io.IOException; |
|||
import java.nio.file.Files; |
|||
import java.nio.file.Path; |
|||
import java.util.List; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
import java.util.stream.Collectors; |
|||
import java.util.stream.IntStream; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoInteractions; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
class DefaultSolutionServiceTest { |
|||
|
|||
private static final String CONFLICTS_INTRO = |
|||
"Some entities of the solution template already exist. Rename or delete them and install the template again:"; |
|||
// mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it
|
|||
private static final int LISTED_NAMES_PER_TYPE = 10; |
|||
private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE |
|||
+ " names of each type are listed. The rest are reported the next time the template is installed."; |
|||
|
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
|
|||
@Mock |
|||
private CustomerService customerService; |
|||
@Mock |
|||
private DeviceService deviceService; |
|||
@Mock |
|||
private AssetService assetService; |
|||
@Mock |
|||
private DashboardService dashboardService; |
|||
@Mock |
|||
private RuleChainService ruleChainService; |
|||
@Mock |
|||
private DeviceProfileService deviceProfileService; |
|||
@Mock |
|||
private AssetProfileService assetProfileService; |
|||
@Mock |
|||
private EdgeService edgeService; |
|||
|
|||
@InjectMocks |
|||
private DefaultSolutionService service; |
|||
|
|||
@TempDir |
|||
private Path tempDir; |
|||
|
|||
@Test |
|||
void testValidateSolutionNamesEveryConflictingEntity() throws IOException { |
|||
writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); |
|||
writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); |
|||
|
|||
Customer customer = new Customer(); |
|||
customer.setTitle("Existing customer"); |
|||
|
|||
when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); |
|||
Asset asset = new Asset(); |
|||
asset.setName("Existing asset"); |
|||
when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); |
|||
when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) |
|||
.thenReturn(existingDevice("Existing device")); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence( |
|||
CONFLICTS_INTRO, |
|||
"- **Customer**: 'Existing customer'", |
|||
"- **Asset**: 'Existing asset'", |
|||
"- **Device**: 'Existing device'"); |
|||
// the randomized customer title and the entities that do not exist yet are not reported
|
|||
assertThat(result.getConflictReport()) |
|||
.doesNotContain("Customer $random") |
|||
.doesNotContain("New device") |
|||
.doesNotContain("New asset"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionReportsConflictingDashboard() throws IOException { |
|||
writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); |
|||
|
|||
DashboardInfo dashboard = new DashboardInfo(); |
|||
dashboard.setTitle("Overview"); |
|||
when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); |
|||
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); |
|||
|
|||
RuleChain ruleChain = new RuleChain(); |
|||
ruleChain.setName("Name the install creates"); |
|||
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) |
|||
.thenReturn(List.of(ruleChain)); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()) |
|||
.containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { |
|||
writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); |
|||
writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); |
|||
writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); |
|||
|
|||
DeviceProfile deviceProfile = new DeviceProfile(); |
|||
deviceProfile.setName("thermostat"); |
|||
AssetProfile assetProfile = new AssetProfile(); |
|||
assetProfile.setName("building"); |
|||
Edge edge = new Edge(); |
|||
edge.setName("Main edge"); |
|||
when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); |
|||
when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); |
|||
when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.isPassed()).isFalse(); |
|||
assertThat(result.getConflictReport().lines().toList()).containsSubsequence( |
|||
"- **Device profile**: 'thermostat'", |
|||
"- **Asset profile**: 'building'", |
|||
"- **Edge**: 'Main edge'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); |
|||
|
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); |
|||
verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + |
|||
"{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); |
|||
writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(ruleChainService); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { |
|||
writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); |
|||
writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); |
|||
|
|||
RuleChain ruleChain = new RuleChain(); |
|||
ruleChain.setName("Edge chain"); |
|||
when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) |
|||
.thenReturn(List.of(ruleChain)); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { |
|||
writeEntitiesFile("devices.json", "null"); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(deviceService); |
|||
} |
|||
|
|||
@ParameterizedTest |
|||
@ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) |
|||
void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { |
|||
List<String> names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); |
|||
writeEntitiesFile("devices.json", names.stream() |
|||
.map(name -> "{\"name\": \"" + name + "\"}") |
|||
.collect(Collectors.joining(",", "[", "]"))); |
|||
names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) |
|||
.thenReturn(existingDevice(name))); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
int hidden = conflictCount - LISTED_NAMES_PER_TYPE; |
|||
String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) |
|||
.map(name -> "'" + name + "'").collect(Collectors.joining(", ")); |
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed |
|||
+ (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); |
|||
if (hidden > 0) { |
|||
assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); |
|||
} else { |
|||
assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* The profile lists are the json file plus every file in the directory of the same name merged into one list, so |
|||
* this is where the same name genuinely can appear twice. |
|||
*/ |
|||
@Test |
|||
void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { |
|||
writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); |
|||
writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); |
|||
|
|||
DeviceProfile profile = new DeviceProfile(); |
|||
profile.setName("Sensor profile"); |
|||
when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); |
|||
|
|||
SolutionValidationResult result = service.validateSolution(tenantId, tempDir); |
|||
|
|||
assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); |
|||
verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionWithoutConflicts() throws IOException { |
|||
writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); |
|||
when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); |
|||
|
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void testValidateSolutionWithoutEntityFiles() { |
|||
assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); |
|||
verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, |
|||
deviceProfileService, assetProfileService, edgeService); |
|||
} |
|||
|
|||
private static Device existingDevice(String name) { |
|||
Device device = new Device(); |
|||
device.setName(name); |
|||
return device; |
|||
} |
|||
|
|||
private void writeFile(String relativePath, String content) throws IOException { |
|||
Path file = tempDir.resolve(relativePath); |
|||
Files.createDirectories(file.getParent()); |
|||
Files.writeString(file, content); |
|||
} |
|||
|
|||
private void writeEntitiesFile(String fileName, String content) throws IOException { |
|||
Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); |
|||
Files.writeString(entitiesDir.resolve(fileName), content); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,109 @@ |
|||
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.script.api.js; |
|||
|
|||
import delight.nashornsandbox.NashornSandbox; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.params.ParameterizedTest; |
|||
import org.junit.jupiter.params.provider.ValueSource; |
|||
import org.mockito.Mockito; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.thingsboard.script.api.ScriptType; |
|||
import org.thingsboard.script.api.TbScriptException; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.stats.StatsFactory; |
|||
|
|||
import javax.script.ScriptEngine; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
import java.util.concurrent.ExecutionException; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.assertj.core.api.Assertions.assertThatThrownBy; |
|||
import static org.mockito.Mockito.mock; |
|||
|
|||
/** |
|||
* Covers the JS global scope lifecycle against both backends the service can be configured with. |
|||
* The Spring-wired {@code NashornJsInvokeServiceTest} only exercises the sandbox, since |
|||
* {@code js.local.use_js_sandbox} defaults to true. |
|||
*/ |
|||
class NashornJsInvokeServiceLifecycleTest { |
|||
|
|||
private static final String[] ARG_NAMES = {"msg", "metadata", "msgType"}; |
|||
|
|||
private NashornJsInvokeService service; |
|||
private boolean useJsSandbox; |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
if (service != null) { |
|||
service.stop(); |
|||
} |
|||
} |
|||
|
|||
@ParameterizedTest(name = "useJsSandbox = {0}") |
|||
@ValueSource(booleans = {true, false}) |
|||
void whenScriptIsReleased_thenGlobalPropertyIsRemovedAndFunctionIsGone(boolean useJsSandbox) throws Exception { |
|||
givenService(useJsSandbox); |
|||
UUID scriptId = UUID.randomUUID(); |
|||
|
|||
JsScriptInfo scriptInfo = eval(scriptId, "return {doubled: msg.temperature * 2};"); |
|||
assertThat(hasGlobalProperty(scriptInfo)).isTrue(); |
|||
assertThat(invoke(scriptId, scriptInfo, "{\"temperature\":21}")).asString().contains("\"doubled\":42"); |
|||
|
|||
service.doRelease(scriptId); |
|||
|
|||
assertThat(hasGlobalProperty(scriptInfo)).isFalse(); |
|||
assertThatThrownBy(() -> invoke(scriptId, scriptInfo, "{\"temperature\":21}")) |
|||
.isInstanceOf(ExecutionException.class) |
|||
.cause() |
|||
.isInstanceOf(TbScriptException.class); |
|||
} |
|||
|
|||
@ParameterizedTest(name = "useJsSandbox = {0}") |
|||
@ValueSource(booleans = {true, false}) |
|||
void whenOneOfTwoScriptsIsReleased_thenTheOtherKeepsWorking(boolean useJsSandbox) throws Exception { |
|||
givenService(useJsSandbox); |
|||
UUID releasedId = UUID.randomUUID(); |
|||
UUID retainedId = UUID.randomUUID(); |
|||
|
|||
JsScriptInfo released = eval(releasedId, "return {v: 1};"); |
|||
JsScriptInfo retained = eval(retainedId, "return {v: 2};"); |
|||
|
|||
service.doRelease(releasedId); |
|||
|
|||
assertThat(hasGlobalProperty(released)).isFalse(); |
|||
assertThat(hasGlobalProperty(retained)).isTrue(); |
|||
assertThat(invoke(retainedId, retained, "{}")).asString().contains("\"v\":2"); |
|||
} |
|||
|
|||
private void givenService(boolean useJsSandbox) { |
|||
this.useJsSandbox = useJsSandbox; |
|||
service = new NashornJsInvokeService(Optional.empty(), Optional.empty()); |
|||
ReflectionTestUtils.setField(service, "statsFactory", mock(StatsFactory.class, Mockito.RETURNS_DEEP_STUBS)); |
|||
ReflectionTestUtils.setField(service, "useJsSandbox", useJsSandbox); |
|||
ReflectionTestUtils.setField(service, "jsExecutorThreadPoolSize", 4); |
|||
ReflectionTestUtils.setField(service, "monitorThreadPoolSize", 2); |
|||
ReflectionTestUtils.setField(service, "maxCpuTime", 8000L); |
|||
ReflectionTestUtils.setField(service, "maxMemory", 104857600L); |
|||
service.init(); |
|||
} |
|||
|
|||
private JsScriptInfo eval(UUID scriptId, String scriptBody) throws Exception { |
|||
service.doEvalScript(TenantId.SYS_TENANT_ID, ScriptType.RULE_NODE_SCRIPT, scriptBody, scriptId, ARG_NAMES).get(); |
|||
return service.scriptInfoMap.get(scriptId); |
|||
} |
|||
|
|||
private Object invoke(UUID scriptId, JsScriptInfo scriptInfo, String msg) throws Exception { |
|||
return service.doInvokeFunction(scriptId, scriptInfo, new Object[]{msg, "{}", "POST_TELEMETRY_REQUEST"}).get(); |
|||
} |
|||
|
|||
private boolean hasGlobalProperty(JsScriptInfo scriptInfo) throws Exception { |
|||
String expression = "this.hasOwnProperty('" + scriptInfo.getFunctionName() + "')"; |
|||
Object result = useJsSandbox |
|||
? ((NashornSandbox) ReflectionTestUtils.getField(service, "sandbox")).eval(expression) |
|||
: ((ScriptEngine) ReflectionTestUtils.getField(service, "engine")).eval(expression); |
|||
return Boolean.TRUE.equals(result); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue