41 changed files with 1004 additions and 254 deletions
@ -0,0 +1,219 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.service.script; |
|||
|
|||
import com.google.common.util.concurrent.Futures; |
|||
import org.apache.commons.lang3.StringUtils; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.thingsboard.server.common.data.ApiUsageState; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.gen.js.JsInvokeProtos; |
|||
import org.thingsboard.server.gen.js.JsInvokeProtos.RemoteJsRequest; |
|||
import org.thingsboard.server.gen.js.JsInvokeProtos.RemoteJsResponse; |
|||
import org.thingsboard.server.queue.TbQueueRequestTemplate; |
|||
import org.thingsboard.server.queue.common.TbProtoJsQueueMsg; |
|||
import org.thingsboard.server.queue.common.TbProtoQueueMsg; |
|||
import org.thingsboard.server.queue.usagestats.TbApiUsageClient; |
|||
import org.thingsboard.server.service.apiusage.TbApiUsageStateService; |
|||
|
|||
import java.util.HashSet; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.argThat; |
|||
import static org.mockito.Mockito.doAnswer; |
|||
import static org.mockito.Mockito.doReturn; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.reset; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoInteractions; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
class RemoteJsInvokeServiceTest { |
|||
|
|||
private RemoteJsInvokeService remoteJsInvokeService; |
|||
private TbQueueRequestTemplate<TbProtoJsQueueMsg<RemoteJsRequest>, TbProtoQueueMsg<RemoteJsResponse>> jsRequestTemplate; |
|||
|
|||
|
|||
@BeforeEach |
|||
public void beforeEach() { |
|||
TbApiUsageStateService apiUsageStateService = mock(TbApiUsageStateService.class); |
|||
ApiUsageState apiUsageState = mock(ApiUsageState.class); |
|||
when(apiUsageState.isJsExecEnabled()).thenReturn(true); |
|||
when(apiUsageStateService.getApiUsageState(any())).thenReturn(apiUsageState); |
|||
TbApiUsageClient apiUsageClient = mock(TbApiUsageClient.class); |
|||
|
|||
remoteJsInvokeService = new RemoteJsInvokeService(apiUsageStateService, apiUsageClient); |
|||
jsRequestTemplate = mock(TbQueueRequestTemplate.class); |
|||
remoteJsInvokeService.requestTemplate = jsRequestTemplate; |
|||
} |
|||
|
|||
@AfterEach |
|||
public void afterEach() { |
|||
reset(jsRequestTemplate); |
|||
} |
|||
|
|||
@Test |
|||
public void whenInvokingFunction_thenDoNotSendScriptBody() throws Exception { |
|||
mockJsEvalResponse(); |
|||
String scriptBody = "return { a: 'b'};"; |
|||
UUID scriptId = remoteJsInvokeService.eval(TenantId.SYS_TENANT_ID, JsScriptType.RULE_NODE_SCRIPT, scriptBody).get(); |
|||
reset(jsRequestTemplate); |
|||
|
|||
String expectedInvocationResult = "scriptInvocationResult"; |
|||
doReturn(Futures.immediateFuture(new TbProtoJsQueueMsg<>(UUID.randomUUID(), RemoteJsResponse.newBuilder() |
|||
.setInvokeResponse(JsInvokeProtos.JsInvokeResponse.newBuilder() |
|||
.setSuccess(true) |
|||
.setResult(expectedInvocationResult) |
|||
.build()) |
|||
.build()))) |
|||
.when(jsRequestTemplate).send(any()); |
|||
|
|||
ArgumentCaptor<TbProtoJsQueueMsg<RemoteJsRequest>> jsRequestCaptor = ArgumentCaptor.forClass(TbProtoJsQueueMsg.class); |
|||
Object invocationResult = remoteJsInvokeService.invokeFunction(TenantId.SYS_TENANT_ID, null, scriptId, "{}").get(); |
|||
verify(jsRequestTemplate).send(jsRequestCaptor.capture()); |
|||
|
|||
JsInvokeProtos.JsInvokeRequest jsInvokeRequestMade = jsRequestCaptor.getValue().getValue().getInvokeRequest(); |
|||
assertThat(jsInvokeRequestMade.getScriptBody()).isNullOrEmpty(); |
|||
assertThat(jsInvokeRequestMade.getScriptHash()).isEqualTo(getScriptHash(scriptId)); |
|||
assertThat(invocationResult).isEqualTo(expectedInvocationResult); |
|||
} |
|||
|
|||
@Test |
|||
public void whenInvokingFunctionAndRemoteJsExecutorRemovedScript_thenHandleNotFoundErrorAndMakeInvokeRequestWithScriptBody() throws Exception { |
|||
mockJsEvalResponse(); |
|||
String scriptBody = "return { a: 'b'};"; |
|||
UUID scriptId = remoteJsInvokeService.eval(TenantId.SYS_TENANT_ID, JsScriptType.RULE_NODE_SCRIPT, scriptBody).get(); |
|||
reset(jsRequestTemplate); |
|||
|
|||
doReturn(Futures.immediateFuture(new TbProtoJsQueueMsg<>(UUID.randomUUID(), RemoteJsResponse.newBuilder() |
|||
.setInvokeResponse(JsInvokeProtos.JsInvokeResponse.newBuilder() |
|||
.setSuccess(false) |
|||
.setErrorCode(JsInvokeProtos.JsInvokeErrorCode.NOT_FOUND_ERROR) |
|||
.build()) |
|||
.build()))) |
|||
.when(jsRequestTemplate).send(argThat(jsQueueMsg -> { |
|||
return StringUtils.isEmpty(jsQueueMsg.getValue().getInvokeRequest().getScriptBody()); |
|||
})); |
|||
|
|||
String expectedInvocationResult = "invocationResult"; |
|||
doReturn(Futures.immediateFuture(new TbProtoJsQueueMsg<>(UUID.randomUUID(), RemoteJsResponse.newBuilder() |
|||
.setInvokeResponse(JsInvokeProtos.JsInvokeResponse.newBuilder() |
|||
.setSuccess(true) |
|||
.setResult(expectedInvocationResult) |
|||
.build()) |
|||
.build()))) |
|||
.when(jsRequestTemplate).send(argThat(jsQueueMsg -> { |
|||
return StringUtils.isNotEmpty(jsQueueMsg.getValue().getInvokeRequest().getScriptBody()); |
|||
})); |
|||
|
|||
ArgumentCaptor<TbProtoJsQueueMsg<RemoteJsRequest>> jsRequestsCaptor = ArgumentCaptor.forClass(TbProtoJsQueueMsg.class); |
|||
Object invocationResult = remoteJsInvokeService.invokeFunction(TenantId.SYS_TENANT_ID, null, scriptId, "{}").get(); |
|||
verify(jsRequestTemplate, times(2)).send(jsRequestsCaptor.capture()); |
|||
|
|||
List<TbProtoJsQueueMsg<RemoteJsRequest>> jsInvokeRequestsMade = jsRequestsCaptor.getAllValues(); |
|||
|
|||
JsInvokeProtos.JsInvokeRequest firstRequestMade = jsInvokeRequestsMade.get(0).getValue().getInvokeRequest(); |
|||
assertThat(firstRequestMade.getScriptBody()).isNullOrEmpty(); |
|||
|
|||
JsInvokeProtos.JsInvokeRequest secondRequestMade = jsInvokeRequestsMade.get(1).getValue().getInvokeRequest(); |
|||
assertThat(secondRequestMade.getScriptBody()).contains(scriptBody); |
|||
|
|||
assertThat(jsInvokeRequestsMade.stream().map(TbProtoQueueMsg::getKey).distinct().count()).as("partition keys are same") |
|||
.isOne(); |
|||
|
|||
assertThat(invocationResult).isEqualTo(expectedInvocationResult); |
|||
} |
|||
|
|||
@Test |
|||
public void whenDoingEval_thenSaveScriptByHashOfTenantIdAndScriptBody() throws Exception { |
|||
mockJsEvalResponse(); |
|||
|
|||
TenantId tenantId1 = TenantId.fromUUID(UUID.randomUUID()); |
|||
String scriptBody1 = "var msg = { temp: 42, humidity: 77 };\n" + |
|||
"var metadata = { data: 40 };\n" + |
|||
"var msgType = \"POST_TELEMETRY_REQUEST\";\n" + |
|||
"\n" + |
|||
"return { msg: msg, metadata: metadata, msgType: msgType };"; |
|||
|
|||
Set<String> scriptHashes = new HashSet<>(); |
|||
String tenant1Script1Hash = null; |
|||
for (int i = 0; i < 3; i++) { |
|||
UUID scriptUuid = remoteJsInvokeService.eval(tenantId1, JsScriptType.RULE_NODE_SCRIPT, scriptBody1).get(); |
|||
tenant1Script1Hash = getScriptHash(scriptUuid); |
|||
scriptHashes.add(tenant1Script1Hash); |
|||
} |
|||
assertThat(scriptHashes).as("Unique scripts ids").size().isOne(); |
|||
|
|||
TenantId tenantId2 = TenantId.fromUUID(UUID.randomUUID()); |
|||
UUID scriptUuid = remoteJsInvokeService.eval(tenantId2, JsScriptType.RULE_NODE_SCRIPT, scriptBody1).get(); |
|||
String tenant2Script1Id = getScriptHash(scriptUuid); |
|||
assertThat(tenant2Script1Id).isNotEqualTo(tenant1Script1Hash); |
|||
|
|||
String scriptBody2 = scriptBody1 + ";;"; |
|||
scriptUuid = remoteJsInvokeService.eval(tenantId2, JsScriptType.RULE_NODE_SCRIPT, scriptBody2).get(); |
|||
String tenant2Script2Id = getScriptHash(scriptUuid); |
|||
assertThat(tenant2Script2Id).isNotEqualTo(tenant2Script1Id); |
|||
} |
|||
|
|||
@Test |
|||
public void whenReleasingScript_thenCheckForHashUsages() throws Exception { |
|||
mockJsEvalResponse(); |
|||
String scriptBody = "return { a: 'b'};"; |
|||
UUID scriptId1 = remoteJsInvokeService.eval(TenantId.SYS_TENANT_ID, JsScriptType.RULE_NODE_SCRIPT, scriptBody).get(); |
|||
UUID scriptId2 = remoteJsInvokeService.eval(TenantId.SYS_TENANT_ID, JsScriptType.RULE_NODE_SCRIPT, scriptBody).get(); |
|||
String scriptHash = getScriptHash(scriptId1); |
|||
assertThat(scriptHash).isEqualTo(getScriptHash(scriptId2)); |
|||
reset(jsRequestTemplate); |
|||
|
|||
doReturn(Futures.immediateFuture(new TbProtoQueueMsg<>(UUID.randomUUID(), RemoteJsResponse.newBuilder() |
|||
.setReleaseResponse(JsInvokeProtos.JsReleaseResponse.newBuilder() |
|||
.setSuccess(true) |
|||
.build()) |
|||
.build()))) |
|||
.when(jsRequestTemplate).send(any()); |
|||
|
|||
remoteJsInvokeService.release(scriptId1).get(); |
|||
verifyNoInteractions(jsRequestTemplate); |
|||
assertThat(remoteJsInvokeService.scriptHashToBodysMap).containsKey(scriptHash); |
|||
|
|||
remoteJsInvokeService.release(scriptId2).get(); |
|||
verify(jsRequestTemplate).send(any()); |
|||
assertThat(remoteJsInvokeService.scriptHashToBodysMap).isEmpty(); |
|||
} |
|||
|
|||
private String getScriptHash(UUID scriptUuid) { |
|||
return remoteJsInvokeService.scriptIdToNameAndHashMap.get(scriptUuid).getSecond(); |
|||
} |
|||
|
|||
private void mockJsEvalResponse() { |
|||
doAnswer(methodCall -> Futures.immediateFuture(new TbProtoJsQueueMsg<>(UUID.randomUUID(), RemoteJsResponse.newBuilder() |
|||
.setCompileResponse(JsInvokeProtos.JsCompileResponse.newBuilder() |
|||
.setSuccess(true) |
|||
.setScriptHash(methodCall.<TbProtoQueueMsg<RemoteJsRequest>>getArgument(0).getValue().getCompileRequest().getScriptHash()) |
|||
.build()) |
|||
.build()))) |
|||
.when(jsRequestTemplate).send(argThat(jsQueueMsg -> jsQueueMsg.getValue().hasCompileRequest())); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,26 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.server.common.data; |
|||
|
|||
import org.thingsboard.server.common.data.id.RuleChainId; |
|||
|
|||
public interface HasRuleEngineProfile { |
|||
|
|||
RuleChainId getDefaultRuleChainId(); |
|||
|
|||
String getDefaultQueueName(); |
|||
|
|||
} |
|||
@ -0,0 +1,45 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.rule.engine.telemetry; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.thingsboard.rule.engine.api.TbContext; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
|
|||
import javax.annotation.Nullable; |
|||
import java.util.List; |
|||
|
|||
@Slf4j |
|||
public class AttributesDeleteNodeCallback extends TelemetryNodeCallback { |
|||
|
|||
private String scope; |
|||
private List<String> keys; |
|||
|
|||
public AttributesDeleteNodeCallback(TbContext ctx, TbMsg msg, String scope, List<String> keys) { |
|||
super(ctx, msg); |
|||
this.scope = scope; |
|||
this.keys = keys; |
|||
} |
|||
|
|||
@Override |
|||
public void onSuccess(@Nullable Void result) { |
|||
TbContext ctx = this.getCtx(); |
|||
TbMsg tbMsg = this.getMsg(); |
|||
ctx.enqueue(ctx.attributesDeletedActionMsg(tbMsg.getOriginator(), ctx.getSelfId(), scope, keys), |
|||
() -> ctx.tellSuccess(tbMsg), |
|||
throwable -> ctx.tellFailure(tbMsg, throwable)); |
|||
} |
|||
} |
|||
@ -0,0 +1,44 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.rule.engine.telemetry; |
|||
|
|||
import org.thingsboard.rule.engine.api.TbContext; |
|||
import org.thingsboard.server.common.data.kv.AttributeKvEntry; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
|
|||
import javax.annotation.Nullable; |
|||
import java.util.List; |
|||
|
|||
public class AttributesUpdateNodeCallback extends TelemetryNodeCallback { |
|||
|
|||
private String scope; |
|||
private List<AttributeKvEntry> attributes; |
|||
|
|||
public AttributesUpdateNodeCallback(TbContext ctx, TbMsg msg, String scope, List<AttributeKvEntry> attributes) { |
|||
super(ctx, msg); |
|||
this.scope = scope; |
|||
this.attributes = attributes; |
|||
} |
|||
|
|||
@Override |
|||
public void onSuccess(@Nullable Void result) { |
|||
TbContext ctx = this.getCtx(); |
|||
TbMsg tbMsg = this.getMsg(); |
|||
ctx.enqueue(ctx.attributesUpdatedActionMsg(tbMsg.getOriginator(), ctx.getSelfId(), scope, attributes), |
|||
() -> ctx.tellSuccess(tbMsg), |
|||
throwable -> ctx.tellFailure(tbMsg, throwable)); |
|||
} |
|||
} |
|||
@ -0,0 +1,73 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.rule.engine.telemetry; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.thingsboard.rule.engine.api.RuleNode; |
|||
import org.thingsboard.rule.engine.api.TbContext; |
|||
import org.thingsboard.rule.engine.api.TbNode; |
|||
import org.thingsboard.rule.engine.api.TbNodeConfiguration; |
|||
import org.thingsboard.rule.engine.api.TbNodeException; |
|||
import org.thingsboard.rule.engine.api.util.TbNodeUtils; |
|||
import org.thingsboard.server.common.data.StringUtils; |
|||
import org.thingsboard.server.common.data.plugin.ComponentType; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
|
|||
import java.util.List; |
|||
import java.util.concurrent.ExecutionException; |
|||
import java.util.stream.Collectors; |
|||
|
|||
@Slf4j |
|||
@RuleNode( |
|||
type = ComponentType.ACTION, |
|||
name = "delete attributes", |
|||
configClazz = TbMsgDeleteAttributesConfiguration.class, |
|||
nodeDescription = "Delete attributes for Message Originator.", |
|||
nodeDetails = "Attempt to remove attributes by selected keys. If msg originator doesn't have an attribute with " + |
|||
" a key selected in the configuration, it will be ignored. If delete operation is completed successfully, " + |
|||
" rule node will send the \"Attributes Deleted\" event to the root chain of the message originator and " + |
|||
" send the incoming message via <b>Success</b> chain, otherwise, <b>Failure</b> chain is used.", |
|||
uiResources = {"static/rulenode/rulenode-core-config.js"}, |
|||
configDirective = "tbActionNodeDeleteAttributesConfig", |
|||
icon = "remove_circle" |
|||
) |
|||
public class TbMsgDeleteAttributes implements TbNode { |
|||
|
|||
private TbMsgDeleteAttributesConfiguration config; |
|||
private String scope; |
|||
private List<String> keys; |
|||
|
|||
@Override |
|||
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { |
|||
this.config = TbNodeUtils.convert(configuration, TbMsgDeleteAttributesConfiguration.class); |
|||
this.scope = config.getScope(); |
|||
this.keys = config.getKeys(); |
|||
} |
|||
|
|||
@Override |
|||
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException { |
|||
List<String> keysToDelete = keys.stream() |
|||
.map(keyPattern -> TbNodeUtils.processPattern(keyPattern, msg)) |
|||
.distinct() |
|||
.filter(StringUtils::isNotBlank) |
|||
.collect(Collectors.toList()); |
|||
if (keysToDelete.isEmpty()) { |
|||
ctx.tellSuccess(msg); |
|||
} else { |
|||
ctx.getTelemetryService().deleteAndNotify(ctx.getTenantId(), msg.getOriginator(), scope, keysToDelete, new AttributesDeleteNodeCallback(ctx, msg, scope, keysToDelete)); |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,38 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.rule.engine.telemetry; |
|||
|
|||
import lombok.Data; |
|||
import org.thingsboard.rule.engine.api.NodeConfiguration; |
|||
import org.thingsboard.server.common.data.DataConstants; |
|||
|
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
|
|||
@Data |
|||
public class TbMsgDeleteAttributesConfiguration implements NodeConfiguration<TbMsgDeleteAttributesConfiguration> { |
|||
|
|||
private String scope; |
|||
private List<String> keys; |
|||
|
|||
@Override |
|||
public TbMsgDeleteAttributesConfiguration defaultConfiguration() { |
|||
TbMsgDeleteAttributesConfiguration configuration = new TbMsgDeleteAttributesConfiguration(); |
|||
configuration.setScope(DataConstants.SERVER_SCOPE); |
|||
configuration.setKeys(Collections.emptyList()); |
|||
return configuration; |
|||
} |
|||
} |
|||
@ -0,0 +1,125 @@ |
|||
/** |
|||
* Copyright © 2016-2022 The Thingsboard Authors |
|||
* |
|||
* Licensed under the Apache License, Version 2.0 (the "License"); |
|||
* you may not use this file except in compliance with the License. |
|||
* You may obtain a copy of the License at |
|||
* |
|||
* http://www.apache.org/licenses/LICENSE-2.0
|
|||
* |
|||
* Unless required by applicable law or agreed to in writing, software |
|||
* distributed under the License is distributed on an "AS IS" BASIS, |
|||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
|||
* See the License for the specific language governing permissions and |
|||
* limitations under the License. |
|||
*/ |
|||
package org.thingsboard.rule.engine.telemetry; |
|||
|
|||
import com.fasterxml.jackson.databind.ObjectMapper; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.junit.jupiter.api.AfterEach; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.runner.RunWith; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.mockito.Captor; |
|||
import org.mockito.junit.MockitoJUnitRunner; |
|||
import org.thingsboard.rule.engine.api.RuleEngineTelemetryService; |
|||
import org.thingsboard.rule.engine.api.TbContext; |
|||
import org.thingsboard.rule.engine.api.TbNodeConfiguration; |
|||
import org.thingsboard.rule.engine.api.TbNodeException; |
|||
import org.thingsboard.server.common.data.DataConstants; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
import org.thingsboard.server.common.msg.TbMsg; |
|||
import org.thingsboard.server.common.msg.TbMsgMetaData; |
|||
import org.thingsboard.server.common.msg.queue.TbMsgCallback; |
|||
|
|||
import java.util.Collections; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
import java.util.function.Consumer; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.ArgumentMatchers.anyList; |
|||
import static org.mockito.ArgumentMatchers.anyString; |
|||
import static org.mockito.BDDMockito.willAnswer; |
|||
import static org.mockito.BDDMockito.willReturn; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.spy; |
|||
import static org.mockito.Mockito.times; |
|||
import static org.mockito.Mockito.verify; |
|||
|
|||
@Slf4j |
|||
public class TbMsgDeleteAttributesTest { |
|||
final ObjectMapper mapper = new ObjectMapper(); |
|||
|
|||
DeviceId deviceId; |
|||
TbMsgDeleteAttributes node; |
|||
TbMsgDeleteAttributesConfiguration config; |
|||
TbNodeConfiguration nodeConfiguration; |
|||
TbContext ctx; |
|||
TbMsgCallback callback; |
|||
|
|||
RuleEngineTelemetryService telemetryService; |
|||
|
|||
@BeforeEach |
|||
void setUp() throws TbNodeException { |
|||
deviceId = new DeviceId(UUID.randomUUID()); |
|||
callback = mock(TbMsgCallback.class); |
|||
ctx = mock(TbContext.class); |
|||
config = new TbMsgDeleteAttributesConfiguration().defaultConfiguration(); |
|||
config.setKeys(List.of("${TestAttribute_1}", "$[TestAttribute_2]", "$[TestAttribute_3]", "TestAttribute_4")); |
|||
nodeConfiguration = new TbNodeConfiguration(mapper.valueToTree(config)); |
|||
node = spy(new TbMsgDeleteAttributes()); |
|||
node.init(ctx, nodeConfiguration); |
|||
telemetryService = mock(RuleEngineTelemetryService.class); |
|||
|
|||
willReturn(telemetryService).given(ctx).getTelemetryService(); |
|||
willAnswer(invocation -> { |
|||
TelemetryNodeCallback callBack = invocation.getArgument(4); |
|||
callBack.onSuccess(null); |
|||
return null; |
|||
}).given(telemetryService).deleteAndNotify( |
|||
any(), any(), anyString(), anyList(), any()); |
|||
} |
|||
|
|||
@AfterEach |
|||
void tearDown() { |
|||
node.destroy(); |
|||
} |
|||
|
|||
@Test |
|||
void givenDefaultConfig_whenVerify_thenOK() { |
|||
TbMsgDeleteAttributesConfiguration defaultConfig = new TbMsgDeleteAttributesConfiguration().defaultConfiguration(); |
|||
assertThat(defaultConfig.getScope()).isEqualTo(DataConstants.SERVER_SCOPE); |
|||
assertThat(defaultConfig.getKeys()).isEqualTo(Collections.emptyList()); |
|||
} |
|||
|
|||
@Test |
|||
void givenMsg_whenOnMsg_thenVerifyOutput() throws Exception { |
|||
final Map<String, String> mdMap = Map.of( |
|||
"TestAttribute_1", "temperature", |
|||
"city", "NY" |
|||
); |
|||
final TbMsgMetaData metaData = new TbMsgMetaData(mdMap); |
|||
final String data = "{\"TestAttribute_2\": \"humidity\", \"TestAttribute_3\": \"voltage\"}"; |
|||
|
|||
TbMsg msg = TbMsg.newMsg("POST_ATTRIBUTES_REQUEST", deviceId, metaData, data, callback); |
|||
node.onMsg(ctx, msg); |
|||
|
|||
ArgumentCaptor<Runnable> successCaptor = ArgumentCaptor.forClass(Runnable.class); |
|||
ArgumentCaptor<Consumer<Throwable>> failureCaptor = ArgumentCaptor.forClass(Consumer.class); |
|||
ArgumentCaptor<TbMsg> newMsgCaptor = ArgumentCaptor.forClass(TbMsg.class); |
|||
|
|||
verify(ctx, times(1)).enqueue(any(), successCaptor.capture(), failureCaptor.capture()); |
|||
successCaptor.getValue().run(); |
|||
verify(ctx, times(1)).tellSuccess(newMsgCaptor.capture()); |
|||
|
|||
verify(ctx, times(1)).attributesDeletedActionMsg(any(), any(), anyString(), anyList()); |
|||
verify(ctx, never()).tellFailure(any(), any()); |
|||
verify(telemetryService, times(1)).deleteAndNotify(any(), any(), anyString(), anyList(), any()); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue