Browse Source

Merge pull request #6816 from thingsboard/refactoring_tests_08

[3.4]Refactoring tests 08
pull/6857/head
Andrew Shvayka 4 years ago
committed by GitHub
parent
commit
fff137b8db
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 254
      application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java
  2. 36
      application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java
  3. 123
      application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java
  4. 47
      application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java
  5. 294
      application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java
  6. 313
      application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java

254
application/src/test/java/org/thingsboard/server/controller/AbstractNotifyEntityTest.java

@ -20,9 +20,11 @@ import org.mockito.ArgumentMatcher;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.boot.test.mock.mockito.SpyBean;
import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.EdgeEventActionType;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.EntityIdFactory; import org.thingsboard.server.common.data.id.EntityIdFactory;
@ -30,9 +32,13 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent; import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent;
import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.ToDeviceActorNotificationMsg;
import org.thingsboard.server.dao.audit.AuditLogService; import org.thingsboard.server.dao.audit.AuditLogService;
import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.model.ModelConstants;
import org.thingsboard.server.service.gateway_device.GatewayNotificationsService;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
@ -49,13 +55,32 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
@SpyBean @SpyBean
protected AuditLogService auditLogService; protected AuditLogService auditLogService;
@SpyBean
protected GatewayNotificationsService gatewayNotificationsService;
protected final String msgErrorPermission = "You don't have permission to perform this operation!";
protected final String msgErrorShouldBeSpecified = "should be specified";
protected void testNotifyEntityAllOneTime(HasName entity, EntityId entityId, EntityId originatorId, protected void testNotifyEntityAllOneTime(HasName entity, EntityId entityId, EntityId originatorId,
TenantId tenantId, CustomerId customerId, UserId userId, String userName, TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, Object... additionalInfo) { ActionType actionType, Object... additionalInfo) {
int cntTime = 1; int cntTime = 1;
testSendNotificationMsgToEdgeServiceTime(entityId, tenantId, actionType, cntTime); testSendNotificationMsgToEdgeServiceTime(entityId, tenantId, actionType, cntTime);
testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo); testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo);
testPushMsgToRuleEngineTime(originatorId, tenantId, cntTime); ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService);
}
protected void testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(HasName entity, EntityId entityId, EntityId originatorId,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, Object... additionalInfo) {
int cntTime = 1;
testSendNotificationMsgToEdgeServiceTime(entityId, tenantId, actionType, cntTime);
testLogEntityActionEntityEqClass(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo);
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
} }
@ -73,7 +98,8 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
int cntTime = 1; int cntTime = 1;
testNotificationMsgToEdgeServiceNever(entityId); testNotificationMsgToEdgeServiceNever(entityId);
testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo); testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo);
testPushMsgToRuleEngineTime(originatorId, tenantId, cntTime); ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
} }
@ -86,8 +112,49 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
ArgumentMatcher<HasName> matcherEntityClassEquals = argument -> argument.getClass().equals(entity.getClass()); ArgumentMatcher<HasName> matcherEntityClassEquals = argument -> argument.getClass().equals(entity.getClass());
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.getClass().equals(originatorId.getClass()); ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.getClass().equals(originatorId.getClass());
testLogEntityActionAdditionalInfo(matcherEntityClassEquals, matcherOriginatorId, tenantId, customerId, userId, userName, actionType, cntTime, testLogEntityActionAdditionalInfo(matcherEntityClassEquals, matcherOriginatorId, tenantId, customerId, userId, userName, actionType, cntTime,
additionalInfo); extractMatcherAdditionalInfo(additionalInfo));
testPushMsgToRuleEngineTime(originatorId, tenantId, cntTime); testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService);
}
protected void testNotifyManyEntityManyTimeMsgToEdgeServiceEntityEqAny(HasName entity, HasName originator,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, ActionType actionTypeEdge,
int cntTime, int cntTimeEdge, int cntTimeRuleEngine, Object... additionalInfo) {
EntityId originatorId = createEntityId_NULL_UUID(originator);
testSendNotificationMsgToEdgeServiceTimeEntityEqAny(tenantId, actionTypeEdge, cntTimeEdge);
ArgumentMatcher<HasName> matcherEntityClassEquals = argument -> argument.getClass().equals(entity.getClass());
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.getClass().equals(originatorId.getClass());
testLogEntityActionAdditionalInfo(matcherEntityClassEquals, matcherOriginatorId, tenantId, customerId, userId, userName, actionType, cntTime,
extractMatcherAdditionalInfo(additionalInfo));
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTimeRuleEngine);
Mockito.reset(tbClusterService, auditLogService);
}
protected void testNotifyManyEntityManyTimeMsgToEdgeServiceEntityEqAnyAdditionalInfoAny(HasName entity, HasName originator,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, ActionType actionTypeEdge, int cntTime, int cntTimeEdge, int cntAdditionalInfo) {
EntityId originatorId = createEntityId_NULL_UUID(originator);
testSendNotificationMsgToEdgeServiceTimeEntityEqAny(tenantId, actionTypeEdge, cntTimeEdge);
ArgumentMatcher<HasName> matcherEntityClassEquals = argument -> argument.getClass().equals(entity.getClass());
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.getClass().equals(originatorId.getClass());
testLogEntityActionAdditionalInfoAny(matcherEntityClassEquals, matcherOriginatorId, tenantId, customerId, userId, userName, actionType, cntTime,
cntAdditionalInfo);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTimeEdge);
Mockito.reset(tbClusterService, auditLogService);
}
protected void testNotifyManyEntityManyTimeMsgToEdgeServiceNeverAdditionalInfoAny(HasName entity, HasName originator,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, int cntTime, int cntAdditionalInfo) {
EntityId entityId = createEntityId_NULL_UUID(entity);
EntityId originatorId = createEntityId_NULL_UUID(originator);
testNotificationMsgToEdgeServiceNever(entityId);
ArgumentMatcher<HasName> matcherEntityClassEquals = argument -> argument.getClass().equals(entity.getClass());
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.getClass().equals(originatorId.getClass());
testLogEntityActionAdditionalInfoAny(matcherEntityClassEquals, matcherOriginatorId, tenantId, customerId, userId, userName, actionType, cntTime,
cntAdditionalInfo);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
} }
@ -97,11 +164,24 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
int cntTime = 1; int cntTime = 1;
testNotificationMsgToEdgeServiceNever(entityId); testNotificationMsgToEdgeServiceNever(entityId);
testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo); testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo);
testPushMsgToRuleEngineTime(originatorId, tenantId, cntTime); ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testPushMsgToRuleEngineTime(matcherOriginatorId, tenantId, cntTime);
testBroadcastEntityStateChangeEventTime(entityId, tenantId, cntTime); testBroadcastEntityStateChangeEventTime(entityId, tenantId, cntTime);
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
} }
protected void testNotifyEntityMsgToEdgePushMsgToCoreOneTime(HasName entity, EntityId entityId, EntityId originatorId,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, Object... additionalInfo) {
int cntTime = 1;
testSendNotificationMsgToEdgeServiceTime(entityId, tenantId, actionType, cntTime);
testLogEntityAction(entity, originatorId, tenantId, customerId, userId, userName, actionType, cntTime, additionalInfo);
tesPushMsgToCoreTime(cntTime);
Mockito.reset(tbClusterService, auditLogService);
}
protected void testNotifyEntityEqualsOneTimeError(HasName entity, TenantId tenantId, protected void testNotifyEntityEqualsOneTimeError(HasName entity, TenantId tenantId,
UserId userId, String userName, ActionType actionType, Exception exp, UserId userId, String userName, ActionType actionType, Exception exp,
Object... additionalInfo) { Object... additionalInfo) {
@ -112,7 +192,7 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
ArgumentMatcher<Exception> matcherError = argument -> argument.getMessage().contains(exp.getMessage()) ArgumentMatcher<Exception> matcherError = argument -> argument.getMessage().contains(exp.getMessage())
& argument.getClass().equals(exp.getClass()); & argument.getClass().equals(exp.getClass());
testLogEntityActionErrorAdditionalInfo(matcherEntityEquals, entity_originator_NULL_UUID, tenantId, customer_NULL_UUID, userId, testLogEntityActionErrorAdditionalInfo(matcherEntityEquals, entity_originator_NULL_UUID, tenantId, customer_NULL_UUID, userId,
userName, actionType, 1, matcherError, additionalInfo); userName, actionType, 1, matcherError, extractMatcherAdditionalInfo(additionalInfo));
testPushMsgToRuleEngineNever(entity_originator_NULL_UUID); testPushMsgToRuleEngineNever(entity_originator_NULL_UUID);
} }
@ -126,7 +206,7 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
ArgumentMatcher<Exception> matcherError = argument -> argument.getMessage().contains(exp.getMessage()) & ArgumentMatcher<Exception> matcherError = argument -> argument.getMessage().contains(exp.getMessage()) &
argument.getClass().equals(exp.getClass()); argument.getClass().equals(exp.getClass());
testLogEntityActionErrorAdditionalInfo(matcherEntityIsNull, entity_originator_NULL_UUID, tenantId, customer_NULL_UUID, testLogEntityActionErrorAdditionalInfo(matcherEntityIsNull, entity_originator_NULL_UUID, tenantId, customer_NULL_UUID,
userId, userName, actionType, 1, matcherError, additionalInfo); userId, userName, actionType, 1, matcherError, extractMatcherAdditionalInfo(additionalInfo));
testPushMsgToRuleEngineNever(entity_originator_NULL_UUID); testPushMsgToRuleEngineNever(entity_originator_NULL_UUID);
} }
@ -138,6 +218,26 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
} }
protected void testNotificationUpdateGatewayOneTime(Device device, Device oldDevice) {
Mockito.verify(gatewayNotificationsService, times(1)).onDeviceUpdated(Mockito.eq(device), Mockito.eq(oldDevice));
}
protected void testNotificationUpdateGatewayTime(int cntTimes) {
Mockito.verify(gatewayNotificationsService, times(cntTimes)).onDeviceUpdated(Mockito.any(Device.class), Mockito.isNull());
}
protected void testNotificationUpdateGatewayNever() {
Mockito.verify(gatewayNotificationsService, never()).onDeviceUpdated(Mockito.any(Device.class), Mockito.any(Device.class));
}
protected void testNotificationDeleteGatewayOneTime(Device device) {
Mockito.verify(gatewayNotificationsService, times(1)).onDeviceDeleted(device);
}
protected void testNotificationDeleteGatewayNever() {
Mockito.verify(gatewayNotificationsService, never()).onDeviceDeleted(Mockito.any(Device.class));
}
private void testNotificationMsgToEdgeServiceNever(EntityId entityId) { private void testNotificationMsgToEdgeServiceNever(EntityId entityId) {
Mockito.verify(tbClusterService, never()).sendNotificationMsgToEdge(Mockito.any(), Mockito.verify(tbClusterService, never()).sendNotificationMsgToEdge(Mockito.any(),
Mockito.any(), Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any(), Mockito.any()); Mockito.any(), Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any(), Mockito.any());
@ -154,16 +254,22 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any()); Mockito.any(entityId.getClass()), Mockito.any(), Mockito.any());
} }
private void testPushMsgToRuleEngineTime(EntityId originatorId, TenantId tenantId, int cntTime) { private void testPushMsgToRuleEngineTime(ArgumentMatcher<EntityId> matcherOriginatorId, TenantId tenantId, int cntTime) {
ArgumentMatcher<EntityId> matcherOriginatorId = cntTime == 1 ? argument -> argument.equals(originatorId) :
argument -> argument.getClass().equals(originatorId.getClass());
Mockito.verify(tbClusterService, times(cntTime)).pushMsgToRuleEngine(Mockito.eq(tenantId), Mockito.verify(tbClusterService, times(cntTime)).pushMsgToRuleEngine(Mockito.eq(tenantId),
Mockito.argThat(matcherOriginatorId), Mockito.any(TbMsg.class), Mockito.isNull()); Mockito.argThat(matcherOriginatorId), Mockito.any(TbMsg.class), Mockito.isNull());
} }
private void testSendNotificationMsgToEdgeServiceTime(EntityId entityId, TenantId tenantId, ActionType actionType, int cntTime) { private void testSendNotificationMsgToEdgeServiceTime(EntityId entityId, TenantId tenantId, ActionType actionType, int cntTime) {
EdgeEventActionType edgeEventActionType = ActionType.CREDENTIALS_UPDATED.equals(actionType) ?
EdgeEventActionType.CREDENTIALS_UPDATED : edgeTypeByActionType(actionType);
Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId), Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId),
Mockito.any(), Mockito.eq(entityId), Mockito.any(), Mockito.isNull(), Mockito.any(), Mockito.eq(entityId), Mockito.any(), Mockito.isNull(),
Mockito.eq(edgeEventActionType));
}
private void testSendNotificationMsgToEdgeServiceTimeEntityEqAny(TenantId tenantId, ActionType actionType, int cntTime) {
Mockito.verify(tbClusterService, times(cntTime)).sendNotificationMsgToEdge(Mockito.eq(tenantId),
Mockito.any(), Mockito.any(EntityId.class), Mockito.any(), Mockito.isNull(),
Mockito.eq(edgeTypeByActionType(actionType))); Mockito.eq(edgeTypeByActionType(actionType)));
} }
@ -172,19 +278,88 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.any(entityId.getClass()), Mockito.any(ComponentLifecycleEvent.class)); Mockito.any(entityId.getClass()), Mockito.any(ComponentLifecycleEvent.class));
} }
private void tesPushMsgToCoreTime(int cntTime) {
Mockito.verify(tbClusterService, times(cntTime)).pushMsgToCore(Mockito.any(ToDeviceActorNotificationMsg.class), Mockito.isNull());
}
private void testLogEntityAction(HasName entity, EntityId originatorId, TenantId tenantId, private void testLogEntityAction(HasName entity, EntityId originatorId, TenantId tenantId,
CustomerId customerId, UserId userId, String userName, CustomerId customerId, UserId userId, String userName,
ActionType actionType, int cntTime, Object... additionalInfo) { ActionType actionType, int cntTime, Object... additionalInfo) {
ArgumentMatcher<HasName> matcherEntityEquals = argument -> argument.equals(entity); ArgumentMatcher<HasName> matcherEntityEquals = argument -> argument.equals(entity);
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId); ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testLogEntityActionAdditionalInfo(matcherEntityEquals, matcherOriginatorId, tenantId, customerId, userId, userName, testLogEntityActionAdditionalInfo(matcherEntityEquals, matcherOriginatorId, tenantId, customerId, userId, userName,
actionType, cntTime, additionalInfo); actionType, cntTime, extractMatcherAdditionalInfo(additionalInfo));
}
private void testLogEntityActionEntityEqClass(HasName entity, EntityId originatorId, TenantId tenantId,
CustomerId customerId, UserId userId, String userName,
ActionType actionType, int cntTime, Object... additionalInfo) {
ArgumentMatcher<HasName> matcherEntityEquals = argument -> argument.getClass().equals(entity.getClass());
ArgumentMatcher<EntityId> matcherOriginatorId = argument -> argument.equals(originatorId);
testLogEntityActionAdditionalInfo(matcherEntityEquals, matcherOriginatorId, tenantId, customerId, userId, userName,
actionType, cntTime, extractMatcherAdditionalInfo(additionalInfo));
} }
private void testLogEntityActionAdditionalInfo(ArgumentMatcher<HasName> matcherEntity, ArgumentMatcher<EntityId> matcherOriginatorId, private void testLogEntityActionAdditionalInfo(ArgumentMatcher<HasName> matcherEntity, ArgumentMatcher<EntityId> matcherOriginatorId,
TenantId tenantId, CustomerId customerId, UserId userId, String userName, TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, int cntTime, Object... additionalInfo) { ActionType actionType, int cntTime, List<ArgumentMatcher<Object>> matcherAdditionalInfos) {
switch (additionalInfo.length) { switch (matcherAdditionalInfos.size()) {
case 1:
Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId),
Mockito.eq(customerId),
Mockito.eq(userId),
Mockito.eq(userName),
Mockito.argThat(matcherOriginatorId),
Mockito.argThat(matcherEntity),
Mockito.eq(actionType),
Mockito.isNull(),
Mockito.argThat(matcherAdditionalInfos.get(0)));
break;
case 2:
Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId),
Mockito.eq(customerId),
Mockito.eq(userId),
Mockito.eq(userName),
Mockito.argThat(matcherOriginatorId),
Mockito.argThat(matcherEntity),
Mockito.eq(actionType),
Mockito.isNull(),
Mockito.argThat(matcherAdditionalInfos.get(0)),
Mockito.argThat(matcherAdditionalInfos.get(1)));
break;
case 3:
Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId),
Mockito.eq(customerId),
Mockito.eq(userId),
Mockito.eq(userName),
Mockito.argThat(matcherOriginatorId),
Mockito.argThat(matcherEntity),
Mockito.eq(actionType),
Mockito.isNull(),
Mockito.argThat(matcherAdditionalInfos.get(0)),
Mockito.argThat(matcherAdditionalInfos.get(1)),
Mockito.argThat(matcherAdditionalInfos.get(2)));
break;
default:
Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId),
Mockito.eq(customerId),
Mockito.eq(userId),
Mockito.eq(userName),
Mockito.argThat(matcherOriginatorId),
Mockito.argThat(matcherEntity),
Mockito.eq(actionType),
Mockito.isNull());
}
}
private void testLogEntityActionAdditionalInfoAny(ArgumentMatcher<HasName> matcherEntity, ArgumentMatcher<EntityId> matcherOriginatorId,
TenantId tenantId, CustomerId customerId, UserId userId, String userName,
ActionType actionType, int cntTime, int cntAdditionalInfo) {
switch (cntAdditionalInfo) {
case 1: case 1:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId), .logEntityAction(Mockito.eq(tenantId),
@ -195,7 +370,7 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.isNull(), Mockito.isNull(),
Mockito.eq(extractParameter(String.class, 0, additionalInfo))); Mockito.anyString());
break; break;
case 2: case 2:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
@ -207,8 +382,8 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.isNull(), Mockito.isNull(),
Mockito.eq(extractParameter(String.class, 0, additionalInfo)), Mockito.anyString(),
Mockito.eq(extractParameter(String.class, 1, additionalInfo))); Mockito.anyString());
break; break;
case 3: case 3:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
@ -220,9 +395,9 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.isNull(), Mockito.isNull(),
Mockito.eq(extractParameter(String.class, 0, additionalInfo)), Mockito.anyString(),
Mockito.eq(extractParameter(String.class, 1, additionalInfo)), Mockito.anyString(),
Mockito.eq(extractParameter(String.class, 2, additionalInfo))); Mockito.anyString());
break; break;
default: default:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
@ -239,8 +414,9 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
private void testLogEntityActionErrorAdditionalInfo(ArgumentMatcher<HasName> matcherEntity, EntityId originatorId, TenantId tenantId, private void testLogEntityActionErrorAdditionalInfo(ArgumentMatcher<HasName> matcherEntity, EntityId originatorId, TenantId tenantId,
CustomerId customerId, UserId userId, String userName, ActionType actionType, CustomerId customerId, UserId userId, String userName, ActionType actionType,
int cntTime, ArgumentMatcher<Exception> matcherError, Object... additionalInfo) { int cntTime, ArgumentMatcher<Exception> matcherError,
switch (additionalInfo.length) { List<ArgumentMatcher<Object>> matcherAdditionalInfos) {
switch (matcherAdditionalInfos.size()) {
case 1: case 1:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId), .logEntityAction(Mockito.eq(tenantId),
@ -251,7 +427,7 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.argThat(matcherError), Mockito.argThat(matcherError),
Mockito.eq(extractParameter(String.class, 0, additionalInfo))); Mockito.argThat(matcherAdditionalInfos.get(0)));
break; break;
case 2: case 2:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
@ -263,9 +439,9 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.argThat(matcherError), Mockito.argThat(matcherError),
Mockito.eq(extractParameter(String.class, 0, additionalInfo)), Mockito.argThat(Mockito.eq(matcherAdditionalInfos.get(0))),
Mockito.eq(extractParameter(String.class, 1, additionalInfo))); Mockito.argThat(Mockito.eq(matcherAdditionalInfos.get(1))));
case 3: case 3:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
.logEntityAction(Mockito.eq(tenantId), .logEntityAction(Mockito.eq(tenantId),
Mockito.eq(customerId), Mockito.eq(customerId),
@ -275,9 +451,9 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
Mockito.argThat(matcherEntity), Mockito.argThat(matcherEntity),
Mockito.eq(actionType), Mockito.eq(actionType),
Mockito.argThat(matcherError), Mockito.argThat(matcherError),
Mockito.eq(extractParameter(String.class, 0, additionalInfo)), Mockito.argThat(Mockito.eq(matcherAdditionalInfos.get(0))),
Mockito.eq(extractParameter(String.class, 1, additionalInfo)), Mockito.argThat(Mockito.eq(matcherAdditionalInfos.get(1))),
Mockito.eq(extractParameter(String.class, 3, additionalInfo))); Mockito.argThat(Mockito.eq(matcherAdditionalInfos.get(2))));
break; break;
default: default:
Mockito.verify(auditLogService, times(cntTime)) Mockito.verify(auditLogService, times(cntTime))
@ -292,10 +468,18 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
} }
} }
private <T> T extractParameter(Class<T> clazz, int index, Object... additionalInfo) { private List<ArgumentMatcher<Object>> extractMatcherAdditionalInfo(Object... additionalInfos) {
List<ArgumentMatcher<Object>> matcherAdditionalInfos = new ArrayList<>(additionalInfos.length);
for (Object additionalInfo : additionalInfos) {
matcherAdditionalInfos.add(argument -> argument.equals(extractParameter(additionalInfo.getClass(), additionalInfo)));
}
return matcherAdditionalInfos;
}
private <T> T extractParameter(Class<T> clazz, Object additionalInfo) {
T result = null; T result = null;
if (additionalInfo != null && additionalInfo.length > index) { if (additionalInfo != null) {
Object paramObject = additionalInfo[index]; Object paramObject = additionalInfo;
if (clazz.isInstance(paramObject)) { if (clazz.isInstance(paramObject)) {
result = clazz.cast(paramObject); result = clazz.cast(paramObject);
} }
@ -308,4 +492,12 @@ public abstract class AbstractNotifyEntityTest extends AbstractWebTest {
.substring(entity.getClass().toString().lastIndexOf(".") + 1).toUpperCase(Locale.ENGLISH)), .substring(entity.getClass().toString().lastIndexOf(".") + 1).toUpperCase(Locale.ENGLISH)),
ModelConstants.NULL_UUID); ModelConstants.NULL_UUID);
} }
protected String msgErrorFieldLength(String fieldName){
return "length of " + fieldName + " must be equal or less than 255";
}
protected String msgErrorNoFound(String entityClassName, String assetIdStr){
return entityClassName + " with id [" + assetIdStr + "] is not found";
}
} }

36
application/src/test/java/org/thingsboard/server/controller/BaseAlarmControllerTest.java

@ -36,6 +36,7 @@ import org.thingsboard.server.common.data.page.PageData;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@Slf4j @Slf4j
@ -132,7 +133,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm", alarm).andExpect(status().isForbidden()); doPost("/api/alarm", alarm)
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -147,7 +150,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm", alarm).andExpect(status().isForbidden()); doPost("/api/alarm", alarm)
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -187,7 +192,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isForbidden()); doDelete("/api/alarm/" + alarm.getId())
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -201,7 +208,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doDelete("/api/alarm/" + alarm.getId()).andExpect(status().isForbidden()); doDelete("/api/alarm/" + alarm.getId())
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -265,7 +274,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isForbidden()); doPost("/api/alarm/" + alarm.getId() + "/clear")
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -279,7 +290,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm/" + alarm.getId() + "/clear").andExpect(status().isForbidden()); doPost("/api/alarm/" + alarm.getId() + "/clear")
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -293,7 +306,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm/" + alarm.getId() + "/ack").andExpect(status().isForbidden()); doPost("/api/alarm/" + alarm.getId() + "/ack")
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(alarm.getId(), alarm); testNotifyEntityNever(alarm.getId(), alarm);
} }
@ -307,7 +322,9 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/alarm/" + alarm.getId() + "/ack").andExpect(status().isForbidden()); doPost("/api/alarm/" + alarm.getId() + "/ack")
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
} }
@Test @Test
@ -355,7 +372,8 @@ public abstract class BaseAlarmControllerTest extends AbstractControllerTest {
loginDifferentCustomer(); loginDifferentCustomer();
doGet("/api/alarm/" + EntityType.DEVICE + "/" doGet("/api/alarm/" + EntityType.DEVICE + "/"
+ customerDevice.getUuidId() + "?page=0&pageSize=" + size) + customerDevice.getUuidId() + "?page=0&pageSize=" + size)
.andExpect(status().isForbidden()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
} }
@Test @Test

123
application/src/test/java/org/thingsboard/server/controller/BaseAssetControllerTest.java

@ -122,9 +122,10 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "length of name must be equal or less than 255"; String msgError = msgErrorFieldLength("name");
doPost("/api/asset", asset).andExpect(statusReason(containsString(msgError))); doPost("/api/asset", asset)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(), testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -132,8 +133,10 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
asset.setName("Normal name"); asset.setName("Normal name");
asset.setType(RandomStringUtils.randomAlphabetic(300)); asset.setType(RandomStringUtils.randomAlphabetic(300));
msgError = "length of type must be equal or less than 255"; msgError = msgErrorFieldLength("type");
doPost("/api/asset", asset).andExpect(statusReason(containsString(msgError))); doPost("/api/asset", asset)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(), testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -141,8 +144,10 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
asset.setType("default"); asset.setType("default");
asset.setLabel(RandomStringUtils.randomAlphabetic(300)); asset.setLabel(RandomStringUtils.randomAlphabetic(300));
msgError = "length of label must be equal or less than 255"; msgError = msgErrorFieldLength("label");
doPost("/api/asset", asset).andExpect(statusReason(containsString(msgError))); doPost("/api/asset", asset)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(), testNotifyEntityEqualsOneTimeError(asset, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -159,12 +164,15 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doPost("/api/asset", savedAsset, Asset.class, status().isForbidden()); doPost("/api/asset", savedAsset)
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(savedAsset.getId(), savedAsset); testNotifyEntityNever(savedAsset.getId(), savedAsset);
doDelete("/api/asset" + savedAsset.getId().getId().toString()) doDelete("/api/asset/" + savedAsset.getId().getId().toString())
.andExpect(status().isNotFound()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(savedAsset.getId(), savedAsset); testNotifyEntityNever(savedAsset.getId(), savedAsset);
@ -239,8 +247,10 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.DELETED, savedAsset.getId().getId().toString()); ActionType.DELETED, savedAsset.getId().getId().toString());
doGet("/api/asset/" + savedAsset.getId().getId().toString()) String assetIdStr = savedAsset.getId().getId().toString();
.andExpect(status().isNotFound()); doGet("/api/asset/" + assetIdStr)
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Asset", assetIdStr))));
} }
@Test @Test
@ -264,12 +274,12 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
doDelete("/api/asset/" + savedAsset1.getId().getId().toString())
.andExpect(status().isBadRequest());
String msgError = "Can't delete asset that has entity views"; String msgError = "Can't delete asset that has entity views";
doDelete("/api/asset/" + savedAsset1.getId().getId().toString())
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityIsNullOneTimeError(savedAsset1, savedTenant.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), testNotifyEntityIsNullOneTimeError(savedAsset1, savedTenant.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.DELETED, new DataValidationException(msgError), savedAsset1.getId().getId().toString()); ActionType.DELETED, new DataValidationException(msgError), savedAsset1.getId().getId().toString());
savedView.setEntityId(savedAsset2.getId()); savedView.setEntityId(savedAsset2.getId());
@ -279,8 +289,10 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
doDelete("/api/asset/" + savedAsset1.getId().getId().toString()) doDelete("/api/asset/" + savedAsset1.getId().getId().toString())
.andExpect(status().isOk()); .andExpect(status().isOk());
doGet("/api/asset/" + savedAsset1.getId().getId().toString()) String assetIdStr = savedAsset1.getId().getId().toString();
.andExpect(status().isNotFound()); doGet("/api/asset/" + assetIdStr)
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Asset", assetIdStr))));
} }
@Test @Test
@ -290,7 +302,7 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "Asset type should be specified"; String msgError = "Asset type " + msgErrorShouldBeSpecified;
doPost("/api/asset", asset) doPost("/api/asset", asset)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError))); .andExpect(statusReason(containsString(msgError)));
@ -306,7 +318,7 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "Asset name should be specified"; String msgError = "Asset name " + msgErrorShouldBeSpecified;
doPost("/api/asset", asset) doPost("/api/asset", asset)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError))); .andExpect(statusReason(containsString(msgError)));
@ -362,10 +374,11 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "Asset name should be specified"; String customerIdStr = Uuids.timeBased().toString();
doPost("/api/customer/" + Uuids.timeBased().toString() doPost("/api/customer/" + customerIdStr
+ "/asset/" + savedAsset.getId().getId().toString()) + "/asset/" + savedAsset.getId().getId().toString())
.andExpect(status().isNotFound()); .andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Customer", customerIdStr))));
testNotifyEntityNever(asset.getId(), asset); testNotifyEntityNever(asset.getId(), asset);
} }
@ -401,9 +414,11 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "You don't have permission to perform this operation!";
doPost("/api/customer/" + savedCustomer.getId().getId().toString() doPost("/api/customer/" + savedCustomer.getId().getId().toString()
+ "/asset/" + savedAsset.getId().getId().toString()) + "/asset/" + savedAsset.getId().getId().toString())
.andExpect(status().isForbidden()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityNever(savedAsset.getId(), savedAsset); testNotifyEntityNever(savedAsset.getId(), savedAsset);
@ -431,7 +446,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/assets?", pageData = doGetTypedWithPageLink("/api/tenant/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssets.addAll(pageData.getData()); loadedAssets.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -480,7 +496,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/assets?", pageData = doGetTypedWithPageLink("/api/tenant/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssetsTitle1.addAll(pageData.getData()); loadedAssetsTitle1.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -496,7 +513,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/assets?", pageData = doGetTypedWithPageLink("/api/tenant/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssetsTitle2.addAll(pageData.getData()); loadedAssetsTitle2.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -515,7 +533,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title1); pageLink = new PageLink(4, 0, title1);
pageData = doGetTypedWithPageLink("/api/tenant/assets?", pageData = doGetTypedWithPageLink("/api/tenant/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
@ -526,7 +545,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
pageData = doGetTypedWithPageLink("/api/tenant/assets?", pageData = doGetTypedWithPageLink("/api/tenant/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }
@ -563,7 +583,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type1); new TypeReference<PageData<Asset>>() {
}, pageLink, type1);
loadedAssetsType1.addAll(pageData.getData()); loadedAssetsType1.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -579,7 +600,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type2); new TypeReference<PageData<Asset>>() {
}, pageLink, type2);
loadedAssetsType2.addAll(pageData.getData()); loadedAssetsType2.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -598,7 +620,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type1); new TypeReference<PageData<Asset>>() {
}, pageLink, type1);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
@ -609,7 +632,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/tenant/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type2); new TypeReference<PageData<Asset>>() {
}, pageLink, type2);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }
@ -636,7 +660,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssets.addAll(pageData.getData()); loadedAssets.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -688,7 +713,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssetsTitle1.addAll(pageData.getData()); loadedAssetsTitle1.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -704,7 +730,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
loadedAssetsTitle2.addAll(pageData.getData()); loadedAssetsTitle2.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -723,7 +750,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title1); pageLink = new PageLink(4, 0, title1);
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
@ -734,7 +762,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>(){}, pageLink); new TypeReference<PageData<Asset>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }
@ -780,7 +809,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = null; PageData<Asset> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type1); new TypeReference<PageData<Asset>>() {
}, pageLink, type1);
loadedAssetsType1.addAll(pageData.getData()); loadedAssetsType1.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -796,7 +826,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type2); new TypeReference<PageData<Asset>>() {
}, pageLink, type2);
loadedAssetsType2.addAll(pageData.getData()); loadedAssetsType2.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -815,7 +846,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type1); new TypeReference<PageData<Asset>>() {
}, pageLink, type1);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
@ -826,7 +858,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
pageLink = new PageLink(4); pageLink = new PageLink(4);
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/assets?type={type}&",
new TypeReference<PageData<Asset>>(){}, pageLink, type2); new TypeReference<PageData<Asset>>() {
}, pageLink, type2);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }
@ -852,7 +885,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
PageData<Asset> pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/assets?", PageData<Asset> pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>() {}, new PageLink(100)); new TypeReference<PageData<Asset>>() {
}, new PageLink(100));
Assert.assertEquals(1, pageData.getData().size()); Assert.assertEquals(1, pageData.getData().size());
@ -867,7 +901,8 @@ public abstract class BaseAssetControllerTest extends AbstractControllerTest {
ActionType.UNASSIGNED_FROM_EDGE, savedAsset.getId().getId().toString(), savedEdge.getId().getId().toString(), savedEdge.getName()); ActionType.UNASSIGNED_FROM_EDGE, savedAsset.getId().getId().toString(), savedEdge.getId().getId().toString(), savedEdge.getName());
pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/assets?", pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/assets?",
new TypeReference<PageData<Asset>>() {}, new PageLink(100)); new TypeReference<PageData<Asset>>() {
}, new PageLink(100));
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }

47
application/src/test/java/org/thingsboard/server/controller/BaseCustomerControllerTest.java

@ -126,8 +126,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);
String msgError = "length of title must be equal or less than 255"; String msgError = msgErrorFieldLength("title");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
customer.setTenantId(savedTenant.getId()); customer.setTenantId(savedTenant.getId());
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
@ -136,8 +138,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
customer.setTitle("Normal title"); customer.setTitle("Normal title");
customer.setCity(RandomStringUtils.randomAlphabetic(300)); customer.setCity(RandomStringUtils.randomAlphabetic(300));
msgError = "length of city must be equal or less than 255"; msgError = msgErrorFieldLength("city");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -145,8 +149,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
customer.setCity("Normal city"); customer.setCity("Normal city");
customer.setCountry(RandomStringUtils.randomAlphabetic(300)); customer.setCountry(RandomStringUtils.randomAlphabetic(300));
msgError = "length of country must be equal or less than 255"; msgError = msgErrorFieldLength("country");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -154,8 +160,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
customer.setCountry("Ukraine"); customer.setCountry("Ukraine");
customer.setPhone(RandomStringUtils.randomAlphabetic(300)); customer.setPhone(RandomStringUtils.randomAlphabetic(300));
msgError = "length of phone must be equal or less than 255"; msgError = msgErrorFieldLength("phone");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -163,8 +171,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
customer.setPhone("+3892555554512"); customer.setPhone("+3892555554512");
customer.setState(RandomStringUtils.randomAlphabetic(300)); customer.setState(RandomStringUtils.randomAlphabetic(300));
msgError = "length of state must be equal or less than 255"; msgError = msgErrorFieldLength("state");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -172,8 +182,10 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
customer.setState("Normal state"); customer.setState("Normal state");
customer.setZip(RandomStringUtils.randomAlphabetic(300)); customer.setZip(RandomStringUtils.randomAlphabetic(300));
msgError = "length of zip or postal code must be equal or less than 255"; msgError = msgErrorFieldLength("zip or postal code");
doPost("/api/customer", customer).andExpect(statusReason(containsString(msgError))); doPost("/api/customer", customer)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(), testNotifyEntityEqualsOneTimeError(customer,savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError)); tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
@ -195,7 +207,8 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
testNotifyEntityNever(savedCustomer.getId(), savedCustomer); testNotifyEntityNever(savedCustomer.getId(), savedCustomer);
doDelete("/api/customer/" + savedCustomer.getId().getId().toString()) doDelete("/api/customer/" + savedCustomer.getId().getId().toString())
.andExpect(status().isForbidden()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(savedCustomer.getId(), savedCustomer); testNotifyEntityNever(savedCustomer.getId(), savedCustomer);
@ -241,14 +254,16 @@ public abstract class BaseCustomerControllerTest extends AbstractControllerTest
savedCustomer.getId(), savedCustomer.getTenantId(), savedCustomer.getId(), tenantAdmin.getId(), savedCustomer.getId(), savedCustomer.getTenantId(), savedCustomer.getId(), tenantAdmin.getId(),
tenantAdmin.getEmail(), ActionType.DELETED, savedCustomer.getId().getId().toString()); tenantAdmin.getEmail(), ActionType.DELETED, savedCustomer.getId().getId().toString());
doGet("/api/customer/" + savedCustomer.getId().getId().toString()) String customerIdStr = savedCustomer.getId().getId().toString();
.andExpect(status().isNotFound()); doGet("/api/customer/" + customerIdStr)
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Customer", customerIdStr))));
} }
@Test @Test
public void testSaveCustomerWithEmptyTitle() throws Exception { public void testSaveCustomerWithEmptyTitle() throws Exception {
Customer customer = new Customer(); Customer customer = new Customer();
String msgError = "Customer title should be specified"; String msgError = "Customer title " + msgErrorShouldBeSpecified;
Mockito.reset(tbClusterService, auditLogService); Mockito.reset(tbClusterService, auditLogService);

294
application/src/test/java/org/thingsboard/server/controller/BaseDashboardControllerTest.java

@ -22,16 +22,19 @@ import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.exception.DataValidationException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -41,54 +44,66 @@ import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public abstract class BaseDashboardControllerTest extends AbstractControllerTest { public abstract class BaseDashboardControllerTest extends AbstractControllerTest {
private IdComparator<DashboardInfo> idComparator = new IdComparator<>(); private IdComparator<DashboardInfo> idComparator = new IdComparator<>();
private Tenant savedTenant; private Tenant savedTenant;
private User tenantAdmin; private User tenantAdmin;
@Before @Before
public void beforeTest() throws Exception { public void beforeTest() throws Exception {
loginSysAdmin(); loginSysAdmin();
Tenant tenant = new Tenant(); Tenant tenant = new Tenant();
tenant.setTitle("My tenant"); tenant.setTitle("My tenant");
savedTenant = doPost("/api/tenant", tenant, Tenant.class); savedTenant = doPost("/api/tenant", tenant, Tenant.class);
Assert.assertNotNull(savedTenant); Assert.assertNotNull(savedTenant);
tenantAdmin = new User(); tenantAdmin = new User();
tenantAdmin.setAuthority(Authority.TENANT_ADMIN); tenantAdmin.setAuthority(Authority.TENANT_ADMIN);
tenantAdmin.setTenantId(savedTenant.getId()); tenantAdmin.setTenantId(savedTenant.getId());
tenantAdmin.setEmail("tenant2@thingsboard.org"); tenantAdmin.setEmail("tenant2@thingsboard.org");
tenantAdmin.setFirstName("Joe"); tenantAdmin.setFirstName("Joe");
tenantAdmin.setLastName("Downs"); tenantAdmin.setLastName("Downs");
tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1"); tenantAdmin = createUserAndLogin(tenantAdmin, "testPassword1");
} }
@After @After
public void afterTest() throws Exception { public void afterTest() throws Exception {
loginSysAdmin(); loginSysAdmin();
doDelete("/api/tenant/"+savedTenant.getId().getId().toString()) doDelete("/api/tenant/" + savedTenant.getId().getId().toString())
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
@Test @Test
public void testSaveDashboard() throws Exception { public void testSaveDashboard() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Mockito.reset(tbClusterService, auditLogService);
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
testNotifyEntityOneTimeMsgToEdgeServiceNever(savedDashboard, savedDashboard.getId(), savedDashboard.getId(), savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED);
Assert.assertNotNull(savedDashboard); Assert.assertNotNull(savedDashboard);
Assert.assertNotNull(savedDashboard.getId()); Assert.assertNotNull(savedDashboard.getId());
Assert.assertTrue(savedDashboard.getCreatedTime() > 0); Assert.assertTrue(savedDashboard.getCreatedTime() > 0);
Assert.assertEquals(savedTenant.getId(), savedDashboard.getTenantId()); Assert.assertEquals(savedTenant.getId(), savedDashboard.getTenantId());
Assert.assertEquals(dashboard.getTitle(), savedDashboard.getTitle()); Assert.assertEquals(dashboard.getTitle(), savedDashboard.getTitle());
savedDashboard.setTitle("My new dashboard"); savedDashboard.setTitle("My new dashboard");
Mockito.reset(tbClusterService, auditLogService);
doPost("/api/dashboard", savedDashboard, Dashboard.class); doPost("/api/dashboard", savedDashboard, Dashboard.class);
testNotifyEntityAllOneTime(savedDashboard, savedDashboard.getId(), savedDashboard.getId(), savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.UPDATED);
Dashboard foundDashboard = doGet("/api/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); Dashboard foundDashboard = doGet("/api/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
Assert.assertEquals(foundDashboard.getTitle(), savedDashboard.getTitle()); Assert.assertEquals(foundDashboard.getTitle(), savedDashboard.getTitle());
} }
@ -97,7 +112,18 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
public void testSaveDashboardInfoWithViolationOfValidation() throws Exception { public void testSaveDashboardInfoWithViolationOfValidation() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle(RandomStringUtils.randomAlphabetic(300)); dashboard.setTitle(RandomStringUtils.randomAlphabetic(300));
doPost("/api/dashboard", dashboard).andExpect(statusReason(containsString("length of title must be equal or less than 255"))); String msgError = msgErrorFieldLength("title");
Mockito.reset(tbClusterService, auditLogService);
doPost("/api/dashboard", dashboard)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
dashboard.setTenantId(savedTenant.getId());
testNotifyEntityEqualsOneTimeError(dashboard, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
Mockito.reset(tbClusterService, auditLogService);
} }
@Test @Test
@ -107,10 +133,16 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
loginDifferentTenant(); loginDifferentTenant();
Mockito.reset(tbClusterService, auditLogService);
doPost("/api/dashboard", savedDashboard, Dashboard.class, status().isForbidden()); doPost("/api/dashboard", savedDashboard, Dashboard.class, status().isForbidden());
testNotifyEntityNever(savedDashboard.getId(), savedDashboard);
deleteDifferentTenant(); deleteDifferentTenant();
} }
@Test @Test
public void testFindDashboardById() throws Exception { public void testFindDashboardById() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
@ -120,48 +152,74 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
Assert.assertNotNull(foundDashboard); Assert.assertNotNull(foundDashboard);
Assert.assertEquals(savedDashboard, foundDashboard); Assert.assertEquals(savedDashboard, foundDashboard);
} }
@Test @Test
public void testDeleteDashboard() throws Exception { public void testDeleteDashboard() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
doDelete("/api/dashboard/"+savedDashboard.getId().getId().toString())
.andExpect(status().isOk());
doGet("/api/dashboard/"+savedDashboard.getId().getId().toString()) Mockito.reset(tbClusterService, auditLogService);
.andExpect(status().isNotFound());
doDelete("/api/dashboard/" + savedDashboard.getId().getId().toString()).andExpect(status().isOk());
testNotifyEntityOneTimeMsgToEdgeServiceNever(savedDashboard, savedDashboard.getId(), savedDashboard.getId(),
savedDashboard.getTenantId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.DELETED,
savedDashboard.getId().getId().toString());
String dashboardIdStr = savedDashboard.getId().getId().toString();
doGet("/api/dashboard/" + savedDashboard.getId().getId().toString())
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Dashboard", dashboardIdStr))));
} }
@Test @Test
public void testSaveDashboardWithEmptyTitle() throws Exception { public void testSaveDashboardWithEmptyTitle() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
String msgError = "Dashboard title " + msgErrorShouldBeSpecified;;
Mockito.reset(tbClusterService, auditLogService);
doPost("/api/dashboard", dashboard) doPost("/api/dashboard", dashboard)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Dashboard title should be specified"))); .andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(dashboard, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
} }
@Test @Test
public void testAssignUnassignDashboardToCustomer() throws Exception { public void testAssignUnassignDashboardToCustomer() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
Customer customer = new Customer(); Customer customer = new Customer();
customer.setTitle("My customer"); customer.setTitle("My customer");
Customer savedCustomer = doPost("/api/customer", customer, Customer.class); Customer savedCustomer = doPost("/api/customer", customer, Customer.class);
Dashboard assignedDashboard = doPost("/api/customer/" + savedCustomer.getId().getId().toString() Mockito.reset(tbClusterService, auditLogService);
Dashboard assignedDashboard = doPost("/api/customer/" + savedCustomer.getId().getId().toString()
+ "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
Assert.assertTrue(assignedDashboard.getAssignedCustomers().contains(savedCustomer.toShortCustomerInfo())); Assert.assertTrue(assignedDashboard.getAssignedCustomers().contains(savedCustomer.toShortCustomerInfo()));
testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(assignedDashboard, assignedDashboard.getId(), assignedDashboard.getId(),
savedTenant.getId(), savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ASSIGNED_TO_CUSTOMER,
savedDashboard.getId().getId().toString(), savedCustomer.getId().getId().toString(), savedCustomer.getTitle());
Dashboard foundDashboard = doGet("/api/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); Dashboard foundDashboard = doGet("/api/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
Assert.assertTrue(foundDashboard.getAssignedCustomers().contains(savedCustomer.toShortCustomerInfo())); Assert.assertTrue(foundDashboard.getAssignedCustomers().contains(savedCustomer.toShortCustomerInfo()));
Dashboard unassignedDashboard = Mockito.reset(tbClusterService, auditLogService);
doDelete("/api/customer/"+savedCustomer.getId().getId().toString()+"/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
Dashboard unassignedDashboard =
doDelete("/api/customer/" + savedCustomer.getId().getId().toString() + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(assignedDashboard, assignedDashboard.getId(), assignedDashboard.getId(),
savedTenant.getId(), savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.UNASSIGNED_FROM_CUSTOMER,
savedDashboard.getId().getId().toString(), savedCustomer.getId().getId().toString(), savedCustomer.getTitle());
Assert.assertTrue(unassignedDashboard.getAssignedCustomers() == null || unassignedDashboard.getAssignedCustomers().isEmpty()); Assert.assertTrue(unassignedDashboard.getAssignedCustomers() == null || unassignedDashboard.getAssignedCustomers().isEmpty());
@ -169,22 +227,27 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
Assert.assertTrue(foundDashboard.getAssignedCustomers() == null || foundDashboard.getAssignedCustomers().isEmpty()); Assert.assertTrue(foundDashboard.getAssignedCustomers() == null || foundDashboard.getAssignedCustomers().isEmpty());
} }
@Test @Test
public void testAssignDashboardToNonExistentCustomer() throws Exception { public void testAssignDashboardToNonExistentCustomer() throws Exception {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
doPost("/api/customer/" + Uuids.timeBased().toString() String customerIdStr = Uuids.timeBased().toString();
doPost("/api/customer/" + customerIdStr
+ "/dashboard/" + savedDashboard.getId().getId().toString()) + "/dashboard/" + savedDashboard.getId().getId().toString())
.andExpect(status().isNotFound()); .andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Customer", customerIdStr))));
Mockito.reset(tbClusterService, auditLogService);
testNotifyEntityNever(savedDashboard.getId(), savedDashboard);
} }
@Test @Test
public void testAssignDashboardToCustomerFromDifferentTenant() throws Exception { public void testAssignDashboardToCustomerFromDifferentTenant() throws Exception {
loginSysAdmin(); loginSysAdmin();
Tenant tenant2 = new Tenant(); Tenant tenant2 = new Tenant();
tenant2.setTitle("Different tenant"); tenant2.setTitle("Different tenant");
Tenant savedTenant2 = doPost("/api/tenant", tenant2, Tenant.class); Tenant savedTenant2 = doPost("/api/tenant", tenant2, Tenant.class);
@ -196,100 +259,123 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
tenantAdmin2.setEmail("tenant3@thingsboard.org"); tenantAdmin2.setEmail("tenant3@thingsboard.org");
tenantAdmin2.setFirstName("Joe"); tenantAdmin2.setFirstName("Joe");
tenantAdmin2.setLastName("Downs"); tenantAdmin2.setLastName("Downs");
tenantAdmin2 = createUserAndLogin(tenantAdmin2, "testPassword1"); createUserAndLogin(tenantAdmin2, "testPassword1");
Customer customer = new Customer(); Customer customer = new Customer();
customer.setTitle("Different customer"); customer.setTitle("Different customer");
Customer savedCustomer = doPost("/api/customer", customer, Customer.class); Customer savedCustomer = doPost("/api/customer", customer, Customer.class);
login(tenantAdmin.getEmail(), "testPassword1"); login(tenantAdmin.getEmail(), "testPassword1");
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
doPost("/api/customer/" + savedCustomer.getId().getId().toString() doPost("/api/customer/" + savedCustomer.getId().getId().toString()
+ "/dashboard/" + savedDashboard.getId().getId().toString()) + "/dashboard/" + savedDashboard.getId().getId().toString())
.andExpect(status().isForbidden()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
Mockito.reset(tbClusterService, auditLogService);
testNotifyEntityNever(savedDashboard.getId(), savedDashboard);
doDelete("/api/tenant/" + savedTenant2.getId().getId().toString())
.andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(savedDashboard.getId(), savedDashboard);
loginSysAdmin(); loginSysAdmin();
doDelete("/api/tenant/"+savedTenant2.getId().getId().toString()) doDelete("/api/tenant/" + savedTenant2.getId().getId().toString())
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
@Test @Test
public void testFindTenantDashboards() throws Exception { public void testFindTenantDashboards() throws Exception {
List<DashboardInfo> dashboards = new ArrayList<>(); List<DashboardInfo> dashboards = new ArrayList<>();
for (int i=0;i<173;i++) {
Mockito.reset(tbClusterService, auditLogService);
int cntEntity = 173;
for (int i = 0; i < cntEntity; i++) {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("Dashboard"+i); dashboard.setTitle("Dashboard" + i);
dashboards.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class))); dashboards.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class)));
} }
testNotifyManyEntityManyTimeMsgToEdgeServiceNever(new Dashboard(), new Dashboard(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED, cntEntity);
List<DashboardInfo> loadedDashboards = new ArrayList<>(); List<DashboardInfo> loadedDashboards = new ArrayList<>();
PageLink pageLink = new PageLink(24); PageLink pageLink = new PageLink(24);
PageData<DashboardInfo> pageData = null; PageData<DashboardInfo> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/dashboards?", pageData = doGetTypedWithPageLink("/api/tenant/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
loadedDashboards.addAll(pageData.getData()); loadedDashboards.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
} }
} while (pageData.hasNext()); } while (pageData.hasNext());
Collections.sort(dashboards, idComparator); Collections.sort(dashboards, idComparator);
Collections.sort(loadedDashboards, idComparator); Collections.sort(loadedDashboards, idComparator);
Assert.assertEquals(dashboards, loadedDashboards); Assert.assertEquals(dashboards, loadedDashboards);
} }
@Test @Test
public void testFindTenantDashboardsByTitle() throws Exception { public void testFindTenantDashboardsByTitle() throws Exception {
String title1 = "Dashboard title 1"; String title1 = "Dashboard title 1";
List<DashboardInfo> dashboardsTitle1 = new ArrayList<>(); List<DashboardInfo> dashboardsTitle1 = new ArrayList<>();
for (int i=0;i<134;i++) { int cntEntity = 134;
for (int i = 0; i < cntEntity; i++) {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
String suffix = RandomStringUtils.randomAlphanumeric((int)(Math.random()*15)); String suffix = RandomStringUtils.randomAlphanumeric((int) (Math.random() * 15));
String title = title1+suffix; String title = title1 + suffix;
title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase();
dashboard.setTitle(title); dashboard.setTitle(title);
dashboardsTitle1.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class))); dashboardsTitle1.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class)));
} }
String title2 = "Dashboard title 2"; String title2 = "Dashboard title 2";
List<DashboardInfo> dashboardsTitle2 = new ArrayList<>(); List<DashboardInfo> dashboardsTitle2 = new ArrayList<>();
for (int i=0;i<112;i++) {
for (int i = 0; i < 112; i++) {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
String suffix = RandomStringUtils.randomAlphanumeric((int)(Math.random()*15)); String suffix = RandomStringUtils.randomAlphanumeric((int) (Math.random() * 15));
String title = title2+suffix; String title = title2 + suffix;
title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase(); title = i % 2 == 0 ? title.toLowerCase() : title.toUpperCase();
dashboard.setTitle(title); dashboard.setTitle(title);
dashboardsTitle2.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class))); dashboardsTitle2.add(new DashboardInfo(doPost("/api/dashboard", dashboard, Dashboard.class)));
} }
List<DashboardInfo> loadedDashboardsTitle1 = new ArrayList<>(); List<DashboardInfo> loadedDashboardsTitle1 = new ArrayList<>();
PageLink pageLink = new PageLink(15, 0, title1); PageLink pageLink = new PageLink(15, 0, title1);
PageData<DashboardInfo> pageData = null; PageData<DashboardInfo> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/dashboards?", pageData = doGetTypedWithPageLink("/api/tenant/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
loadedDashboardsTitle1.addAll(pageData.getData()); loadedDashboardsTitle1.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
} }
} while (pageData.hasNext()); } while (pageData.hasNext());
Collections.sort(dashboardsTitle1, idComparator); Collections.sort(dashboardsTitle1, idComparator);
Collections.sort(loadedDashboardsTitle1, idComparator); Collections.sort(loadedDashboardsTitle1, idComparator);
Assert.assertEquals(dashboardsTitle1, loadedDashboardsTitle1); Assert.assertEquals(dashboardsTitle1, loadedDashboardsTitle1);
List<DashboardInfo> loadedDashboardsTitle2 = new ArrayList<>(); List<DashboardInfo> loadedDashboardsTitle2 = new ArrayList<>();
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/dashboards?", pageData = doGetTypedWithPageLink("/api/tenant/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
loadedDashboardsTitle2.addAll(pageData.getData()); loadedDashboardsTitle2.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
@ -298,63 +384,79 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
Collections.sort(dashboardsTitle2, idComparator); Collections.sort(dashboardsTitle2, idComparator);
Collections.sort(loadedDashboardsTitle2, idComparator); Collections.sort(loadedDashboardsTitle2, idComparator);
Assert.assertEquals(dashboardsTitle2, loadedDashboardsTitle2); Assert.assertEquals(dashboardsTitle2, loadedDashboardsTitle2);
Mockito.reset(tbClusterService, auditLogService);
for (DashboardInfo dashboard : loadedDashboardsTitle1) { for (DashboardInfo dashboard : loadedDashboardsTitle1) {
doDelete("/api/dashboard/"+dashboard.getId().getId().toString()) doDelete("/api/dashboard/" + dashboard.getId().getId().toString())
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
testNotifyManyEntityManyTimeMsgToEdgeServiceNeverAdditionalInfoAny(new Dashboard(), new Dashboard(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.DELETED, cntEntity, 1);
pageLink = new PageLink(4, 0, title1); pageLink = new PageLink(4, 0, title1);
pageData = doGetTypedWithPageLink("/api/tenant/dashboards?", pageData = doGetTypedWithPageLink("/api/tenant/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
for (DashboardInfo dashboard : loadedDashboardsTitle2) { for (DashboardInfo dashboard : loadedDashboardsTitle2) {
doDelete("/api/dashboard/"+dashboard.getId().getId().toString()) doDelete("/api/dashboard/" + dashboard.getId().getId().toString())
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
pageLink = new PageLink(4, 0, title2); pageLink = new PageLink(4, 0, title2);
pageData = doGetTypedWithPageLink("/api/tenant/dashboards?", pageData = doGetTypedWithPageLink("/api/tenant/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
Assert.assertFalse(pageData.hasNext()); Assert.assertFalse(pageData.hasNext());
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }
@Test @Test
public void testFindCustomerDashboards() throws Exception { public void testFindCustomerDashboards() throws Exception {
Customer customer = new Customer(); Customer customer = new Customer();
customer.setTitle("Test customer"); customer.setTitle("Test customer");
customer = doPost("/api/customer", customer, Customer.class); customer = doPost("/api/customer", customer, Customer.class);
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
Mockito.reset(tbClusterService, auditLogService);
int cntEntity = 173;
List<DashboardInfo> dashboards = new ArrayList<>(); List<DashboardInfo> dashboards = new ArrayList<>();
for (int i=0;i<173;i++) { for (int i = 0; i < cntEntity; i++) {
Dashboard dashboard = new Dashboard(); Dashboard dashboard = new Dashboard();
dashboard.setTitle("Dashboard"+i); dashboard.setTitle("Dashboard" + i);
dashboard = doPost("/api/dashboard", dashboard, Dashboard.class); dashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
dashboards.add(new DashboardInfo(doPost("/api/customer/" + customerId.getId().toString() dashboards.add(new DashboardInfo(doPost("/api/customer/" + customerId.getId().toString()
+ "/dashboard/" + dashboard.getId().getId().toString(), Dashboard.class))); + "/dashboard/" + dashboard.getId().getId().toString(), Dashboard.class)));
} }
testNotifyManyEntityManyTimeMsgToEdgeServiceEntityEqAny(new Dashboard(), new Dashboard(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED, ActionType.ASSIGNED_TO_CUSTOMER, cntEntity, cntEntity, cntEntity*2);
List<DashboardInfo> loadedDashboards = new ArrayList<>(); List<DashboardInfo> loadedDashboards = new ArrayList<>();
PageLink pageLink = new PageLink(21); PageLink pageLink = new PageLink(21);
PageData<DashboardInfo> pageData = null; PageData<DashboardInfo> pageData = null;
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/dashboards?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId().toString() + "/dashboards?",
new TypeReference<PageData<DashboardInfo>>(){}, pageLink); new TypeReference<PageData<DashboardInfo>>() {
}, pageLink);
loadedDashboards.addAll(pageData.getData()); loadedDashboards.addAll(pageData.getData());
if (pageData.hasNext()) { if (pageData.hasNext()) {
pageLink = pageLink.nextPageLink(); pageLink = pageLink.nextPageLink();
} }
} while (pageData.hasNext()); } while (pageData.hasNext());
Collections.sort(dashboards, idComparator); Collections.sort(dashboards, idComparator);
Collections.sort(loadedDashboards, idComparator); Collections.sort(loadedDashboards, idComparator);
Assert.assertEquals(dashboards, loadedDashboards); Assert.assertEquals(dashboards, loadedDashboards);
} }
@ -367,11 +469,18 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
dashboard.setTitle("My dashboard"); dashboard.setTitle("My dashboard");
Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class); Dashboard savedDashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
Mockito.reset(tbClusterService, auditLogService);
doPost("/api/edge/" + savedEdge.getId().getId().toString() doPost("/api/edge/" + savedEdge.getId().getId().toString()
+ "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
testNotifyEntityAllOneTime(savedDashboard, savedDashboard.getId(), savedDashboard.getId(), savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ASSIGNED_TO_EDGE,
savedDashboard.getId().getId().toString(), savedEdge.getId().getId().toString(), savedEdge.getName());
PageData<Dashboard> pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/dashboards?", PageData<Dashboard> pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/dashboards?",
new TypeReference<PageData<Dashboard>>() {}, new PageLink(100)); new TypeReference<PageData<Dashboard>>() {
}, new PageLink(100));
Assert.assertEquals(1, pageData.getData().size()); Assert.assertEquals(1, pageData.getData().size());
@ -379,7 +488,8 @@ public abstract class BaseDashboardControllerTest extends AbstractControllerTest
+ "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class); + "/dashboard/" + savedDashboard.getId().getId().toString(), Dashboard.class);
pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/dashboards?", pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId().toString() + "/dashboards?",
new TypeReference<PageData<Dashboard>>() {}, new PageLink(100)); new TypeReference<PageData<Dashboard>>() {
}, new PageLink(100));
Assert.assertEquals(0, pageData.getData().size()); Assert.assertEquals(0, pageData.getData().size());
} }

313
application/src/test/java/org/thingsboard/server/controller/BaseDeviceControllerTest.java

@ -21,22 +21,24 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.MoreExecutors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito;
import org.thingsboard.common.util.ThingsBoardExecutors; import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntitySubtype; import org.thingsboard.server.common.data.EntitySubtype;
import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceCredentialsId; import org.thingsboard.server.common.data.id.DeviceCredentialsId;
import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.relation.EntityRelation; import org.thingsboard.server.common.data.relation.EntityRelation;
@ -44,6 +46,8 @@ import org.thingsboard.server.common.data.relation.RelationTypeGroup;
import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.data.security.DeviceCredentialsType; import org.thingsboard.server.common.data.security.DeviceCredentialsType;
import org.thingsboard.server.dao.exception.DataValidationException;
import org.thingsboard.server.dao.exception.DeviceCredentialsValidationException;
import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.model.ModelConstants;
import java.util.ArrayList; import java.util.ArrayList;
@ -55,7 +59,6 @@ import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID; import static org.thingsboard.server.dao.model.ModelConstants.NULL_UUID;
@Slf4j
public abstract class BaseDeviceControllerTest extends AbstractControllerTest { public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
static final TypeReference<PageData<Device>> PAGE_DATA_DEVICE_TYPE_REF = new TypeReference<>() { static final TypeReference<PageData<Device>> PAGE_DATA_DEVICE_TYPE_REF = new TypeReference<>() {
}; };
@ -70,7 +73,6 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
@Before @Before
public void beforeTest() throws Exception { public void beforeTest() throws Exception {
log.debug("beforeTest");
executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass())); executor = MoreExecutors.listeningDecorator(ThingsBoardExecutors.newWorkStealingPool(8, getClass()));
loginSysAdmin(); loginSysAdmin();
@ -92,14 +94,12 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
@After @After
public void afterTest() throws Exception { public void afterTest() throws Exception {
log.debug("afterTest...");
executor.shutdownNow(); executor.shutdownNow();
loginSysAdmin(); loginSysAdmin();
doDelete("/api/tenant/" + savedTenant.getId().getId()) doDelete("/api/tenant/" + savedTenant.getId().getId())
.andExpect(status().isOk()); .andExpect(status().isOk());
log.debug("afterTest done");
} }
@Test @Test
@ -107,8 +107,17 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
Device device = new Device(); Device device = new Device();
device.setName("My device"); device.setName("My device");
device.setType("default"); device.setType("default");
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
Device oldDevice = new Device(savedDevice);
testNotifyEntityOneTimeMsgToEdgeServiceNever(savedDevice, savedDevice.getId(), savedDevice.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED);
testNotificationUpdateGatewayNever();
Assert.assertNotNull(savedDevice); Assert.assertNotNull(savedDevice);
Assert.assertNotNull(savedDevice.getId()); Assert.assertNotNull(savedDevice.getId());
Assert.assertTrue(savedDevice.getCreatedTime() > 0); Assert.assertTrue(savedDevice.getCreatedTime() > 0);
@ -127,9 +136,15 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
Assert.assertNotNull(deviceCredentials.getCredentialsId()); Assert.assertNotNull(deviceCredentials.getCredentialsId());
Assert.assertEquals(20, deviceCredentials.getCredentialsId().length()); Assert.assertEquals(20, deviceCredentials.getCredentialsId().length());
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
savedDevice.setName("My new device"); savedDevice.setName("My new device");
doPost("/api/device", savedDevice, Device.class); doPost("/api/device", savedDevice, Device.class);
testNotifyEntityAllOneTime(savedDevice, savedDevice.getId(), savedDevice.getId(), savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.UPDATED);
testNotificationUpdateGatewayOneTime(savedDevice, oldDevice);
Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class);
Assert.assertEquals(foundDevice.getName(), savedDevice.getName()); Assert.assertEquals(foundDevice.getName(), savedDevice.getName());
} }
@ -139,13 +154,41 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
Device device = new Device(); Device device = new Device();
device.setName(RandomStringUtils.randomAlphabetic(300)); device.setName(RandomStringUtils.randomAlphabetic(300));
device.setType("default"); device.setType("default");
doPost("/api/device", device).andExpect(statusReason(containsString("length of name must be equal or less than 255")));
device.setName("Normal Name"); Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String msgError = "length of name must be equal or less than 255";
doPost("/api/device", device)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
testNotificationUpdateGatewayNever();
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
device.setTenantId(savedTenant.getId());
msgError = "length of type must be equal or less than 255";
device.setType(RandomStringUtils.randomAlphabetic(300)); device.setType(RandomStringUtils.randomAlphabetic(300));
doPost("/api/device", device).andExpect(statusReason(containsString("length of type must be equal or less than 255"))); doPost("/api/device", device)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
testNotificationUpdateGatewayNever();
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
msgError = "length of label must be equal or less than 255";
device.setType("Normal type"); device.setType("Normal type");
device.setLabel(RandomStringUtils.randomAlphabetic(300)); device.setLabel(RandomStringUtils.randomAlphabetic(300));
doPost("/api/device", device).andExpect(statusReason(containsString("length of label must be equal or less than 255"))); doPost("/api/device", device)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -155,7 +198,24 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
loginDifferentTenant(); loginDifferentTenant();
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/device", savedDevice, Device.class, status().isNotFound()); doPost("/api/device", savedDevice, Device.class, status().isNotFound());
testNotifyEntityNever(savedDevice.getId(), savedDevice);
testNotificationUpdateGatewayNever();
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String savedDeviceIdStr = savedDevice.getId().getId().toString();
doDelete("/api/device/" + savedDeviceIdStr)
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Device", savedDeviceIdStr))));
testNotifyEntityNever(savedDevice.getId(), savedDevice);
testNotificationUpdateGatewayNever();
deleteDifferentTenant(); deleteDifferentTenant();
} }
@ -173,12 +233,24 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
@Test @Test
public void testFindDeviceTypesByTenantId() throws Exception { public void testFindDeviceTypesByTenantId() throws Exception {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int cntEntity = 3;
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
for (int i = 0; i < cntEntity; i++) {
Device device = new Device(); Device device = new Device();
device.setName("My device B" + i); device.setName("My device B" + i);
device.setType("typeB"); device.setType("typeB");
devices.add(doPost("/api/device", device, Device.class)); devices.add(doPost("/api/device", device, Device.class));
} }
testNotifyManyEntityManyTimeMsgToEdgeServiceNever(new Device(), new Device(),
savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED, cntEntity);
testNotificationUpdateGatewayNever();
for (int i = 0; i < 7; i++) { for (int i = 0; i < 7; i++) {
Device device = new Device(); Device device = new Device();
device.setName("My device C" + i); device.setName("My device C" + i);
@ -192,7 +264,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
devices.add(doPost("/api/device", device, Device.class)); devices.add(doPost("/api/device", device, Device.class));
} }
List<EntitySubtype> deviceTypes = doGetTyped("/api/device/types", List<EntitySubtype> deviceTypes = doGetTyped("/api/device/types",
new TypeReference<List<EntitySubtype>>() { new TypeReference<>() {
}); });
Assert.assertNotNull(deviceTypes); Assert.assertNotNull(deviceTypes);
@ -211,28 +283,52 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doDelete("/api/device/" + savedDevice.getId().getId()) doDelete("/api/device/" + savedDevice.getId().getId())
.andExpect(status().isOk()); .andExpect(status().isOk());
doGet("/api/device/" + savedDevice.getId().getId()) testNotifyEntityOneTimeMsgToEdgeServiceNever(savedDevice, savedDevice.getId(), savedDevice.getId(), savedTenant.getId(),
.andExpect(status().isNotFound()); tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.DELETED, savedDevice.getId().getId().toString());
testNotificationDeleteGatewayOneTime(savedDevice);
EntityId savedDeviceId = savedDevice.getId();
doGet("/api/device/" + savedDeviceId)
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Device", savedDeviceId.getId().toString()))));
} }
@Test @Test
public void testSaveDeviceWithEmptyType() throws Exception { public void testSaveDeviceWithEmptyType() throws Exception {
Device device = new Device(); Device device = new Device();
device.setName("My device"); device.setName("My device");
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
Assert.assertEquals("default", savedDevice.getType()); Assert.assertEquals("default", savedDevice.getType());
testNotifyEntityOneTimeMsgToEdgeServiceNever(savedDevice, savedDevice.getId(), savedDevice.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED);
testNotificationUpdateGatewayNever();
} }
@Test @Test
public void testSaveDeviceWithEmptyName() throws Exception { public void testSaveDeviceWithEmptyName() throws Exception {
Device device = new Device(); Device device = new Device();
device.setType("default"); device.setType("default");
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String msgError = "Device name " + msgErrorShouldBeSpecified;
doPost("/api/device", device) doPost("/api/device", device)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Device name should be specified"))); .andExpect(statusReason(containsString(msgError)));
testNotifyEntityEqualsOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ADDED, new DataValidationException(msgError));
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -246,17 +342,33 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
customer.setTitle("My customer"); customer.setTitle("My customer");
Customer savedCustomer = doPost("/api/customer", customer, Customer.class); Customer savedCustomer = doPost("/api/customer", customer, Customer.class);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
Device assignedDevice = doPost("/api/customer/" + savedCustomer.getId().getId() Device assignedDevice = doPost("/api/customer/" + savedCustomer.getId().getId()
+ "/device/" + savedDevice.getId().getId(), Device.class); + "/device/" + savedDevice.getId().getId(), Device.class);
Assert.assertEquals(savedCustomer.getId(), assignedDevice.getCustomerId()); Assert.assertEquals(savedCustomer.getId(), assignedDevice.getCustomerId());
testNotifyEntityAllOneTime(assignedDevice, assignedDevice.getId(), assignedDevice.getId(), savedTenant.getId(),
savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.ASSIGNED_TO_CUSTOMER,
assignedDevice.getId().getId().toString(), savedCustomer.getId().getId().toString(),
savedCustomer.getTitle());
testNotificationUpdateGatewayNever();
Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); Device foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class);
Assert.assertEquals(savedCustomer.getId(), foundDevice.getCustomerId()); Assert.assertEquals(savedCustomer.getId(), foundDevice.getCustomerId());
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
Device unassignedDevice = Device unassignedDevice =
doDelete("/api/customer/device/" + savedDevice.getId().getId(), Device.class); doDelete("/api/customer/device/" + savedDevice.getId().getId(), Device.class);
Assert.assertEquals(ModelConstants.NULL_UUID, unassignedDevice.getCustomerId().getId()); Assert.assertEquals(ModelConstants.NULL_UUID, unassignedDevice.getCustomerId().getId());
testNotifyEntityAllOneTime(unassignedDevice, unassignedDevice.getId(), unassignedDevice.getId(), savedTenant.getId(),
savedCustomer.getId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.UNASSIGNED_FROM_CUSTOMER,
unassignedDevice.getId().getId().toString(), savedCustomer.getId().getId().toString(),
savedCustomer.getTitle());
testNotificationDeleteGatewayNever();
foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class); foundDevice = doGet("/api/device/" + savedDevice.getId().getId(), Device.class);
Assert.assertEquals(ModelConstants.NULL_UUID, foundDevice.getCustomerId().getId()); Assert.assertEquals(ModelConstants.NULL_UUID, foundDevice.getCustomerId().getId());
} }
@ -267,9 +379,17 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setName("My device"); device.setName("My device");
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
doPost("/api/customer/" + Uuids.timeBased().toString()
+ "/device/" + savedDevice.getId().getId()) Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
.andExpect(status().isNotFound());
String customerIdStr = savedDevice.getId().toString();
doPost("/api/customer/" + customerIdStr
+ "/device/" + savedDevice.getId().getId())
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Customer", customerIdStr))));
testNotifyEntityNever(savedDevice.getId(), savedDevice);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -288,7 +408,7 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
tenantAdmin2.setFirstName("Joe"); tenantAdmin2.setFirstName("Joe");
tenantAdmin2.setLastName("Downs"); tenantAdmin2.setLastName("Downs");
tenantAdmin2 = createUserAndLogin(tenantAdmin2, "testPassword1"); createUserAndLogin(tenantAdmin2, "testPassword1");
Customer customer = new Customer(); Customer customer = new Customer();
customer.setTitle("Different customer"); customer.setTitle("Different customer");
@ -301,9 +421,15 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/customer/" + savedCustomer.getId().getId() doPost("/api/customer/" + savedCustomer.getId().getId()
+ "/device/" + savedDevice.getId().getId()) + "/device/" + savedDevice.getId().getId())
.andExpect(status().isForbidden()); .andExpect(status().isForbidden())
.andExpect(statusReason(containsString(msgErrorPermission)));
testNotifyEntityNever(savedDevice.getId(), savedDevice);
testNotificationUpdateGatewayNever();
loginSysAdmin(); loginSysAdmin();
@ -333,9 +459,16 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId()); Assert.assertEquals(savedDevice.getId(), deviceCredentials.getDeviceId());
deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN); deviceCredentials.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN);
deviceCredentials.setCredentialsId("access_token"); deviceCredentials.setCredentialsId("access_token");
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/device/credentials", deviceCredentials) doPost("/api/device/credentials", deviceCredentials)
.andExpect(status().isOk()); .andExpect(status().isOk());
testNotifyEntityMsgToEdgePushMsgToCoreOneTime(savedDevice, savedDevice.getId(), savedDevice.getId(), savedTenant.getId(),
tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.CREDENTIALS_UPDATED, deviceCredentials);
testNotificationUpdateGatewayNever();
DeviceCredentials foundDeviceCredentials = DeviceCredentials foundDeviceCredentials =
doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class);
@ -345,8 +478,15 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
@Test @Test
public void testSaveDeviceCredentialsWithEmptyDevice() throws Exception { public void testSaveDeviceCredentialsWithEmptyDevice() throws Exception {
DeviceCredentials deviceCredentials = new DeviceCredentials(); DeviceCredentials deviceCredentials = new DeviceCredentials();
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/device/credentials", deviceCredentials) doPost("/api/device/credentials", deviceCredentials)
.andExpect(status().isBadRequest()); .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Incorrect deviceId null")));
testNotifyEntityNever(deviceCredentials.getDeviceId(), new Device());
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -358,9 +498,18 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
DeviceCredentials deviceCredentials = DeviceCredentials deviceCredentials =
doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class);
deviceCredentials.setCredentialsType(null); deviceCredentials.setCredentialsType(null);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String msgError = "Device credentials type " + msgErrorShouldBeSpecified;
doPost("/api/device/credentials", deviceCredentials) doPost("/api/device/credentials", deviceCredentials)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Device credentials type should be specified"))); .andExpect(statusReason(containsString(msgError)));
testNotifyEntityIsNullOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.CREDENTIALS_UPDATED,
new DataValidationException(msgError), deviceCredentials);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -372,9 +521,18 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
DeviceCredentials deviceCredentials = DeviceCredentials deviceCredentials =
doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class);
deviceCredentials.setCredentialsId(null); deviceCredentials.setCredentialsId(null);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String msgError = "Device credentials id " + msgErrorShouldBeSpecified;
doPost("/api/device/credentials", deviceCredentials) doPost("/api/device/credentials", deviceCredentials)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Device credentials id should be specified"))); .andExpect(statusReason(containsString(msgError)));
testNotifyEntityIsNullOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.CREDENTIALS_UPDATED,
new DeviceCredentialsValidationException(msgError), deviceCredentials);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -390,9 +548,18 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
newDeviceCredentials.setDeviceId(deviceCredentials.getDeviceId()); newDeviceCredentials.setDeviceId(deviceCredentials.getDeviceId());
newDeviceCredentials.setCredentialsType(deviceCredentials.getCredentialsType()); newDeviceCredentials.setCredentialsType(deviceCredentials.getCredentialsType());
newDeviceCredentials.setCredentialsId(deviceCredentials.getCredentialsId()); newDeviceCredentials.setCredentialsId(deviceCredentials.getCredentialsId());
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
String msgError = "Unable to update non-existent device credentials";
doPost("/api/device/credentials", newDeviceCredentials) doPost("/api/device/credentials", newDeviceCredentials)
.andExpect(status().isBadRequest()) .andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Unable to update non-existent device credentials"))); .andExpect(statusReason(containsString(msgError)));
testNotifyEntityIsNullOneTimeError(device, savedTenant.getId(),
tenantAdmin.getId(), tenantAdmin.getEmail(), ActionType.CREDENTIALS_UPDATED,
new DeviceCredentialsValidationException(msgError), newDeviceCredentials);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -401,29 +568,44 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setName("My device"); device.setName("My device");
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
DeviceId deviceTimeBasedId = new DeviceId(Uuids.timeBased());
DeviceCredentials deviceCredentials = DeviceCredentials deviceCredentials =
doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class); doGet("/api/device/" + savedDevice.getId().getId() + "/credentials", DeviceCredentials.class);
deviceCredentials.setDeviceId(new DeviceId(Uuids.timeBased())); deviceCredentials.setDeviceId(deviceTimeBasedId);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/device/credentials", deviceCredentials) doPost("/api/device/credentials", deviceCredentials)
.andExpect(status().isNotFound()); .andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Device", deviceTimeBasedId.toString()))));
testNotifyEntityNever(savedDevice.getId(), savedDevice);
testNotificationUpdateGatewayNever();
} }
@Test @Test
public void testFindTenantDevices() throws Exception { public void testFindTenantDevices() throws Exception {
log.debug("testFindTenantDevices"); int cntEntity = 178;
futures = new ArrayList<>(178);
for (int i = 0; i < 178; i++) { Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
futures = new ArrayList<>(cntEntity);
for (int i = 0; i < cntEntity; i++) {
Device device = new Device(); Device device = new Device();
device.setName("Device" + i); device.setName("Device" + i);
device.setType("default"); device.setType("default");
futures.add(executor.submit(() -> futures.add(executor.submit(() ->
doPost("/api/device", device, Device.class))); doPost("/api/device", device, Device.class)));
} }
log.debug("await create devices");
List<Device> devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); List<Device> devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS);
log.debug("start reading"); testNotifyManyEntityManyTimeMsgToEdgeServiceNever(new Device(), new Device(),
List<Device> loadedDevices = new ArrayList<>(178); savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED, cntEntity);
testNotificationUpdateGatewayNever();
List<Device> loadedDevices = new ArrayList<>(cntEntity);
PageLink pageLink = new PageLink(23); PageLink pageLink = new PageLink(23);
do { do {
pageData = doGetTypedWithPageLink("/api/tenant/devices?", pageData = doGetTypedWithPageLink("/api/tenant/devices?",
@ -435,11 +617,16 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
} }
} while (pageData.hasNext()); } while (pageData.hasNext());
log.debug("asserting");
assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices); assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices);
log.debug("delete devices async");
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
deleteEntitiesAsync("/api/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS); deleteEntitiesAsync("/api/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS);
log.debug("done");
testNotifyManyEntityManyTimeMsgToEdgeServiceNeverAdditionalInfoAny(new Device(), new Device(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.DELETED, cntEntity, 1);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -604,9 +791,12 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
customer.setTitle("Test customer"); customer.setTitle("Test customer");
customer = doPost("/api/customer", customer, Customer.class); customer = doPost("/api/customer", customer, Customer.class);
CustomerId customerId = customer.getId(); CustomerId customerId = customer.getId();
int cntEntity = 128;
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
futures = new ArrayList<>(128); futures = new ArrayList<>(cntEntity);
for (int i = 0; i < 128; i++) { for (int i = 0; i < cntEntity; i++) {
Device device = new Device(); Device device = new Device();
device.setName("Device" + i); device.setName("Device" + i);
device.setType("default"); device.setType("default");
@ -618,7 +808,12 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
List<Device> devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS); List<Device> devices = Futures.allAsList(futures).get(TIMEOUT, TimeUnit.SECONDS);
List<Device> loadedDevices = new ArrayList<>(128); testNotifyManyEntityManyTimeMsgToEdgeServiceEntityEqAny(new Device(), new Device(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ADDED, ActionType.ASSIGNED_TO_CUSTOMER, cntEntity, cntEntity, cntEntity * 2);
testNotificationUpdateGatewayNever();
List<Device> loadedDevices = new ArrayList<>(cntEntity);
PageLink pageLink = new PageLink(23); PageLink pageLink = new PageLink(23);
do { do {
pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?", pageData = doGetTypedWithPageLink("/api/customer/" + customerId.getId() + "/devices?",
@ -631,9 +826,14 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices); assertThat(devices).containsExactlyInAnyOrderElementsOf(loadedDevices);
log.debug("delete devices async"); Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
deleteEntitiesAsync("/api/customer/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS); deleteEntitiesAsync("/api/customer/device/", loadedDevices, executor).get(TIMEOUT, TimeUnit.SECONDS);
log.debug("done");
testNotifyManyEntityManyTimeMsgToEdgeServiceEntityEqAnyAdditionalInfoAny(new Device(), new Device(),
savedTenant.getId(), customerId, tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.UNASSIGNED_FROM_CUSTOMER, ActionType.UNASSIGNED_FROM_CUSTOMER, cntEntity, cntEntity, 3);
testNotificationUpdateGatewayNever();
} }
@Test @Test
@ -843,16 +1043,30 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
createUserAndLogin(user, "testPassword1"); createUserAndLogin(user, "testPassword1");
login("tenant2@thingsboard.org", "testPassword1"); login("tenant2@thingsboard.org", "testPassword1");
Device assignedDevice = doPost("/api/tenant/" + savedDifferentTenant.getId().getId() + "/device/" + savedDevice.getId().getId(), Device.class);
doGet("/api/device/" + assignedDevice.getId().getId(), Device.class, status().isNotFound()); Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
Device assignedDevice = doPost("/api/tenant/" + savedDifferentTenant.getId().getId() + "/device/"
+ savedDevice.getId().getId(), Device.class);
doGet("/api/device/" + assignedDevice.getId().getId())
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Device", assignedDevice.getId().getId().toString()))));
testNotifyEntityOneTimeMsgToEdgeServiceNever(assignedDevice, assignedDevice.getId(), assignedDevice.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ASSIGNED_TO_TENANT, savedDifferentTenant.getId().getId().toString(), savedDifferentTenant.getTitle());
testNotificationUpdateGatewayNever();
login("tenant9@thingsboard.org", "testPassword1"); login("tenant9@thingsboard.org", "testPassword1");
Device foundDevice1 = doGet("/api/device/" + assignedDevice.getId().getId(), Device.class); Device foundDevice1 = doGet("/api/device/" + assignedDevice.getId().getId(), Device.class);
Assert.assertNotNull(foundDevice1); Assert.assertNotNull(foundDevice1);
doGet("/api/relation?fromId=" + savedDevice.getId().getId() + "&fromType=DEVICE&relationType=Contains&toId=" + savedAnotherDevice.getId().getId() + "&toType=DEVICE", EntityRelation.class, status().isNotFound()); doGet("/api/relation?fromId=" + savedDevice.getId().getId() + "&fromType=DEVICE&relationType=Contains&toId="
+ savedAnotherDevice.getId().getId() + "&toType=DEVICE")
.andExpect(status().isNotFound())
.andExpect(statusReason(containsString(msgErrorNoFound("Device", savedAnotherDevice.getId().getId().toString()))));
loginSysAdmin(); loginSysAdmin();
doDelete("/api/tenant/" + savedDifferentTenant.getId().getId()) doDelete("/api/tenant/" + savedDifferentTenant.getId().getId())
@ -869,17 +1083,32 @@ public abstract class BaseDeviceControllerTest extends AbstractControllerTest {
device.setType("default"); device.setType("default");
Device savedDevice = doPost("/api/device", device, Device.class); Device savedDevice = doPost("/api/device", device, Device.class);
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doPost("/api/edge/" + savedEdge.getId().getId() doPost("/api/edge/" + savedEdge.getId().getId()
+ "/device/" + savedDevice.getId().getId(), Device.class); + "/device/" + savedDevice.getId().getId(), Device.class);
testNotifyEntityAllOneTime(savedDevice, savedDevice.getId(), savedDevice.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.ASSIGNED_TO_EDGE,
savedDevice.getId().getId().toString(), savedEdge.getId().getId().toString(), savedEdge.getName());
testNotificationUpdateGatewayNever();
pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?", pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?",
PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100)); PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100));
Assert.assertEquals(1, pageData.getData().size()); Assert.assertEquals(1, pageData.getData().size());
Mockito.reset(tbClusterService, auditLogService, gatewayNotificationsService);
doDelete("/api/edge/" + savedEdge.getId().getId() doDelete("/api/edge/" + savedEdge.getId().getId()
+ "/device/" + savedDevice.getId().getId(), Device.class); + "/device/" + savedDevice.getId().getId(), Device.class);
testNotifyEntityAllOneTime(savedDevice, savedDevice.getId(), savedDevice.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.UNASSIGNED_FROM_EDGE, savedDevice.getId().getId().toString(), savedEdge.getId().getId().toString(), savedEdge.getName());
testNotificationUpdateGatewayNever();
pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?", pageData = doGetTypedWithPageLink("/api/edge/" + savedEdge.getId().getId() + "/devices?",
PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100)); PAGE_DATA_DEVICE_TYPE_REF, new PageLink(100));

Loading…
Cancel
Save