Remove allure (phase2) (#2483)

Signed-off-by: Avgustin Marinov <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2025-06-20 15:51:06 +03:00
committed by GitHub
parent 39593fc6b6
commit cb7f1107fe
406 changed files with 6993 additions and 5863 deletions

View File

@@ -12,23 +12,22 @@ package org.eclipse.hawkbit.repository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.ArtifactEncryptionUnsupportedException;
import org.junit.jupiter.api.Test;
/**
* Test class to verify that no {@link ArtifactEncryptionService} required beans
* are loaded and therefore the encryption support is not given.
* <p/>
* Feature: Unit Tests - Repository<br/>
* Story: Artifact Encryption Service
*/
@Feature("Unit Tests - Repository")
@Story("Artifact Encryption Service")
class ArtifactEncryptionServiceTest {
@Test
@Description("Verify that no artifact encryption support is given")
void verifyNoArtifactEncryptionSupport() {
/**
* Verify that no artifact encryption support is given
*/
@Test void verifyNoArtifactEncryptionSupport() {
final ArtifactEncryptionService artifactEncryptionService = ArtifactEncryptionService.getInstance();
assertThat(artifactEncryptionService.isEncryptionSupported()).isFalse();

View File

@@ -16,51 +16,55 @@ import java.time.Duration;
import java.time.ZonedDateTime;
import com.cronutils.model.Cron;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.InvalidMaintenanceScheduleException;
import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository")
@Story("Maintenance Schedule Utility")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Maintenance Schedule Utility
*/
class MaintenanceScheduleHelperTest {
@Test
@Description("Verifies that the Cron object is returned for valid cron expression")
void getCronFromExpressionValid() {
/**
* Verifies that the Cron object is returned for valid cron expression
*/
@Test void getCronFromExpressionValid() {
final String validCron = "0 0 0 ? * 6"; // at 00:00 every Saturday
assertThat(MaintenanceScheduleHelper.getCronFromExpression(validCron)).isNotNull().isInstanceOf(Cron.class);
}
@Test
@Description("Verifies that the Duration object is returned for valid duration format (hh:mm or hh:mm:ss)")
void convertToISODurationValid() {
/**
* Verifies that the Duration object is returned for valid duration format (hh:mm or hh:mm:ss)
*/
@Test void convertToISODurationValid() {
final String duration = "00:10";
assertThat(MaintenanceScheduleHelper.convertToISODuration(duration)).isNotNull().isInstanceOf(Duration.class);
}
@Test
@Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid duration format")
void validateDurationInvalid() {
/**
* Verifies that the InvalidMaintenanceScheduleException is thrown for invalid duration format
*/
@Test void validateDurationInvalid() {
final String duration = "10";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateDuration(duration))
.isInstanceOf(InvalidMaintenanceScheduleException.class).hasMessage("Provided duration is not valid")
.extracting("durationErrorIndex").isEqualTo(2);
}
@Test
@Description("Verifies that the InvalidMaintenanceScheduleException is thrown for invalid cron expression")
void validateCronScheduleInvalid() {
/**
* Verifies that the InvalidMaintenanceScheduleException is thrown for invalid cron expression
*/
@Test void validateCronScheduleInvalid() {
final String invalidCron = "0 0 0 * * 6";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateCronSchedule(invalidCron))
.isInstanceOf(InvalidMaintenanceScheduleException.class)
.hasMessageContaining("Both, a day-of-week AND a day-of-month parameter, are not supported");
}
@Test
@Description("Verifies that there is a maintenance window available for correct schedule, duration and timezone")
void getNextMaintenanceWindowValid() {
/**
* Verifies that there is a maintenance window available for correct schedule, duration and timezone
*/
@Test void getNextMaintenanceWindowValid() {
final ZonedDateTime currentTime = ZonedDateTime.now();
final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(),
currentTime.getDayOfMonth(), currentTime.getMonthValue(), currentTime.getYear());
@@ -69,18 +73,20 @@ class MaintenanceScheduleHelperTest {
assertThat(MaintenanceScheduleHelper.getNextMaintenanceWindow(cronSchedule, duration, timezone)).isPresent();
}
@Test
@Description("Verifies the maintenance schedule when only one required field is present")
void validateMaintenanceScheduleAtLeastOneNotEmpty() {
/**
* Verifies the maintenance schedule when only one required field is present
*/
@Test void validateMaintenanceScheduleAtLeastOneNotEmpty() {
final String duration = "00:10";
assertThatThrownBy(() -> MaintenanceScheduleHelper.validateMaintenanceSchedule(null, duration, null))
.isInstanceOf(InvalidMaintenanceScheduleException.class)
.hasMessage("All of schedule, duration and timezone should either be null or non empty.");
}
@Test
@Description("Verifies that there is no valid maintenance window available, scheduled before current time")
void validateMaintenanceScheduleBeforeCurrentTime() {
/**
* Verifies that there is no valid maintenance window available, scheduled before current time
*/
@Test void validateMaintenanceScheduleBeforeCurrentTime() {
ZonedDateTime currentTime = ZonedDateTime.now();
currentTime = currentTime.plusMinutes(-30);
final String cronSchedule = String.format("0 %d %d %d %d ? %d", currentTime.getMinute(), currentTime.getHour(),

View File

@@ -11,23 +11,23 @@ package org.eclipse.hawkbit.repository;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.RegexCharacterCollection.RegexChar;
import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository")
@Story("Regular expression helper")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Regular expression helper
*/
class RegexCharTest {
private static final int INDEX_FIRST_PRINTABLE_ASCII_CHAR = 32;
private static final int INDEX_LAST_PRINTABLE_ASCII_CHAR = 127;
private static final String TEST_STRING = getPrintableAsciiCharacters();
@Test
@Description("Verifies every RegexChar can be used to exclusively find the desired characters in a String.")
void allRegexCharsOnlyFindExpectedChars() {
/**
* Verifies every RegexChar can be used to exclusively find the desired characters in a String.
*/
@Test void allRegexCharsOnlyFindExpectedChars() {
for (final RegexChar character : RegexChar.values()) {
switch (character) {
case DIGITS:
@@ -49,9 +49,10 @@ class RegexCharTest {
}
}
@Test
@Description("Verifies that combinations of RegexChars can be used to find the desired characters in a String.")
void combinedRegexCharsFindExpectedChars() {
/**
* Verifies that combinations of RegexChars can be used to find the desired characters in a String.
*/
@Test void combinedRegexCharsFindExpectedChars() {
final RegexCharacterCollection greaterAndLessThan = new RegexCharacterCollection(RegexChar.GREATER_THAN,
RegexChar.LESS_THAN);
final RegexCharacterCollection equalsAndQuestionMark = new RegexCharacterCollection(RegexChar.EQUALS_SYMBOL,

View File

@@ -20,22 +20,22 @@ import java.util.Set;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.prepost.PreAuthorize;
@Feature("Unit Tests - Repository")
@Story("Security Test")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Security Test
*/
class RepositoryManagementMethodPreAuthorizeAnnotatedTest {
// if some methods are to be excluded
private static final Set<Method> METHOD_SECURITY_EXCLUSION = new HashSet<>();
@Test
@Description("Verifies that repository methods are @PreAuthorize annotated")
void repositoryManagementMethodsArePreAuthorizedAnnotated() {
/**
* Verifies that repository methods are @PreAuthorize annotated
*/
@Test void repositoryManagementMethodsArePreAuthorizedAnnotated() {
final String packageName = getClass().getPackage().getName();
try (final ScanResult scanResult = new ClassGraph().acceptPackages(packageName).scan()) {
final List<? extends Class<?>> matchingClasses = scanResult.getAllClasses()

View File

@@ -15,13 +15,12 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - TotalTargetCountStatus")
@Story("TotalTargetCountStatus should correctly present finished DOWNLOAD_ONLY actions")
/**
* Feature: Component Tests - TotalTargetCountStatus<br/>
* Story: TotalTargetCountStatus should correctly present finished DOWNLOAD_ONLY actions
*/
class TotalTargetCountStatusTest {
private final List<TotalTargetCountActionStatus> targetCountActionStatuses = Arrays.asList(
@@ -36,9 +35,10 @@ class TotalTargetCountStatusTest {
new TotalTargetCountActionStatus(Action.Status.CANCELING, 9L),
new TotalTargetCountActionStatus(Action.Status.DOWNLOADED, 10L));
/**
* Different Action Statuses should be correctly mapped to the corresponding TotalTargetCountStatus.Status
*/
@Test
@Description("Different Action Statuses should be correctly mapped to the corresponding " +
"TotalTargetCountStatus.Status")
void shouldCorrectlyMapActionStatuses() {
TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L,
Action.ActionType.FORCED);
@@ -51,9 +51,11 @@ class TotalTargetCountStatusTest {
assertThat(status.getFinishedPercent()).isEqualTo((float) 100 * 3 / 55);
}
/**
* When an empty list is passed to the TotalTargetCountStatus, all actions should be displayed as
* NOTSTARTED
*/
@Test
@Description("When an empty list is passed to the TotalTargetCountStatus, all actions should be displayed as " +
"NOTSTARTED")
void shouldCorrectlyMapActionStatusesToNotStarted() {
TotalTargetCountStatus status = new TotalTargetCountStatus(Collections.emptyList(), 55L,
Action.ActionType.FORCED);
@@ -66,9 +68,10 @@ class TotalTargetCountStatusTest {
assertThat(status.getFinishedPercent()).isZero();
}
@Test
@Description("DownloadOnly actions should be displayed as FINISHED when they have ActionStatus.DOWNLOADED")
void shouldCorrectlyMapActionStatusesInDownloadOnlyCase() {
/**
* DownloadOnly actions should be displayed as FINISHED when they have ActionStatus.DOWNLOADED
*/
@Test void shouldCorrectlyMapActionStatusesInDownloadOnlyCase() {
TotalTargetCountStatus status = new TotalTargetCountStatus(targetCountActionStatuses, 55L,
Action.ActionType.DOWNLOAD_ONLY);
assertThat(status.getTotalTargetCountByStatus(TotalTargetCountStatus.Status.SCHEDULED)).isEqualTo(1L);

View File

@@ -15,7 +15,6 @@ import static org.mockito.Mockito.when;
import java.util.HashMap;
import io.qameta.allure.Description;
import org.eclipse.hawkbit.repository.event.remote.entity.RemoteEntityEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.model.Target;
@@ -45,9 +44,10 @@ class BusProtoStuffMessageConverterTest {
when(targetMock.getId()).thenReturn(1L);
}
@Test
@Description("Verifies that the TargetCreatedEvent can be successfully serialized and deserialized")
void successfullySerializeAndDeserializeEvent() {
/**
* Verifies that the TargetCreatedEvent can be successfully serialized and deserialized
*/
@Test void successfullySerializeAndDeserializeEvent() {
final TargetCreatedEvent targetCreatedEvent = new TargetCreatedEvent(targetMock, "1");
// serialize
final Object serializedEvent = underTest.convertToInternal(targetCreatedEvent,
@@ -62,9 +62,10 @@ class BusProtoStuffMessageConverterTest {
.isEqualTo(targetCreatedEvent);
}
@Test
@Description("Verifies that a MessageConversationException is thrown on missing event-type information encoding")
void missingEventTypeMappingThrowsMessageConversationException() {
/**
* Verifies that a MessageConversationException is thrown on missing event-type information encoding
*/
@Test void missingEventTypeMappingThrowsMessageConversationException() {
final DummyRemoteEntityEvent dummyEvent = new DummyRemoteEntityEvent(targetMock, "applicationId");
final MessageHeaders messageHeaders = new MessageHeaders(new HashMap<>());

View File

@@ -18,32 +18,33 @@ import java.sql.SQLException;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Test;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.UncategorizedDataAccessException;
/**
* Mapping tests for {@link HawkbitEclipseLinkJpaDialect}.
* <p/>
* Feature: Unit Tests - Repository<br/>
* Story: Exception handling
*/
@Feature("Unit Tests - Repository")
@Story("Exception handling")
class HawkBitEclipseLinkJpaDialectTest {
private final HawkbitEclipseLinkJpaDialect hawkBitEclipseLinkJpaDialectUnderTest = new HawkbitEclipseLinkJpaDialect();
@Test
@Description("Use Case: PersistenceException that can be mapped by EclipseLinkJpaDialect into corresponding DataAccessException.")
void jpaOptimisticLockExceptionIsConcurrencyFailureException() {
/**
* Use Case: PersistenceException that can be mapped by EclipseLinkJpaDialect into corresponding DataAccessException.
*/
@Test void jpaOptimisticLockExceptionIsConcurrencyFailureException() {
assertThat(hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(mock(OptimisticLockException.class)))
.isInstanceOf(ConcurrencyFailureException.class);
}
/**
* Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but
* instead is wrapped into JpaSystemException. Cause of PersistenceException is an SQLException.
*/
@Test
@Description("Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but "
+ "instead is wrapped into JpaSystemException. Cause of PersistenceException is an SQLException.")
void jpaSystemExceptionWithSqlDeadLockExceptionIsConcurrencyFailureException() {
final PersistenceException persEception = mock(PersistenceException.class);
when(persEception.getCause()).thenReturn(new SQLException("simulated transaction ER_LOCK_DEADLOCK", "40001"));
@@ -52,9 +53,11 @@ class HawkBitEclipseLinkJpaDialectTest {
.isInstanceOf(ConcurrencyFailureException.class);
}
/**
* Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but instead is wrapped
* into JpaSystemException. Cause of PersistenceException is not an SQLException.
*/
@Test
@Description("Use Case: PersistenceException that could not be mapped by EclipseLinkJpaDialect directly but instead is wrapped"
+ " into JpaSystemException. Cause of PersistenceException is not an SQLException.")
void jpaSystemExceptionWithNumberFormatExceptionIsNull() {
final PersistenceException persEception = mock(PersistenceException.class);
when(persEception.getCause()).thenReturn(new NumberFormatException());
@@ -63,9 +66,11 @@ class HawkBitEclipseLinkJpaDialectTest {
.isInstanceOf(UncategorizedDataAccessException.class);
}
/**
* Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly.
* Cause of RuntimeException is an SQLException.
*/
@Test
@Description("Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly. Cause of "
+ "RuntimeException is an SQLException.")
void runtimeExceptionWithSqlDeadLockExceptionIsConcurrencyFailureException() {
final RuntimeException persEception = mock(RuntimeException.class);
when(persEception.getCause()).thenReturn(new SQLException("simulated transaction ER_LOCK_DEADLOCK", "40001"));
@@ -74,9 +79,11 @@ class HawkBitEclipseLinkJpaDialectTest {
.isInstanceOf(ConcurrencyFailureException.class);
}
/**
* Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly. Cause of
* RuntimeException is not an SQLException.
*/
@Test
@Description("Use Case: RuntimeException that could not be mapped by EclipseLinkJpaDialect directly. Cause of "
+ "RuntimeException is not an SQLException.")
void runtimeExceptionWithNumberFormatExceptionIsNull() {
final RuntimeException persEception = mock(RuntimeException.class);
when(persEception.getCause()).thenReturn(new NumberFormatException());

View File

@@ -15,18 +15,16 @@ import static org.assertj.core.api.Assertions.fail;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Entity Id Events
*/
@Feature("Component Tests - Repository")
@Story("Entity Id Events")
class RemoteIdEventTest extends AbstractRemoteEventTest {
private static final long ENTITY_ID = 1L;
@@ -36,41 +34,47 @@ class RemoteIdEventTest extends AbstractRemoteEventTest {
private static final String CONTROLLER_ID = "controller911";
private static final String ADDRESS = "amqp://anyhost";
@Test
@Description("Verifies that the ds id is correct reloaded")
void testDistributionSetDeletedEvent() {
/**
* Verifies that the ds id is correct reloaded
*/
@Test void testDistributionSetDeletedEvent() {
assertAndCreateRemoteEvent(DistributionSetDeletedEvent.class);
}
@Test
@Description("Verifies that the ds tag id is correct reloaded")
void testDistributionSetTagDeletedEvent() {
/**
* Verifies that the ds tag id is correct reloaded
*/
@Test void testDistributionSetTagDeletedEvent() {
assertAndCreateRemoteEvent(DistributionSetTagDeletedEvent.class);
}
@Test
@Description("Verifies that the target id is correct reloaded")
void testTargetDeletedEvent() {
/**
* Verifies that the target id is correct reloaded
*/
@Test void testTargetDeletedEvent() {
final TargetDeletedEvent deletedEvent = new TargetDeletedEvent(TENANT, ENTITY_ID, CONTROLLER_ID, ADDRESS,
ENTITY_CLASS, NODE);
assertEntity(deletedEvent);
}
@Test
@Description("Verifies that the target tag id is correct reloaded")
void testTargetTagDeletedEvent() {
/**
* Verifies that the target tag id is correct reloaded
*/
@Test void testTargetTagDeletedEvent() {
assertAndCreateRemoteEvent(TargetTagDeletedEvent.class);
}
@Test
@Description("Verifies that the software module id is correct reloaded")
void testSoftwareModuleDeletedEvent() {
/**
* Verifies that the software module id is correct reloaded
*/
@Test void testSoftwareModuleDeletedEvent() {
assertAndCreateRemoteEvent(SoftwareModuleDeletedEvent.class);
}
@Test
@Description("Verifies that the rollout id is correct reloaded")
void testRolloutDeletedEvent() {
/**
* Verifies that the rollout id is correct reloaded
*/
@Test void testRolloutDeletedEvent() {
assertAndCreateRemoteEvent(RolloutDeletedEvent.class);
}

View File

@@ -13,9 +13,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
@@ -24,16 +21,19 @@ import org.eclipse.hawkbit.repository.model.ActionProperties;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository")
@Story("RemoteTenantAwareEvent Tests")
/**
* Feature: Component Tests - Repository<br/>
* Story: RemoteTenantAwareEvent Tests
*/
class RemoteTenantAwareEventTest extends AbstractRemoteEventTest {
private static final String TENANT_DEFAULT = "DEFAULT";
private static final String APPLICATION_ID_DEFAULT = "Node";
@Test
@Description("Verifies that a testMultiActionAssignEvent can be properly serialized and deserialized")
void testMultiActionAssignEvent() {
/**
* Verifies that a testMultiActionAssignEvent can be properly serialized and deserialized
*/
@Test void testMultiActionAssignEvent() {
final List<String> controllerIds = List.of("id0", "id1", "id2", "id3", "id4loooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnng");
final List<Action> actions = controllerIds.stream().map(this::createAction).toList();
@@ -49,9 +49,10 @@ class RemoteTenantAwareEventTest extends AbstractRemoteEventTest {
assertThat(remoteAssignEventJackson.getControllerIds()).containsExactlyElementsOf(controllerIds);
}
@Test
@Description("Verifies that a MultiActionCancelEvent can be properly serialized and deserialized")
void testMultiActionCancelEvent() {
/**
* Verifies that a MultiActionCancelEvent can be properly serialized and deserialized
*/
@Test void testMultiActionCancelEvent() {
final List<String> controllerIds = List.of("id0", "id1", "id2", "id3", "id4loooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnng");
final List<Action> actions = controllerIds.stream().map(this::createAction).toList();
@@ -67,9 +68,10 @@ class RemoteTenantAwareEventTest extends AbstractRemoteEventTest {
assertThat(remoteCancelEventJackson.getControllerIds()).containsExactlyElementsOf(controllerIds);
}
@Test
@Description("Verifies that a DownloadProgressEvent can be properly serialized and deserialized")
void reloadDownloadProgressByRemoteEvent() {
/**
* Verifies that a DownloadProgressEvent can be properly serialized and deserialized
*/
@Test void reloadDownloadProgressByRemoteEvent() {
final DownloadProgressEvent downloadProgressEvent = new DownloadProgressEvent(TENANT_DEFAULT, 1L, 3L,
APPLICATION_ID_DEFAULT);
@@ -80,9 +82,10 @@ class RemoteTenantAwareEventTest extends AbstractRemoteEventTest {
assertThat(downloadProgressEvent).isEqualTo(remoteEventJackson);
}
@Test
@Description("Verifies that a TargetAssignDistributionSetEvent can be properly serialized and deserialized")
void testTargetAssignDistributionSetEvent() {
/**
* Verifies that a TargetAssignDistributionSetEvent can be properly serialized and deserialized
*/
@Test void testTargetAssignDistributionSetEvent() {
final DistributionSet dsA = testdataFactory.createDistributionSet("");
@@ -107,9 +110,10 @@ class RemoteTenantAwareEventTest extends AbstractRemoteEventTest {
assertTargetAssignDistributionSetEvent(action, remoteEventJackson);
}
@Test
@Description("Verifies that a TargetAssignDistributionSetEvent can be properly serialized and deserialized")
void testCancelTargetAssignmentEvent() {
/**
* Verifies that a TargetAssignDistributionSetEvent can be properly serialized and deserialized
*/
@Test void testCancelTargetAssignmentEvent() {
final DistributionSet dsA = testdataFactory.createDistributionSet("");

View File

@@ -15,15 +15,14 @@ import static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.event.remote.AbstractRemoteEventTest;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Entity Events
*/
@Feature("Component Tests - Repository")
@Story("Entity Events")
public abstract class AbstractRemoteEntityEventTest<E> extends AbstractRemoteEventTest {
protected RemoteEntityEvent<?> assertAndCreateRemoteEvent(final Class<? extends RemoteEntityEvent<?>> eventType) {

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.event.remote.entity;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
@@ -24,20 +21,23 @@ import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test ActionCreatedEvent and ActionUpdatedEvent
*/
@Feature("Component Tests - Repository")
@Story("Test ActionCreatedEvent and ActionUpdatedEvent")
class ActionEventTest extends AbstractRemoteEntityEventTest<Action> {
@Test
@Description("Verifies that the action entity reloading by remote created works")
void testActionCreatedEvent() {
/**
* Verifies that the action entity reloading by remote created works
*/
@Test void testActionCreatedEvent() {
assertAndCreateRemoteEvent(ActionCreatedEvent.class);
}
@Test
@Description("Verifies that the action entity reloading by remote updated works")
void testActionUpdatedEvent() {
/**
* Verifies that the action entity reloading by remote updated works
*/
@Test void testActionUpdatedEvent() {
assertAndCreateRemoteEvent(ActionUpdatedEvent.class);
}

View File

@@ -9,22 +9,21 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test DistributionSetCreatedEvent
*/
@Feature("Component Tests - Repository")
@Story("Test DistributionSetCreatedEvent")
class DistributionSetCreatedEventTest extends AbstractRemoteEntityEventTest<DistributionSet> {
@Test
@Description("Verifies that the distribution set entity reloading by remote created event works")
void testDistributionSetCreatedEvent() {
/**
* Verifies that the distribution set entity reloading by remote created event works
*/
@Test void testDistributionSetCreatedEvent() {
assertAndCreateRemoteEvent(DistributionSetCreatedEvent.class);
}

View File

@@ -9,28 +9,28 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test DistributionSetTagCreatedEvent and DistributionSetTagUpdateEvent
*/
@Feature("Component Tests - Repository")
@Story("Test DistributionSetTagCreatedEvent and DistributionSetTagUpdateEvent")
class DistributionSetTagEventTest extends AbstractRemoteEntityEventTest<DistributionSetTag> {
@Test
@Description("Verifies that the distribution set tag entity reloading by remote created event works")
void testDistributionSetTagCreatedEvent() {
/**
* Verifies that the distribution set tag entity reloading by remote created event works
*/
@Test void testDistributionSetTagCreatedEvent() {
assertAndCreateRemoteEvent(DistributionSetTagCreatedEvent.class);
}
@Test
@Description("Verifies that the distribution set tag entity reloading by remote updated event works")
void testDistributionSetTagUpdateEvent() {
/**
* Verifies that the distribution set tag entity reloading by remote updated event works
*/
@Test void testDistributionSetTagUpdateEvent() {
assertAndCreateRemoteEvent(DistributionSetTagUpdatedEvent.class);
}

View File

@@ -9,22 +9,21 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test DistributionSetUpdateEvent
*/
@Feature("Component Tests - Repository")
@Story("Test DistributionSetUpdateEvent")
class DistributionSetUpdatedEventTest extends AbstractRemoteEntityEventTest<DistributionSet> {
@Test
@Description("Verifies that the distribution set entity reloading by remote updated event works")
void testDistributionSetUpdateEvent() {
/**
* Verifies that the distribution set entity reloading by remote updated event works
*/
@Test void testDistributionSetUpdateEvent() {
assertAndCreateRemoteEvent(DistributionSetUpdatedEvent.class);
}

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.event.remote.entity;
import java.util.Collections;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
@@ -23,14 +20,16 @@ import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test RolloutUpdatedEvent
*/
@Feature("Component Tests - Repository")
@Story("Test RolloutUpdatedEvent")
class RolloutEventTest extends AbstractRemoteEntityEventTest<Rollout> {
@Test
@Description("Verifies that the rollout entity reloading by remote updated event works")
void testRolloutUpdatedEvent() {
/**
* Verifies that the rollout entity reloading by remote updated event works
*/
@Test void testRolloutUpdatedEvent() {
assertAndCreateRemoteEvent(RolloutUpdatedEvent.class);
}

View File

@@ -14,9 +14,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.UUID;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
@@ -27,22 +24,25 @@ import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test RolloutGroupCreatedEvent and RolloutGroupUpdatedEvent
*/
@Feature("Component Tests - Repository")
@Story("Test RolloutGroupCreatedEvent and RolloutGroupUpdatedEvent")
class RolloutGroupEventTest extends AbstractRemoteEntityEventTest<RolloutGroup> {
@Test
@Description("Verifies that the rollout group entity reloading by remote created event works")
void testRolloutGroupCreatedEvent() {
/**
* Verifies that the rollout group entity reloading by remote created event works
*/
@Test void testRolloutGroupCreatedEvent() {
final RolloutGroupCreatedEvent createdEvent = (RolloutGroupCreatedEvent) assertAndCreateRemoteEvent(
RolloutGroupCreatedEvent.class);
assertThat(createdEvent.getRolloutId()).isNotNull();
}
@Test
@Description("Verifies that the rollout group entity reloading by remote updated event works")
void testRolloutGroupUpdatedEvent() {
/**
* Verifies that the rollout group entity reloading by remote updated event works
*/
@Test void testRolloutGroupUpdatedEvent() {
assertAndCreateRemoteEvent(RolloutGroupUpdatedEvent.class);
}

View File

@@ -9,28 +9,28 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test SoftwareModuleCreatedEvent, SoftwareModuleUpdatedEvent
*/
@Feature("Component Tests - Repository")
@Story("Test SoftwareModuleCreatedEvent, SoftwareModuleUpdatedEvent")
class SoftwareModuleEventTest extends AbstractRemoteEntityEventTest<SoftwareModule> {
@Test
@Description("Verifies that the software module entity reloading by remote created event works")
void testTargetCreatedEvent() {
/**
* Verifies that the software module entity reloading by remote created event works
*/
@Test void testTargetCreatedEvent() {
assertAndCreateRemoteEvent(SoftwareModuleCreatedEvent.class);
}
@Test
@Description("Verifies that the software module entity reloading by remote updated event works")
void testTargetUpdatedEvent() {
/**
* Verifies that the software module entity reloading by remote updated event works
*/
@Test void testTargetUpdatedEvent() {
assertAndCreateRemoteEvent(SoftwareModuleUpdatedEvent.class);
}

View File

@@ -9,28 +9,28 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.Target;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test TargetCreatedEvent, TargetUpdatedEvent and CancelTargetAssignmentEvent
*/
@Feature("Component Tests - Repository")
@Story("Test TargetCreatedEvent, TargetUpdatedEvent and CancelTargetAssignmentEvent")
class TargetEventTest extends AbstractRemoteEntityEventTest<Target> {
@Test
@Description("Verifies that the target entity reloading by remote created event works")
void testTargetCreatedEvent() {
/**
* Verifies that the target entity reloading by remote created event works
*/
@Test void testTargetCreatedEvent() {
assertAndCreateRemoteEvent(TargetCreatedEvent.class);
}
@Test
@Description("Verifies that the target entity reloading by remote updated event works")
void testTargetUpdatedEvent() {
/**
* Verifies that the target entity reloading by remote updated event works
*/
@Test void testTargetUpdatedEvent() {
assertAndCreateRemoteEvent(TargetUpdatedEvent.class);
}

View File

@@ -9,28 +9,28 @@
*/
package org.eclipse.hawkbit.repository.event.remote.entity;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.model.TargetTag;
import org.junit.jupiter.api.Test;
/**
* Test the remote entity events.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Test TargetTagCreatedEvent and TargetTagUpdateEvent
*/
@Feature("Component Tests - Repository")
@Story("Test TargetTagCreatedEvent and TargetTagUpdateEvent")
class TargetTagEventTest extends AbstractRemoteEntityEventTest<TargetTag> {
@Test
@Description("Verifies that the target tag entity reloading by remote created event works")
void testTargetTagCreatedEvent() {
/**
* Verifies that the target tag entity reloading by remote created event works
*/
@Test void testTargetTagCreatedEvent() {
assertAndCreateRemoteEvent(TargetTagCreatedEvent.class);
}
@Test
@Description("Verifies that the target tag entity reloading by remote updated event works")
void testTargetTagUpdateEventt() {
/**
* Verifies that the target tag entity reloading by remote updated event works
*/
@Test void testTargetTagUpdateEventt() {
assertAndCreateRemoteEvent(TargetTagUpdatedEvent.class);
}

View File

@@ -11,7 +11,6 @@ package org.eclipse.hawkbit.repository.jpa;
import java.util.List;
import io.qameta.allure.Description;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.junit.jupiter.api.Test;
@@ -34,76 +33,87 @@ public abstract class AbstractRepositoryManagementSecurityTest<T, C, U> extends
*/
protected abstract U getUpdateObject();
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
void createCollectionPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test void createCollectionPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().create(List.of(getCreateObject())), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
void createPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().create(getCreateObject()), List.of(SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
void updatePermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionCheck() {
assertPermissions(() -> getRepositoryManagement().update(getUpdateObject()), List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
void deletePermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionCheck() {
assertPermissions(() -> {
getRepositoryManagement().delete(1L);
return null;
}, List.of(SpPermission.DELETE_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void countPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void countPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().count(), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void deleteCollectionRepositoryManagement() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void deleteCollectionRepositoryManagement() {
assertPermissions(() -> {
getRepositoryManagement().delete(List.of(1L));
return null;
}, List.of(SpPermission.DELETE_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void getPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void getPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().get(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void getCollectionPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void getCollectionPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().get(List.of(1L)), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void existsCollectionPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void existsCollectionPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().exists(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void findAllPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void findAllPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().findAll(Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.")
public void findByRsqlPermissionCheck() {
/**
* Tests RepositoryManagement PreAuthorized method with correct and insufficient permissions.
*/
@Test public void findByRsqlPermissionCheck() {
assertPermissions(() -> getRepositoryManagement().findByRsql("(name==*)", Pageable.ofSize(1)), List.of(SpPermission.READ_REPOSITORY));
}

View File

@@ -19,9 +19,6 @@ import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.awaitility.Awaitility;
import org.eclipse.hawkbit.repository.exception.StopRolloutException;
import org.eclipse.hawkbit.repository.jpa.model.JpaRolloutGroup;
@@ -46,16 +43,18 @@ import org.springframework.test.context.TestPropertySource;
/**
* Test class testing the invalidation of a {@link DistributionSet} while the
* handle rollouts is ongoing.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Concurrent Distribution Set invalidation
*/
@Feature("Component Tests - Repository")
@Story("Concurrent Distribution Set invalidation")
@ContextConfiguration(classes = ConcurrentDistributionSetInvalidationTest.Config.class)
@TestPropertySource(properties = { "hawkbit.server.repository.dsInvalidationLockTimeout=1" })
class ConcurrentDistributionSetInvalidationTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verify that a large rollout causes a timeout when trying to invalidate a distribution set")
void verifyInvalidateDistributionSetWithLargeRolloutThrowsException() {
/**
* Verify that a large rollout causes a timeout when trying to invalidate a distribution set
*/
@Test void verifyInvalidateDistributionSetWithLargeRolloutThrowsException() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final Rollout rollout = createRollout(distributionSet);
final String tenant = tenantAware.getCurrentTenant();

View File

@@ -15,9 +15,6 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.ContextAware;
import org.eclipse.hawkbit.repository.autoassign.AutoAssignExecutor;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -32,8 +29,10 @@ import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
@Feature("Component Tests - Context runner")
@Story("Test Context Runner")
/**
* Feature: Component Tests - Context runner<br/>
* Story: Test Context Runner
*/
class ContextAwareTest extends AbstractJpaIntegrationTest {
@Autowired
@@ -51,9 +50,10 @@ class ContextAwareTest extends AbstractJpaIntegrationTest {
reset(contextAware);
}
@Test
@Description("Verifies acm context is persisted when creating Rollout")
void verifyAcmContextIsPersistedInCreatedRollout() {
/**
* Verifies acm context is persisted when creating Rollout
*/
@Test void verifyAcmContextIsPersistedInCreatedRollout() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
assertThat(securityContext).isNotNull();
@@ -63,9 +63,10 @@ class ContextAwareTest extends AbstractJpaIntegrationTest {
assertThat(SECURITY_CONTEXT_SERIALIZER.deserialize(ctx)).isEqualTo(securityContext));
}
@Test
@Description("Verifies acm context is reused when handling a rollout")
void verifyContextIsReusedWhenHandlingRollout() {
/**
* Verifies acm context is reused when handling a rollout
*/
@Test void verifyContextIsReusedWhenHandlingRollout() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
assertThat(securityContext).isNotNull();
@@ -74,9 +75,10 @@ class ContextAwareTest extends AbstractJpaIntegrationTest {
verify(contextAware).runInContext(eq(SECURITY_CONTEXT_SERIALIZER.serialize(securityContext)), any(Runnable.class));
}
@Test
@Description("Verifies acm context is persisted when activating auto assignment")
void verifyContextIsPersistedInActiveAutoAssignment() {
/**
* Verifies acm context is persisted when activating auto assignment
*/
@Test void verifyContextIsPersistedInActiveAutoAssignment() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
assertThat(securityContext).isNotNull();
@@ -86,9 +88,10 @@ class ContextAwareTest extends AbstractJpaIntegrationTest {
assertThat(SECURITY_CONTEXT_SERIALIZER.deserialize(ctx)).isEqualTo(securityContext));
}
@Test
@Description("Verifies acm context is used when performing auto assign check on all target")
void verifyContextIsReusedWhenCheckingForAutoAssignmentAllTargets() {
/**
* Verifies acm context is used when performing auto assign check on all target
*/
@Test void verifyContextIsReusedWhenCheckingForAutoAssignmentAllTargets() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
assertThat(securityContext).isNotNull();
@@ -97,9 +100,10 @@ class ContextAwareTest extends AbstractJpaIntegrationTest {
verify(contextAware).runInContext(eq(SECURITY_CONTEXT_SERIALIZER.serialize(securityContext)), any(Runnable.class));
}
@Test
@Description("Verifies acm context is used when performing auto assign check on single target")
void verifyContextIsReusedWhenCheckingForAutoAssignmentSingleTarget() {
/**
* Verifies acm context is used when performing auto assign check on single target
*/
@Test void verifyContextIsReusedWhenCheckingForAutoAssignmentSingleTarget() {
final SecurityContext securityContext = SecurityContextHolder.getContext();
assertThat(securityContext).isNotNull();

View File

@@ -20,9 +20,6 @@ import java.util.Map;
import jakarta.persistence.criteria.Predicate;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.builder.AutoAssignDistributionSetUpdate;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
@@ -41,13 +38,16 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
@Feature("Component Tests - Access Control")
@Story("Test Distribution Set Access Controller")
/**
* Feature: Component Tests - Access Control<br/>
* Story: Test Distribution Set Access Controller
*/
class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
@Test
@Description("Verifies read access rules for distribution sets")
void verifyDistributionSetReadOperations() {
/**
* Verifies read access rules for distribution sets
*/
@Test void verifyDistributionSetReadOperations() {
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE);
@@ -116,9 +116,10 @@ class DistributionSetAccessControllerTest extends AbstractAccessControllerTest {
.as("Action is hidden.").isInstanceOf(InsufficientPermissionException.class);
}
@Test
@Description("Verifies read access rules for distribution sets")
void verifyDistributionSetUpdates() {
/**
* Verifies read access rules for distribution sets
*/
@Test void verifyDistributionSetUpdates() {
// permit all operations first to prepare test setup
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);

View File

@@ -18,9 +18,6 @@ import java.util.List;
import jakarta.persistence.criteria.Predicate;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException;
@@ -42,16 +39,19 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
@Feature("Component Tests - Access Control")
@Story("Test Target Access Controller")
/**
* Feature: Component Tests - Access Control<br/>
* Story: Test Target Access Controller
*/
class TargetAccessControllerTest extends AbstractAccessControllerTest {
@Autowired
AutoAssignChecker autoAssignChecker;
@Test
@Description("Verifies read access rules for targets")
void verifyTargetReadOperations() {
/**
* Verifies read access rules for targets
*/
@Test void verifyTargetReadOperations() {
permitAllOperations(AccessController.Operation.CREATE);
final Target permittedTarget = targetManagement
@@ -203,9 +203,10 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
.isInstanceOf(InsufficientPermissionException.class);
}
@Test
@Description("Verifies rules for target assignment")
void verifyTargetAssignment() {
/**
* Verifies rules for target assignment
*/
@Test void verifyTargetAssignment() {
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE);
@@ -249,9 +250,10 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
.map(Identifiable::getId).toList()).containsOnly(permittedTarget.getId());
}
@Test
@Description("Verifies rules for target assignment")
void verifyTargetAssignmentOnNonUpdatableTarget() {
/**
* Verifies rules for target assignment
*/
@Test void verifyTargetAssignmentOnNonUpdatableTarget() {
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE);
@@ -289,9 +291,10 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
Action.ActionType.FORCED).getAssigned()).isEqualTo(1);
}
@Test
@Description("Verifies only manageable targets are part of the rollout")
void verifyRolloutTargetScope() {
/**
* Verifies only manageable targets are part of the rollout
*/
@Test void verifyRolloutTargetScope() {
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE);
@@ -330,9 +333,10 @@ class TargetAccessControllerTest extends AbstractAccessControllerTest {
.anyMatch(readTarget -> readTarget.getId().equals(target.getId())));
}
@Test
@Description("Verifies only manageable targets are part of an auto assignment.")
void verifyAutoAssignmentTargetScope() {
/**
* Verifies only manageable targets are part of an auto assignment.
*/
@Test void verifyAutoAssignmentTargetScope() {
permitAllOperations(AccessController.Operation.READ);
permitAllOperations(AccessController.Operation.CREATE);
permitAllOperations(AccessController.Operation.UPDATE);

View File

@@ -16,9 +16,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.Identifiable;
import org.eclipse.hawkbit.repository.builder.TargetTypeCreate;
import org.eclipse.hawkbit.repository.builder.TargetTypeUpdate;
@@ -31,13 +28,16 @@ import org.eclipse.hawkbit.repository.model.TargetType;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
@Feature("Component Tests - Access Control")
@Story("Test Target Type Access Controller")
/**
* Feature: Component Tests - Access Control<br/>
* Story: Test Target Type Access Controller
*/
class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
@Test
@Description("Verifies read access rules for target types")
void verifyTargetTypeReadOperations() {
/**
* Verifies read access rules for target types
*/
@Test void verifyTargetTypeReadOperations() {
permitAllOperations(AccessController.Operation.CREATE);
final TargetType permittedTargetType = targetTypeManagement.create(entityFactory.targetType().create().name("type1"));
final TargetType hiddenTargetType = targetTypeManagement.create(entityFactory.targetType().create().name("type2"));
@@ -96,9 +96,10 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
.isInstanceOf(EntityNotFoundException.class);
}
@Test
@Description("Verifies delete access rules for target types")
void verifyTargetTypeDeleteOperations() {
/**
* Verifies delete access rules for target types
*/
@Test void verifyTargetTypeDeleteOperations() {
permitAllOperations(AccessController.Operation.CREATE);
final TargetType manageableTargetType = targetTypeManagement.create(entityFactory.targetType().create().name("type1"));
@@ -119,9 +120,10 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
.isInstanceOfAny(InsufficientPermissionException.class, EntityNotFoundException.class);
}
@Test
@Description("Verifies update operation for target types")
void verifyTargetTypeUpdateOperations() {
/**
* Verifies update operation for target types
*/
@Test void verifyTargetTypeUpdateOperations() {
permitAllOperations(AccessController.Operation.CREATE);
final TargetType manageableTargetType = targetTypeManagement
.create(entityFactory.targetType().create().name("type1"));
@@ -146,9 +148,10 @@ class TargetTypeAccessControllerTest extends AbstractAccessControllerTest {
.isInstanceOf(InsufficientPermissionException.class);
}
@Test
@Description("Verifies create operation blocked by controller")
void verifyTargetTypeCreationBlockedByAccessController() {
/**
* Verifies create operation blocked by controller
*/
@Test void verifyTargetTypeCreationBlockedByAccessController() {
defineAccess(AccessController.Operation.CREATE); // allows for none
// verify targetTypeManagement#create for any type
final TargetTypeCreate targetTypeCreate = entityFactory.targetType().create().name("type1");

View File

@@ -20,10 +20,6 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.builder.AutoAssignDistributionSetUpdate;
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
@@ -49,9 +45,10 @@ import org.springframework.data.domain.Slice;
/**
* Test class for {@link AutoAssignChecker}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Auto assign checker
*/
@Feature("Component Tests - Repository")
@Story("Auto assign checker")
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@@ -62,9 +59,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
@Autowired
private DeploymentManagement deploymentManagement;
@Test
@Description("Verifies that a running action is auto canceled by a AutoAssignment which assigns another distribution-set.")
void autoAssignDistributionSetAndAutoCloseOldActions() {
/**
* Verifies that a running action is auto canceled by a AutoAssignment which assigns another distribution-set.
*/
@Test void autoAssignDistributionSetAndAutoCloseOldActions() {
tenantConfigurationManagement
.addOrUpdateConfiguration(TenantConfigurationKey.REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED, true);
@@ -106,9 +104,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Test auto assignment of a DS to filtered targets")
void checkAutoAssign() {
/**
* Test auto assignment of a DS to filtered targets
*/
@Test void checkAutoAssign() {
// will be auto assigned
final DistributionSet setA = testdataFactory.createDistributionSet("dsA");
final DistributionSet setB = testdataFactory.createDistributionSet("dsB");
@@ -158,9 +157,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
verifyThatCreatedActionsAreInitiatedByCurrentUser(targetFilterQuery, setA, targets);
}
@Test
@Description("Test auto assignment of a DS for a specific device")
void checkAutoAssignmentForDevice() {
/**
* Test auto assignment of a DS for a specific device
*/
@Test void checkAutoAssignmentForDevice() {
final DistributionSet toAssignDs = testdataFactory.createDistributionSet();
@@ -182,9 +182,11 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
verifyThatTargetsNotHaveDistributionSetAssignment(toAssignDs, targets.subList(1, 25));
}
/**
* Test auto assignment of a DS to filtered targets with different confirmation options
*/
@ParameterizedTest
@MethodSource("confirmationOptions")
@Description("Test auto assignment of a DS to filtered targets with different confirmation options")
void checkAutoAssignWithConfirmationOptions(final boolean confirmationFlowActive, final boolean confirmationRequired,
final Action.Status expectedStatus) {
@@ -210,9 +212,11 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
verifyThatTargetsHaveDistributionSetAssignedAndActionStatus(distributionSet, targets, expectedStatus);
}
/**
* Test auto assignment of a DS for a specific device with different confirmation options
*/
@ParameterizedTest
@MethodSource("confirmationOptions")
@Description("Test auto assignment of a DS for a specific device with different confirmation options")
void checkAutoAssignmentForDeviceWithConfirmationRequired(final boolean confirmationFlowActive,
final boolean confirmationRequired, final Action.Status expectedStatus) {
@@ -237,9 +241,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
verifyThatTargetsNotHaveDistributionSetAssignment(toAssignDs, targets.subList(1, 25));
}
@Test
@Description("Test auto assignment of an incomplete DS to filtered targets, that causes failures")
void checkAutoAssignWithFailures() {
/**
* Test auto assignment of an incomplete DS to filtered targets, that causes failures
*/
@Test void checkAutoAssignWithFailures() {
// incomplete distribution set that will be assigned
final DistributionSet setF = distributionSetManagement.create(entityFactory.distributionSet().create()
@@ -286,9 +291,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Test auto assignment of a distribution set with FORCED, SOFT and DOWNLOAD_ONLY action types")
void checkAutoAssignWithDifferentActionTypes() {
/**
* Test auto assignment of a distribution set with FORCED, SOFT and DOWNLOAD_ONLY action types
*/
@Test void checkAutoAssignWithDifferentActionTypes() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final String targetDsAIdPref = "A";
final String targetDsBIdPref = "B";
@@ -315,9 +321,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
verifyThatTargetsHaveAssignmentActionType(ActionType.DOWNLOAD_ONLY, targetsC);
}
@Test
@Description("An auto assignment target filter with weight creates actions with weights")
void actionsWithWeightAreCreated() {
/**
* An auto assignment target filter with weight creates actions with weights
*/
@Test void actionsWithWeightAreCreated() {
final int amountOfTargets = 5;
final DistributionSet ds = testdataFactory.createDistributionSet();
final int weight = 32;
@@ -334,9 +341,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getWeight().get() == weight);
}
@Test
@Description("An auto assignment target filter without weight still works after multi assignment is enabled")
void filterWithoutWeightWorksInMultiAssignmentMode() {
/**
* An auto assignment target filter without weight still works after multi assignment is enabled
*/
@Test void filterWithoutWeightWorksInMultiAssignmentMode() {
final int amountOfTargets = 5;
final DistributionSet ds = testdataFactory.createDistributionSet();
targetFilterQueryManagement.create(
@@ -352,9 +360,10 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getWeight().isPresent());
}
@Test
@Description("Verifies an auto assignment only creates actions for compatible targets")
void checkAutoAssignmentWithIncompatibleTargets() {
/**
* Verifies an auto assignment only creates actions for compatible targets
*/
@Test void checkAutoAssignmentWithIncompatibleTargets() {
final int TARGET_COUNT = 5;
final DistributionSet testDs = testdataFactory.createDistributionSet();
@@ -414,7 +423,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
* @param set the expected distribution set
* @param targets the targets that should have it
*/
@Step
private void verifyThatTargetsHaveDistributionSetAssignment(
final DistributionSet set, final List<Target> targets, final int count) {
final List<Long> targetIds = targets.stream().map(Target::getId).toList();
@@ -430,7 +438,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
}
}
@Step
private void verifyThatTargetsHaveDistributionSetAssignedAndActionStatus(final DistributionSet set,
final List<Target> targets, final Action.Status status) {
final List<String> targetIds = targets.stream().map(Target::getControllerId).toList();
@@ -445,7 +452,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
assertThat(actionsByDs).allMatch(action -> action.getStatus() == status);
}
@Step
private void verifyThatTargetsNotHaveDistributionSetAssignment(final DistributionSet set,
final List<Target> targets) {
final List<Long> targetIds = targets.stream().map(Target::getId).toList();
@@ -460,7 +466,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
}
@Step
private void verifyThatCreatedActionsAreInitiatedByCurrentUser(final TargetFilterQuery targetFilterQuery,
final DistributionSet distributionSet, final List<Target> targets) {
final Set<String> targetIds = targets.stream().map(Target::getControllerId).collect(Collectors.toSet());
@@ -472,7 +477,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
.isEqualTo(targetFilterQuery.getAutoAssignInitiatedBy()));
}
@Step
private List<Target> createTargetsAndAutoAssignDistSet(final String prefix, final int targetCount,
final DistributionSet distributionSet, final ActionType actionType) {
@@ -485,7 +489,6 @@ class AutoAssignCheckerIntTest extends AbstractJpaIntegrationTest {
return targets;
}
@Step
private void verifyThatTargetsHaveAssignmentActionType(final ActionType actionType, final List<Target> targets) {
final List<Action> actions = targets.stream()
.map(Target::getControllerId)

View File

@@ -21,9 +21,6 @@ import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.ContextAware;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
@@ -42,8 +39,10 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.SliceImpl;
import org.springframework.transaction.PlatformTransactionManager;
@Feature("Unit Tests - Repository")
@Story("Auto assign checker")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Auto assign checker
*/
@ExtendWith(MockitoExtension.class)
class AutoAssignCheckerTest {
@@ -66,9 +65,10 @@ class AutoAssignCheckerTest {
transactionManager, contextAware);
}
@Test
@Description("Single device check triggers update for matching auto assignment filter.")
void checkForDevice() {
/**
* Single device check triggers update for matching auto assignment filter.
*/
@Test void checkForDevice() {
mockRunningAsNonSystem();
final String target = getRandomString();
final long ds = getRandomLong();

View File

@@ -17,9 +17,6 @@ import static org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationPrope
import java.util.Arrays;
import java.util.stream.Collectors;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
@@ -30,18 +27,20 @@ import org.springframework.beans.factory.annotation.Autowired;
/**
* Test class for {@link AutoActionCleanup}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Action cleanup handler
*/
@Feature("Component Tests - Repository")
@Story("Action cleanup handler")
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
@Autowired
private AutoActionCleanup autoActionCleanup;
@Test
@Description("Verifies that running actions are not cleaned up.")
void runningActionsAreNotCleanedUp() {
/**
* Verifies that running actions are not cleaned up.
*/
@Test void runningActionsAreNotCleanedUp() {
// cleanup config for this test case
setupCleanupConfiguration(true, 0, Action.Status.CANCELED, Action.Status.ERROR);
@@ -62,9 +61,10 @@ class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
assertThat(actionRepository.count()).isEqualTo(2);
}
@Test
@Description("Verifies that nothing is cleaned up if the cleanup is disabled.")
void cleanupDisabled() {
/**
* Verifies that nothing is cleaned up if the cleanup is disabled.
*/
@Test void cleanupDisabled() {
// cleanup config for this test case
setupCleanupConfiguration(false, 0, Action.Status.CANCELED);
@@ -87,9 +87,10 @@ class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
assertThat(actionRepository.count()).isEqualTo(2);
}
@Test
@Description("Verifies that canceled and failed actions are cleaned up.")
void canceledAndFailedActionsAreCleanedUp() {
/**
* Verifies that canceled and failed actions are cleaned up.
*/
@Test void canceledAndFailedActionsAreCleanedUp() {
// cleanup config for this test case
setupCleanupConfiguration(true, 0, Action.Status.CANCELED, Action.Status.ERROR);
@@ -118,9 +119,10 @@ class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
assertThat(actionRepository.findById(action3)).isPresent();
}
@Test
@Description("Verifies that canceled actions are cleaned up.")
void canceledActionsAreCleanedUp() {
/**
* Verifies that canceled actions are cleaned up.
*/
@Test void canceledActionsAreCleanedUp() {
// cleanup config for this test case
setupCleanupConfiguration(true, 0, Action.Status.CANCELED);
@@ -150,9 +152,10 @@ class AutoActionCleanupTest extends AbstractJpaIntegrationTest {
assertThat(actionRepository.findById(action3)).isPresent();
}
@Test
@Description("Verifies that canceled and failed actions are cleaned up once they expired.")
@SuppressWarnings("squid:S2925")
/**
* Verifies that canceled and failed actions are cleaned up once they expired.
*/
@Test @SuppressWarnings("squid:S2925")
void canceledAndFailedActionsAreCleanedUpWhenExpired() throws InterruptedException {
// cleanup config for this test case
setupCleanupConfiguration(true, 500, Action.Status.CANCELED, Action.Status.ERROR);

View File

@@ -14,9 +14,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -25,9 +22,10 @@ import org.springframework.integration.support.locks.LockRegistry;
/**
* Test class for {@link AutoCleanupScheduler}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Auto cleanup scheduler
*/
@Feature("Component Tests - Repository")
@Story("Auto cleanup scheduler")
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
@@ -41,9 +39,10 @@ class AutoCleanupSchedulerTest extends AbstractJpaIntegrationTest {
counter.set(0);
}
@Test
@Description("Verifies that all cleanup handlers are executed regardless if one of them throws an error")
void executeHandlerChain() {
/**
* Verifies that all cleanup handlers are executed regardless if one of them throws an error
*/
@Test void executeHandlerChain() {
new AutoCleanupScheduler(systemManagement, systemSecurityContext, lockRegistry, Arrays.asList(
new SuccessfulCleanup(), new SuccessfulCleanup(), new FailingCleanup(), new SuccessfulCleanup())).run();

View File

@@ -19,9 +19,6 @@ import java.util.concurrent.locks.Lock;
import javax.sql.DataSource;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@@ -43,8 +40,10 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Feature("Component Tests - Repository")
@Story("Distributed Lock")
/**
* Feature: Component Tests - Repository<br/>
* Story: Distributed Lock
*/
@SpringBootTest(classes = { DistributedLockTest.Config.class }, webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Slf4j
class DistributedLockTest extends AbstractJpaIntegrationTest {
@@ -94,9 +93,11 @@ class DistributedLockTest extends AbstractJpaIntegrationTest {
}
}
/**
* Test to verify that lock is kept while ping runs
*/
@SuppressWarnings({"java:S2925"})
@Test
@Description("Test to verify that lock is kept while ping runs")
void keepLockAlive() {
final LockRegistry lockRegistry0 = new JdbcLockRegistry(lockRepository0);
final LockRegistry lockRegistry1 = new JdbcLockRegistry(lockRepository1);

View File

@@ -15,9 +15,6 @@ import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.repository.event.TenantAwareEvent;
import org.eclipse.hawkbit.repository.event.remote.DistributionSetDeletedEvent;
@@ -47,8 +44,10 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
@Feature("Component Tests - Repository")
@Story("Entity Events")
/**
* Feature: Component Tests - Repository<br/>
* Story: Entity Events
*/
@SpringBootTest(classes = { RepositoryTestConfiguration.class }, webEnvironment = SpringBootTest.WebEnvironment.NONE)
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
@@ -61,9 +60,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
eventListener.queue.clear();
}
@Test
@Description("Verifies that the target created event is published when a target has been created")
void targetCreatedEventIsPublished() throws InterruptedException {
/**
* Verifies that the target created event is published when a target has been created
*/
@Test void targetCreatedEventIsPublished() throws InterruptedException {
final Target createdTarget = testdataFactory.createTarget("12345");
final TargetCreatedEvent targetCreatedEvent = eventListener.waitForEvent(TargetCreatedEvent.class);
@@ -71,9 +71,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(targetCreatedEvent)).isEqualTo(createdTarget.getId());
}
@Test
@Description("Verifies that the target update event is published when a target has been updated")
void targetUpdateEventIsPublished() throws InterruptedException {
/**
* Verifies that the target update event is published when a target has been updated
*/
@Test void targetUpdateEventIsPublished() throws InterruptedException {
final Target createdTarget = testdataFactory.createTarget("12345");
targetManagement.update(entityFactory.target().update(createdTarget.getControllerId()).name("updateName"));
@@ -82,9 +83,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(targetUpdatedEvent)).isEqualTo(createdTarget.getId());
}
@Test
@Description("Verifies that the target deleted event is published when a target has been deleted")
void targetDeletedEventIsPublished() throws InterruptedException {
/**
* Verifies that the target deleted event is published when a target has been deleted
*/
@Test void targetDeletedEventIsPublished() throws InterruptedException {
final Target createdTarget = testdataFactory.createTarget("12345");
targetManagement.deleteByControllerID("12345");
@@ -94,9 +96,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(targetDeletedEvent.getEntityId()).isEqualTo(createdTarget.getId());
}
@Test
@Description("Verifies that the target type created event is published when a target type has been created")
void targetTypeCreatedEventIsPublished() throws InterruptedException {
/**
* Verifies that the target type created event is published when a target type has been created
*/
@Test void targetTypeCreatedEventIsPublished() throws InterruptedException {
final TargetType createdTargetType = testdataFactory.findOrCreateTargetType("targettype");
final TargetTypeCreatedEvent targetTypeCreatedEvent = eventListener.waitForEvent(TargetTypeCreatedEvent.class);
@@ -104,9 +107,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(targetTypeCreatedEvent)).isEqualTo(createdTargetType.getId());
}
@Test
@Description("Verifies that the target type updated event is published when a target type has been updated")
void targetTypeUpdatedEventIsPublished() throws InterruptedException {
/**
* Verifies that the target type updated event is published when a target type has been updated
*/
@Test void targetTypeUpdatedEventIsPublished() throws InterruptedException {
final TargetType createdTargetType = testdataFactory.findOrCreateTargetType("targettype");
targetTypeManagement
.update(entityFactory.targetType().update(createdTargetType.getId()).name("updatedtargettype"));
@@ -116,9 +120,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(targetTypeUpdatedEvent)).isEqualTo(createdTargetType.getId());
}
@Test
@Description("Verifies that the target type deleted event is published when a target type has been deleted")
void targetTypeDeletedEventIsPublished() throws InterruptedException {
/**
* Verifies that the target type deleted event is published when a target type has been deleted
*/
@Test void targetTypeDeletedEventIsPublished() throws InterruptedException {
final TargetType createdTargetType = testdataFactory.findOrCreateTargetType("targettype");
targetTypeManagement.delete(createdTargetType.getId());
@@ -127,9 +132,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(targetTypeDeletedEvent.getEntityId()).isEqualTo(createdTargetType.getId());
}
@Test
@Description("Verifies that the rollout deleted event is published when a rollout has been deleted")
void rolloutDeletedEventIsPublished() throws InterruptedException {
/**
* Verifies that the rollout deleted event is published when a rollout has been deleted
*/
@Test void rolloutDeletedEventIsPublished() throws InterruptedException {
final int amountTargetsForRollout = 50;
final int amountGroups = 5;
final String successCondition = "50";
@@ -150,9 +156,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(rolloutDeletedEvent.getEntityId()).isEqualTo(createdRollout.getId());
}
@Test
@Description("Verifies that the distribution set created event is published when a distribution set has been created")
void distributionSetCreatedEventIsPublished() throws InterruptedException {
/**
* Verifies that the distribution set created event is published when a distribution set has been created
*/
@Test void distributionSetCreatedEventIsPublished() throws InterruptedException {
final DistributionSet createDistributionSet = testdataFactory.createDistributionSet();
final DistributionSetCreatedEvent dsCreatedEvent = eventListener
@@ -161,9 +168,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(dsCreatedEvent)).isEqualTo(createDistributionSet.getId());
}
@Test
@Description("Verifies that the distribution set deleted event is published when a distribution set has been deleted")
void distributionSetDeletedEventIsPublished() throws InterruptedException {
/**
* Verifies that the distribution set deleted event is published when a distribution set has been deleted
*/
@Test void distributionSetDeletedEventIsPublished() throws InterruptedException {
final DistributionSet createDistributionSet = testdataFactory.createDistributionSet();
distributionSetManagement.delete(createDistributionSet.getId());
@@ -174,9 +182,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(dsDeletedEvent.getEntityId()).isEqualTo(createDistributionSet.getId());
}
@Test
@Description("Verifies that the software module created event is published when a software module has been created")
void softwareModuleCreatedEventIsPublished() throws InterruptedException {
/**
* Verifies that the software module created event is published when a software module has been created
*/
@Test void softwareModuleCreatedEventIsPublished() throws InterruptedException {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModuleApp();
final SoftwareModuleCreatedEvent softwareModuleCreatedEvent = eventListener
@@ -185,9 +194,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(softwareModuleCreatedEvent)).isEqualTo(softwareModule.getId());
}
@Test
@Description("Verifies that the software module update event is published when a software module has been updated")
void softwareModuleUpdateEventIsPublished() throws InterruptedException {
/**
* Verifies that the software module update event is published when a software module has been updated
*/
@Test void softwareModuleUpdateEventIsPublished() throws InterruptedException {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModuleApp();
softwareModuleManagement
.update(entityFactory.softwareModule().update(softwareModule.getId()).description("New"));
@@ -198,9 +208,10 @@ class RepositoryEntityEventTest extends AbstractJpaIntegrationTest {
assertThat(getIdOfEntity(softwareModuleUpdatedEvent)).isEqualTo(softwareModule.getId());
}
@Test
@Description("Verifies that the software module deleted event is published when a software module has been deleted")
void softwareModuleDeletedEventIsPublished() throws InterruptedException {
/**
* Verifies that the software module deleted event is published when a software module has been deleted
*/
@Test void softwareModuleDeletedEventIsPublished() throws InterruptedException {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModuleApp();
softwareModuleManagement.delete(softwareModule.getId());

View File

@@ -14,9 +14,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.awaitility.Awaitility;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
@@ -28,16 +25,19 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository")
@Story("Deployment Management")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Deployment Management
*/
class ActionTest extends AbstractJpaIntegrationTest {
private Target target;
private DistributionSet distributionSet;
@Test
@Description("Ensures that timeforced moded switch from soft to forces after defined timeframe.")
void timeForcedHitNewHasCodeIsGenerated() {
/**
* Ensures that timeforced moded switch from soft to forces after defined timeframe.
*/
@Test void timeForcedHitNewHasCodeIsGenerated() {
// current time + 1 seconds
final long sleepTime = 1000;
final long timeForceTimeAt = System.currentTimeMillis() + sleepTime;
@@ -50,9 +50,10 @@ class ActionTest extends AbstractJpaIntegrationTest {
Awaitility.await().atMost(Duration.ofSeconds(2)).pollInterval(Duration.ofMillis(100)).until(timeforcedAction::isForcedOrTimeForced);
}
@Test
@Description("Tests the action type mapping.")
void testActionTypeConvert() {
/**
* Tests the action type mapping.
*/
@Test void testActionTypeConvert() {
final long id = createAction().getId();
for (final ActionType actionType : ActionType.values()) {
final JpaAction action = actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
@@ -63,9 +64,10 @@ class ActionTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Tests the status mapping.")
void testStatusConvert() {
/**
* Tests the status mapping.
*/
@Test void testStatusConvert() {
final long id = createAction().getId();
for (final Status status : Status.values()) {
final JpaAction action = actionRepository.findById(id).orElseThrow(() -> new IllegalStateException("Action not found"));
@@ -76,9 +78,10 @@ class ActionTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Tests the action status status mapping.")
void testActionsStatusStatusConvert() {
/**
* Tests the action status status mapping.
*/
@Test void testActionsStatusStatusConvert() {
for (final Status status : Status.values()) {
final long id = createAction().getId();
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(id).status(status));

View File

@@ -12,87 +12,96 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.io.ByteArrayInputStream;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.ArtifactUpload;
import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - ArtifactManagement")
@Story("SecurityTests ArtifactManagement")
/**
* Feature: SecurityTests - ArtifactManagement<br/>
* Story: SecurityTests ArtifactManagement
*/
class ArtifactManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ArtifactManagement#count() method")
@WithUser(principal = "user", authorities = { SpPermission.READ_REPOSITORY })
/**
* Tests ArtifactManagement#count() method
*/
@Test @WithUser(principal = "user", authorities = { SpPermission.READ_REPOSITORY })
void countPermissionCheck() {
assertPermissions(() -> artifactManagement.count(), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#create() method")
void createPermissionCheck() {
/**
* Tests ArtifactManagement#create() method
*/
@Test void createPermissionCheck() {
ArtifactUpload artifactUpload = new ArtifactUpload(new ByteArrayInputStream("RandomString".getBytes()), 1L, "filename", false, 1024);
assertPermissions(() -> artifactManagement.create(artifactUpload), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#delete() method")
void deletePermissionCheck() {
/**
* Tests ArtifactManagement#delete() method
*/
@Test void deletePermissionCheck() {
assertPermissions(() -> {
artifactManagement.delete(1);
return null;
}, List.of(SpPermission.DELETE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#get() method")
void getPermissionCheck() {
/**
* Tests ArtifactManagement#get() method
*/
@Test void getPermissionCheck() {
assertPermissions(() -> artifactManagement.get(1L), List.of(SpPermission.READ_REPOSITORY));
assertPermissions(() -> artifactManagement.get(1L), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#getByFilenameAndSoftwareModule() method")
void getByFilenameAndSoftwareModulePermissionCheck() {
/**
* Tests ArtifactManagement#getByFilenameAndSoftwareModule() method
*/
@Test void getByFilenameAndSoftwareModulePermissionCheck() {
assertPermissions(() -> artifactManagement.getByFilenameAndSoftwareModule("filename", 1L),
List.of(SpPermission.READ_REPOSITORY), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> artifactManagement.getByFilenameAndSoftwareModule("filename", 1L),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#findFirstBySHA1() method")
void findFirstBySHA1PermissionCheck() {
/**
* Tests ArtifactManagement#findFirstBySHA1() method
*/
@Test void findFirstBySHA1PermissionCheck() {
assertPermissions(() -> artifactManagement.findFirstBySHA1("sha1"), List.of(SpPermission.READ_REPOSITORY));
assertPermissions(() -> artifactManagement.findFirstBySHA1("sha1"), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#getByFilename() method")
void getByFilenamePermissionCheck() {
/**
* Tests ArtifactManagement#getByFilename() method
*/
@Test void getByFilenamePermissionCheck() {
assertPermissions(() -> artifactManagement.getByFilename("filename"), List.of(SpPermission.READ_REPOSITORY));
assertPermissions(() -> artifactManagement.getByFilename("filename"), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#findBySoftwareModule() method")
void findBySoftwareModulePermissionCheck() {
/**
* Tests ArtifactManagement#findBySoftwareModule() method
*/
@Test void findBySoftwareModulePermissionCheck() {
assertPermissions(() -> artifactManagement.findBySoftwareModule(1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#countBySoftwareModule() method")
void countBySoftwareModulePermissionCheck() {
/**
* Tests ArtifactManagement#countBySoftwareModule() method
*/
@Test void countBySoftwareModulePermissionCheck() {
assertPermissions(() -> artifactManagement.countBySoftwareModule(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ArtifactManagement#loadArtifactBinary() method")
void loadArtifactBinaryPermissionCheck() {
/**
* Tests ArtifactManagement#loadArtifactBinary() method
*/
@Test void loadArtifactBinaryPermissionCheck() {
assertPermissions(() -> artifactManagement.loadArtifactBinary("sha1", 1L, false), List.of(SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> artifactManagement.loadArtifactBinary("sha1", 1L, false), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}

View File

@@ -26,9 +26,6 @@ import java.util.concurrent.Callable;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.apache.commons.io.IOUtils;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
@@ -57,14 +54,16 @@ import org.junit.jupiter.api.Test;
/**
* Test class for {@link ArtifactManagement}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Artifact Management
*/
@Feature("Component Tests - Repository")
@Story("Artifact Management")
class ArtifactManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access react as specfied on calls for non existing entities by means of Optional not present.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
/**
* Verifies that management get access react as specfied on calls for non existing entities by means of Optional not present.
*/
@Test @ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
void nonExistingEntityAccessReturnsNotPresent() {
final SoftwareModule module = testdataFactory.createSoftwareModuleOs();
@@ -75,9 +74,11 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactManagement.loadArtifactBinary(NOT_EXIST_ID, module.getId(), module.isEncrypted())).isEmpty();
}
/**
* Verifies that management queries react as specfied on calls for non existing entities by means of
* throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities by means of " +
"throwing EntityNotFoundException.")
@ExpectEvents()
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final String artifactData = "test";
@@ -100,9 +101,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> artifactManagement.getByFilenameAndSoftwareModule("xxx", NOT_EXIST_IDL), "SoftwareModule");
}
@Test
@Description("Test if a local artifact can be created by API including metadata.")
void createArtifact() throws IOException {
/**
* Test if a local artifact can be created by API including metadata.
*/
@Test void createArtifact() throws IOException {
// check baseline
assertThat(softwareModuleRepository.findAll()).isEmpty();
assertThat(artifactRepository.findAll()).isEmpty();
@@ -143,9 +145,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verifies that artifact management does not create artifacts with illegal filename.")
void entityQueryWithIllegalFilenameThrowsException() {
/**
* Verifies that artifact management does not create artifacts with illegal filename.
*/
@Test void entityQueryWithIllegalFilenameThrowsException() {
final String illegalFilename = "<img src=ernw onerror=alert(1)>.xml";
final String artifactData = "test";
final int artifactSize = artifactData.length();
@@ -157,9 +160,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleManagement.get(smID).get().getArtifacts()).isEmpty();
}
@Test
@Description("Verifies that the quota specifying the maximum number of artifacts per software module is enforced.")
void createArtifactsUntilQuotaIsExceeded() throws IOException {
/**
* Verifies that the quota specifying the maximum number of artifacts per software module is enforced.
*/
@Test void createArtifactsUntilQuotaIsExceeded() throws IOException {
// create a software module
final long smId = softwareModuleRepository.save(new JpaSoftwareModule(osType, "sm1", "1.0")).getId();
@@ -186,9 +190,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactManagement.findBySoftwareModule(smId, PAGE).getTotalElements()).isEqualTo(maxArtifacts);
}
@Test
@Description("Verifies that the quota specifying the maximum artifact storage is enforced (across software modules).")
void createArtifactsUntilStorageQuotaIsExceeded() throws IOException {
/**
* Verifies that the quota specifying the maximum artifact storage is enforced (across software modules).
*/
@Test void createArtifactsUntilStorageQuotaIsExceeded() throws IOException {
// create as many small artifacts as possible w/o violating the storage quota
final long maxBytes = quotaManagement.getMaxArtifactStorage();
final List<Long> artifactIds = new ArrayList<>();
@@ -213,9 +218,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
createArtifactForSoftwareModule("fileXYZ", smId, artifactSize);
}
@Test
@Description("Verifies that you cannot create artifacts which exceed the configured maximum size.")
void createArtifactFailsIfTooLarge() {
/**
* Verifies that you cannot create artifacts which exceed the configured maximum size.
*/
@Test void createArtifactFailsIfTooLarge() {
// create a software module
final long smId = softwareModuleRepository.save(new JpaSoftwareModule(osType, "sm1", "1.0")).getId();
@@ -225,9 +231,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> createArtifactForSoftwareModule("file", smId, artifactSize));
}
@Test
@Description("Tests hard delete directly on repository.")
void hardDeleteSoftwareModule() throws IOException {
/**
* Tests hard delete directly on repository.
*/
@Test void hardDeleteSoftwareModule() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
createArtifactForSoftwareModule("file1", sm.getId(), 5 * 1024);
@@ -240,9 +247,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
/**
* Test method for {@link org.eclipse.hawkbit.repository.ArtifactManagement#delete(long)}.
*/
@Test
@Description("Tests the deletion of a local artifact including metadata.")
void deleteArtifact() throws IOException {
/**
* Tests the deletion of a local artifact including metadata.
*/
@Test void deleteArtifact() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
@@ -277,9 +285,11 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Test the deletion of an artifact metadata where the binary is still linked to another metadata element.
* The expected result is that the metadata is deleted but the binary kept.
*/
@Test
@Description("Test the deletion of an artifact metadata where the binary is still linked to another metadata element. " +
"The expected result is that the metadata is deleted but the binary kept.")
void deleteDuplicateArtifacts() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
@@ -309,9 +319,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verifies that you cannot delete an artifact which exists with the same hash, in the same tenant and the SoftwareModule is not deleted .")
void deleteArtifactWithSameHashAndSoftwareModuleIsNotDeletedInSameTenants() throws IOException {
/**
* Verifies that you cannot delete an artifact which exists with the same hash, in the same tenant and the SoftwareModule is not deleted .
*/
@Test void deleteArtifactWithSameHashAndSoftwareModuleIsNotDeletedInSameTenants() throws IOException {
final JpaSoftwareModule sm = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 1", "version 1"));
final JpaSoftwareModule sm2 = softwareModuleRepository.save(new JpaSoftwareModule(osType, "name 2", "version 2"));
@@ -346,9 +357,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verifies that you can not delete artifacts from another tenant which exists in another tenant with the same hash and the SoftwareModule is not deleted")
void deleteArtifactWithSameHashAndSoftwareModuleIsNotDeletedInDifferentTenants() throws Exception {
/**
* Verifies that you can not delete artifacts from another tenant which exists in another tenant with the same hash and the SoftwareModule is not deleted
*/
@Test void deleteArtifactWithSameHashAndSoftwareModuleIsNotDeletedInDifferentTenants() throws Exception {
final String tenant1 = "mytenant";
final String tenant2 = "tenant2";
@@ -373,9 +385,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
verifyTenantArtifactCountIs(tenant2, 1);
}
@Test
@Description("Loads an local artifact based on given ID.")
void findArtifact() throws IOException {
/**
* Loads an local artifact based on given ID.
*/
@Test void findArtifact() throws IOException {
final int artifactSize = 5 * 1024;
try (final InputStream inputStream = new RandomGeneratedInputStream(artifactSize)) {
final Artifact artifact = createArtifactForSoftwareModule(
@@ -384,9 +397,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Loads an artifact binary based on given ID.")
void loadStreamOfArtifact() throws IOException {
/**
* Loads an artifact binary based on given ID.
*/
@Test void loadStreamOfArtifact() throws IOException {
final int artifactSize = 5 * 1024;
final byte[] randomBytes = randomBytes(artifactSize);
try (final InputStream input = new ByteArrayInputStream(randomBytes)) {
@@ -397,18 +411,21 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Trys and fails to load an artifact without required permission. Checks if expected InsufficientPermissionException is thrown.
*/
@Test
@WithUser(allSpPermissions = true, removeFromAllPermission = { SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT })
@Description("Trys and fails to load an artifact without required permission. Checks if expected InsufficientPermissionException is thrown.")
void loadArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() {
assertThatExceptionOfType(InsufficientPermissionException.class)
.as("Should not have worked with missing permission.")
.isThrownBy(() -> artifactManagement.loadArtifactBinary("123", 1, false));
}
@Test
@Description("Searches an artifact through the relations of a software module.")
void findArtifactBySoftwareModule() throws IOException {
/**
* Searches an artifact through the relations of a software module.
*/
@Test void findArtifactBySoftwareModule() throws IOException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
assertThat(artifactManagement.findBySoftwareModule(sm.getId(), PAGE)).isEmpty();
@@ -419,9 +436,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Searches an artifact through the relations of a software module and the filename.")
void findByFilenameAndSoftwareModule() throws IOException {
/**
* Searches an artifact through the relations of a software module and the filename.
*/
@Test void findByFilenameAndSoftwareModule() throws IOException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
assertThat(artifactManagement.getByFilenameAndSoftwareModule("file1", sm.getId())).isNotPresent();
@@ -435,9 +453,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verifies that creation of an artifact with none matching hashes fails.")
void createArtifactWithNoneMatchingHashes() throws IOException, NoSuchAlgorithmException {
/**
* Verifies that creation of an artifact with none matching hashes fails.
*/
@Test void createArtifactWithNoneMatchingHashes() throws IOException, NoSuchAlgorithmException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = randomBytes(100);
@@ -468,9 +487,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verifies that creation of an artifact with matching hashes works.")
void createArtifactWithMatchingHashes() throws IOException, NoSuchAlgorithmException {
/**
* Verifies that creation of an artifact with matching hashes works.
*/
@Test void createArtifactWithMatchingHashes() throws IOException, NoSuchAlgorithmException {
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
final byte[] testData = randomBytes(100);
@@ -490,9 +510,10 @@ class ArtifactManagementTest extends AbstractJpaIntegrationTest {
assertThat(dbArtifact).isPresent();
}
@Test
@Description("Verifies that creation of an existing artifact returns a full hash list.")
void createExistingArtifactReturnsFullHashList() throws IOException, NoSuchAlgorithmException {
/**
* Verifies that creation of an existing artifact returns a full hash list.
*/
@Test void createExistingArtifactReturnsFullHashList() throws IOException, NoSuchAlgorithmException {
final SoftwareModule smOs = testdataFactory.createSoftwareModuleOs();
final SoftwareModule smApp = testdataFactory.createSoftwareModuleApp();

View File

@@ -11,55 +11,60 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - ConfirmationManagement")
@Story("SecurityTests ConfirmationManagement")
/**
* Feature: SecurityTests - ConfirmationManagement<br/>
* Story: SecurityTests ConfirmationManagement
*/
class ConfirmationManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ConfirmationManagement#findActiveActionsWaitingConfirmation() method")
void findActiveActionsWaitingConfirmationPermissionsCheck() {
/**
* Tests ConfirmationManagement#findActiveActionsWaitingConfirmation() method
*/
@Test void findActiveActionsWaitingConfirmationPermissionsCheck() {
assertPermissions(() -> confirmationManagement.findActiveActionsWaitingConfirmation("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ConfirmationManagement#activateAutoConfirmation() method")
void activateAutoConfirmationPermissionsCheck() {
/**
* Tests ConfirmationManagement#activateAutoConfirmation() method
*/
@Test void activateAutoConfirmationPermissionsCheck() {
assertPermissions(() -> confirmationManagement.activateAutoConfirmation("controllerId", "initiator", "remark"),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ConfirmationManagement#getStatus() method")
void getStatusPermissionsCheck() {
/**
* Tests ConfirmationManagement#getStatus() method
*/
@Test void getStatusPermissionsCheck() {
assertPermissions(() -> confirmationManagement.getStatus("controllerId"), List.of(SpPermission.READ_TARGET),
List.of(SpPermission.CREATE_TARGET));
assertPermissions(() -> confirmationManagement.getStatus("controllerId"), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ConfirmationManagement#confirmAction() method")
void confirmActionPermissionsCheck() {
/**
* Tests ConfirmationManagement#confirmAction() method
*/
@Test void confirmActionPermissionsCheck() {
assertPermissions(() -> confirmationManagement.confirmAction(1L, null, null),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ConfirmationManagement#denyAction() method")
void denyActionPermissionsCheck() {
/**
* Tests ConfirmationManagement#denyAction() method
*/
@Test void denyActionPermissionsCheck() {
assertPermissions(() -> confirmationManagement.denyAction(1L, null, null),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ConfirmationManagement#deactivateAutoConfirmation() method")
void deactivateAutoConfirmationPermissionsCheck() {
/**
* Tests ConfirmationManagement#deactivateAutoConfirmation() method
*/
@Test void deactivateAutoConfirmationPermissionsCheck() {
assertPermissions(() -> {
confirmationManagement.deactivateAutoConfirmation("controllerId");
return null;

View File

@@ -18,9 +18,6 @@ import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.AutoConfirmationAlreadyActiveException;
import org.eclipse.hawkbit.repository.exception.InvalidConfirmationFeedbackException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -38,14 +35,16 @@ import org.junit.jupiter.params.provider.MethodSource;
/**
* Test class testing the functionality of triggering a deployment of
* {@link DistributionSet}s to {@link Target}s with AutoConfirmation active.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Confirmation Management
*/
@Feature("Component Tests - Repository")
@Story("Confirmation Management")
class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verify 'findActiveActionsWaitingConfirmation' method is filtering like expected")
void retrieveActionsWithConfirmationState() {
/**
* Verify 'findActiveActionsWaitingConfirmation' method is filtering like expected
*/
@Test void retrieveActionsWithConfirmationState() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -65,9 +64,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getStatus() == Status.WAIT_FOR_CONFIRMATION);
}
@Test
@Description("Verify 'findActiveActionsWaitingConfirmation' method is filtering like expected with multi assignment active")
void retrieveActionsWithConfirmationStateInMultiAssignment() {
/**
* Verify 'findActiveActionsWaitingConfirmation' method is filtering like expected with multi assignment active
*/
@Test void retrieveActionsWithConfirmationStateInMultiAssignment() {
enableMultiAssignments();
enableConfirmationFlow();
@@ -94,9 +94,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify confirming an action will put it to the running state")
void confirmedActionWillSwitchToRunningState() {
/**
* Verify confirming an action will put it to the running state
*/
@Test void confirmedActionWillSwitchToRunningState() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -122,9 +123,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.anyMatch(status -> status.getStatus() == Status.RUNNING);
}
@Test
@Description("Verify confirming an confirmed action will lead to a specific failure")
void confirmedActionCannotBeConfirmedAgain() {
/**
* Verify confirming an confirmed action will lead to a specific failure
*/
@Test void confirmedActionCannotBeConfirmedAgain() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -143,9 +145,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.getReason() == InvalidConfirmationFeedbackException.Reason.NOT_AWAITING_CONFIRMATION);
}
@Test
@Description("Verify confirming a closed action will lead to a specific failure")
void confirmedActionCannotBeGivenOnFinishedAction() {
/**
* Verify confirming a closed action will lead to a specific failure
*/
@Test void confirmedActionCannotBeGivenOnFinishedAction() {
enableConfirmationFlow();
final Long actionId = prepareFinishedUpdate().getId();
assertThatThrownBy(() -> confirmationManagement.confirmAction(actionId, null, null))
@@ -154,9 +157,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.getReason() == InvalidConfirmationFeedbackException.Reason.ACTION_CLOSED);
}
@Test
@Description("Verify denying an action will leave it in WFC state")
void deniedActionWillStayInWfcState() {
/**
* Verify denying an action will leave it in WFC state
*/
@Test void deniedActionWillStayInWfcState() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -182,9 +186,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.noneMatch(status -> status.getStatus() == Status.RUNNING);
}
@Test
@Description("Verify multiple actions in WFC state will be transferred in RUNNING state in case auto-confirmation is activated.")
void activateAutoConfirmationInMultiAssignment() {
/**
* Verify multiple actions in WFC state will be transferred in RUNNING state in case auto-confirmation is activated.
*/
@Test void activateAutoConfirmationInMultiAssignment() {
enableMultiAssignments();
enableConfirmationFlow();
@@ -208,9 +213,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getStatus() == Status.RUNNING);
}
@Test
@Description("Verify action in WFC state will be transferred in RUNNING state in case auto-confirmation is activated.")
void activateAutoConfirmationOnActiveAction() {
/**
* Verify action in WFC state will be transferred in RUNNING state in case auto-confirmation is activated.
*/
@Test void activateAutoConfirmationOnActiveAction() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -230,9 +236,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getStatus() == Status.RUNNING);
}
@Test
@Description("Verify created action after activating auto confirmation is directly in running state.")
void activateAutoConfirmationAndCreateAction() {
/**
* Verify created action after activating auto confirmation is directly in running state.
*/
@Test void activateAutoConfirmationAndCreateAction() {
enableConfirmationFlow();
final String controllerId = testdataFactory.createTarget().getControllerId();
@@ -251,9 +258,11 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getStatus() == Status.RUNNING);
}
/**
* Verify activating auto confirmation with different parameters
*/
@ParameterizedTest
@MethodSource("getAutoConfirmationArguments")
@Description("Verify activating auto confirmation with different parameters")
void verifyAutoConfirmationActivationValues(final String initiator, final String remark) {
final String controllerId = testdataFactory.createTarget().getControllerId();
confirmationManagement.activateAutoConfirmation(controllerId, initiator, remark);
@@ -272,9 +281,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
verifyAutoConfirmationIsDisabled(controllerId);
}
@Test
@Description("Verify activating already active auto confirmation will throw exception.")
void verifyActivateAlreadyActiveAutoConfirmationThrowException() {
/**
* Verify activating already active auto confirmation will throw exception.
*/
@Test void verifyActivateAlreadyActiveAutoConfirmationThrowException() {
final String controllerId = testdataFactory.createTarget().getControllerId();
confirmationManagement.activateAutoConfirmation(controllerId, "any", "any");
@@ -285,9 +295,10 @@ class ConfirmationManagementTest extends AbstractJpaIntegrationTest {
.hasMessage("Auto confirmation is already active for device " + controllerId);
}
@Test
@Description("Verify disabling already disabled auto confirmation will not have any affect.")
void disableAlreadyDisabledAutoConfirmationHaveNoAffect() {
/**
* Verify disabling already disabled auto confirmation will not have any affect.
*/
@Test void disableAlreadyDisabledAutoConfirmationHaveNoAffect() {
final String controllerId = testdataFactory.createTarget().getControllerId();
verifyAutoConfirmationIsDisabled(controllerId);

View File

@@ -13,9 +13,6 @@ import java.net.URI;
import java.util.List;
import java.util.Map;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.exception.CancelActionNotAllowedException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -24,115 +21,133 @@ import org.eclipse.hawkbit.repository.model.Target;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
@Feature("SecurityTests - ControllerManagement")
@Story("SecurityTests ControllerManagement")
/**
* Feature: SecurityTests - ControllerManagement<br/>
* Story: SecurityTests ControllerManagement
*/
class ControllerManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ControllerManagement#cancelActionStatus() method")
void addCancelActionStatusPermissionsCheck() {
/**
* Tests ControllerManagement#cancelActionStatus() method
*/
@Test void addCancelActionStatusPermissionsCheck() {
assertPermissions(() -> controllerManagement.addCancelActionStatus(entityFactory.actionStatus().create(0L)),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getSoftwareModule() method")
void getSoftwareModulePermissionsCheck() {
/**
* Tests ControllerManagement#getSoftwareModule() method
*/
@Test void getSoftwareModulePermissionsCheck() {
assertPermissions(() -> controllerManagement.getSoftwareModule(1L), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findTargetVisibleMetaDataBySoftwareModuleId() method")
void findTargetVisibleMetaDataBySoftwareModuleIdPermissionsCheck() {
/**
* Tests ControllerManagement#findTargetVisibleMetaDataBySoftwareModuleId() method
*/
@Test void findTargetVisibleMetaDataBySoftwareModuleIdPermissionsCheck() {
assertPermissions(() -> controllerManagement.findTargetVisibleMetaDataBySoftwareModuleId(List.of(1L)),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#addInformationalActionStatus() method")
void addInformationalActionStatusPermissionsCheck() {
/**
* Tests ControllerManagement#addInformationalActionStatus() method
*/
@Test void addInformationalActionStatusPermissionsCheck() {
assertPermissions(() -> controllerManagement.addInformationalActionStatus(entityFactory.actionStatus().create(0L)),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#addUpdateActionStatus() method")
void addUpdateActionStatusPermissionsCheck() {
/**
* Tests ControllerManagement#addUpdateActionStatus() method
*/
@Test void addUpdateActionStatusPermissionsCheck() {
assertPermissions(() -> controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(0L)),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findActiveActionWithHighestWeight() method")
void findActiveActionWithHighestWeightPermissionsCheck() {
/**
* Tests ControllerManagement#findActiveActionWithHighestWeight() method
*/
@Test void findActiveActionWithHighestWeightPermissionsCheck() {
assertPermissions(() -> controllerManagement.findActiveActionWithHighestWeight("controllerId"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findActiveActionsWithHighestWeight() method")
void findActiveActionsWithHighestWeightPermissionsCheck() {
/**
* Tests ControllerManagement#findActiveActionsWithHighestWeight() method
*/
@Test void findActiveActionsWithHighestWeightPermissionsCheck() {
assertPermissions(() -> controllerManagement.findActiveActionsWithHighestWeight("controllerId", 1),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findActionWithDetails() method")
void findActionWithDetailsPermissionsCheck() {
/**
* Tests ControllerManagement#findActionWithDetails() method
*/
@Test void findActionWithDetailsPermissionsCheck() {
assertPermissions(() -> controllerManagement.findActionWithDetails(1L), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findActionStatusByAction() method")
void findActionStatusByActionPermissionsCheck() {
/**
* Tests ControllerManagement#findActionStatusByAction() method
*/
@Test void findActionStatusByActionPermissionsCheck() {
assertPermissions(() -> controllerManagement.findActionStatusByAction(1L, Pageable.unpaged()),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findOrRegisterTargetIfItDoesNotExist() method")
void findOrRegisterTargetIfItDoesNotExistPermissionsCheck() {
/**
* Tests ControllerManagement#findOrRegisterTargetIfItDoesNotExist() method
*/
@Test void findOrRegisterTargetIfItDoesNotExistPermissionsCheck() {
assertPermissions(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist("controllerId", URI.create("someaddress")),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#findOrRegisterTargetIfItDoesNotExist() method")
void findOrRegisterTargetIfItDoesNotExistWithDetailsPermissionsCheck() {
/**
* Tests ControllerManagement#findOrRegisterTargetIfItDoesNotExist() method
*/
@Test void findOrRegisterTargetIfItDoesNotExistWithDetailsPermissionsCheck() {
assertPermissions(
() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist("controllerId", URI.create("someaddress"), "name", "type"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getActionForDownloadByTargetAndSoftwareModule() method")
void getActionForDownloadByTargetAndSoftwareModulePermissionsCheck() {
/**
* Tests ControllerManagement#getActionForDownloadByTargetAndSoftwareModule() method
*/
@Test void getActionForDownloadByTargetAndSoftwareModulePermissionsCheck() {
assertPermissions(() -> controllerManagement.getActionForDownloadByTargetAndSoftwareModule("controllerId", 1L),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getPollingTime() method")
void getPollingTimePermissionsCheck() {
/**
* Tests ControllerManagement#getPollingTime() method
*/
@Test void getPollingTimePermissionsCheck() {
assertPermissions(() -> controllerManagement.getPollingTime(), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getMinPollingTime() method")
void getMinPollingTimePermissionsCheck() {
/**
* Tests ControllerManagement#getMinPollingTime() method
*/
@Test void getMinPollingTimePermissionsCheck() {
assertPermissions(() -> controllerManagement.getMinPollingTime(), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getMaxPollingTime() method")
void getMaintenanceWindowPollCountPermissionsCheck() {
/**
* Tests ControllerManagement#getMaxPollingTime() method
*/
@Test void getMaintenanceWindowPollCountPermissionsCheck() {
assertPermissions(() -> controllerManagement.getMaintenanceWindowPollCount(),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getPollingTimeForAction() method")
void getPollingTimeForActionPermissionsCheck() {
/**
* Tests ControllerManagement#getPollingTimeForAction() method
*/
@Test void getPollingTimeForActionPermissionsCheck() {
final JpaAction action = new JpaAction();
action.setId(1L);
assertPermissions(() -> {
@@ -145,53 +160,60 @@ class ControllerManagementSecurityTest extends AbstractJpaIntegrationTest {
}, List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#hasTargetArtifactAssigned() method")
void hasTargetArtifactAssignedPermissionsCheck() {
/**
* Tests ControllerManagement#hasTargetArtifactAssigned() method
*/
@Test void hasTargetArtifactAssignedPermissionsCheck() {
assertPermissions(() -> controllerManagement.hasTargetArtifactAssigned("controllerId", "sha1Hash"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#hasTargetArtifactAssigned() method")
void hasTargetArtifactAssignedByIdPermissionsCheck() {
/**
* Tests ControllerManagement#hasTargetArtifactAssigned() method
*/
@Test void hasTargetArtifactAssignedByIdPermissionsCheck() {
assertPermissions(() -> controllerManagement.hasTargetArtifactAssigned(1L, "sha1Hash"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#updateControllerAttributes() method")
void updateControllerAttributesPermissionsCheck() {
/**
* Tests ControllerManagement#updateControllerAttributes() method
*/
@Test void updateControllerAttributesPermissionsCheck() {
assertPermissions(() -> controllerManagement.updateControllerAttributes("controllerId", Map.of(), null),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getByControllerId() method")
void getByControllerIdPermissionsCheck() {
/**
* Tests ControllerManagement#getByControllerId() method
*/
@Test void getByControllerIdPermissionsCheck() {
assertPermissions(() -> controllerManagement.getByControllerId("controllerId"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
assertPermissions(() -> controllerManagement.getByControllerId("controllerId"),
List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ControllerManagement#get() method")
void getPermissionsCheck() {
/**
* Tests ControllerManagement#get() method
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> controllerManagement.get(1L), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
assertPermissions(() -> controllerManagement.get(1L), List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ControllerManagement#getActionHistoryMessages() method")
void getActionHistoryMessagesPermissionsCheck() {
/**
* Tests ControllerManagement#getActionHistoryMessages() method
*/
@Test void getActionHistoryMessagesPermissionsCheck() {
assertPermissions(() -> controllerManagement.getActionHistoryMessages(1L, 1),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#cancelAction() method")
void cancelActionPermissionsCheck() {
/**
* Tests ControllerManagement#cancelAction() method
*/
@Test void cancelActionPermissionsCheck() {
final JpaAction action = new JpaAction();
action.setId(1L);
assertPermissions(() -> {
@@ -204,60 +226,67 @@ class ControllerManagementSecurityTest extends AbstractJpaIntegrationTest {
}, List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#updateActionExternalRef() method")
void updateActionExternalRefPermissionsCheck() {
/**
* Tests ControllerManagement#updateActionExternalRef() method
*/
@Test void updateActionExternalRefPermissionsCheck() {
assertPermissions(() -> {
controllerManagement.updateActionExternalRef(1L, "externalRef");
return null;
}, List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getActionByExternalRef() method")
void getActionByExternalRefPermissionsCheck() {
/**
* Tests ControllerManagement#getActionByExternalRef() method
*/
@Test void getActionByExternalRefPermissionsCheck() {
assertPermissions(() -> controllerManagement.getActionByExternalRef("externalRef"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#deleteExistingTarget() method")
void deleteExistingTargetPermissionsCheck() {
/**
* Tests ControllerManagement#deleteExistingTarget() method
*/
@Test void deleteExistingTargetPermissionsCheck() {
assertPermissions(() -> {
controllerManagement.deleteExistingTarget("controllerId");
return null;
}, List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#getInstalledActionByTarget() method")
void getInstalledActionByTargetPermissionsCheck() {
/**
* Tests ControllerManagement#getInstalledActionByTarget() method
*/
@Test void getInstalledActionByTargetPermissionsCheck() {
final Target target = testdataFactory.createTarget();
assertPermissions(
() -> controllerManagement.getInstalledActionByTarget(target),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#activateAutoConfirmation() method")
void activateAutoConfirmationPermissionsCheck() {
/**
* Tests ControllerManagement#activateAutoConfirmation() method
*/
@Test void activateAutoConfirmationPermissionsCheck() {
assertPermissions(
() -> controllerManagement.activateAutoConfirmation("controllerId", "initiator", "remark"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#deactivateAutoConfirmation() method")
void deactivateAutoConfirmationPermissionsCheck() {
/**
* Tests ControllerManagement#deactivateAutoConfirmation() method
*/
@Test void deactivateAutoConfirmationPermissionsCheck() {
assertPermissions(() -> {
controllerManagement.deactivateAutoConfirmation("controllerId");
return null;
}, List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}
@Test
@Description("Tests ControllerManagement#updateOfflineAssignedVersion() method")
void updateOfflineAssignedVersionPermissionsCheck() {
/**
* Tests ControllerManagement#updateOfflineAssignedVersion() method
*/
@Test void updateOfflineAssignedVersionPermissionsCheck() {
assertPermissions(() -> controllerManagement.updateOfflineAssignedVersion("controllerId", "distributionName", "version"),
List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE));
}

View File

@@ -35,10 +35,6 @@ import java.util.stream.IntStream;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryProperties;
@@ -89,16 +85,19 @@ import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.ConcurrencyFailureException;
@Feature("Component Tests - Repository")
@Story("Controller Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Controller Management
*/
class ControllerManagementTest extends AbstractJpaIntegrationTest {
@Autowired
private RepositoryProperties repositoryProperties;
@Test
@Description("Ensures that target attribute update fails if quota hits.")
@ExpectEvents({
/**
* Ensures that target attribute update fails if quota hits.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 2) })
void updateTargetAttributesFailsIfTooManyEntries() throws Exception {
@@ -135,9 +134,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Checks if invalid values of attribute-key and attribute-value are handled correctly")
void updateTargetAttributesFailsForInvalidAttributes() {
/**
* Checks if invalid values of attribute-key and attribute-value are handled correctly
*/
@Test void updateTargetAttributesFailsForInvalidAttributes() {
final String controllerId = "targetId123";
testdataFactory.createTarget(controllerId);
@@ -165,9 +165,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> controllerManagement.updateControllerAttributes(controllerId, attributesNV, null));
}
@Test
@Description("Controller providing status entries fails if providing more than permitted by quota.")
@ExpectEvents({
/**
* Controller providing status entries fails if providing more than permitted by quota.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -190,9 +191,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Test to verify the storage and retrieval of action history.")
void findMessagesByActionStatusId() {
/**
* Test to verify the storage and retrieval of action history.
*/
@Test void findMessagesByActionStatusId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("1");
final List<Target> testTarget = testdataFactory.createTargets(1);
@@ -215,9 +217,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(messages.get(1)).as("Message of action-status").isEqualTo("proceeding message 1");
}
@Test
@Description("Verifies that the quota specifying the maximum number of status entries per action is enforced.")
@ExpectEvents({
/**
* Verifies that the quota specifying the maximum number of status entries per action is enforced.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 2),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6),
@@ -253,9 +256,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> controllerManagement.addInformationalActionStatus(statusWarning));
}
@Test
@Description("Verifies that the quota specifying the maximum number of messages per action status is enforced.")
@ExpectEvents({
/**
* Verifies that the quota specifying the maximum number of messages per action status is enforced.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -283,9 +287,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> controllerManagement.addInformationalActionStatus(statusToManyMessages));
}
@Test
@Description("Verifies that a DOWNLOAD_ONLY action is not marked complete when the controller reports DOWNLOAD")
@ExpectEvents({
/**
* Verifies that a DOWNLOAD_ONLY action is not marked complete when the controller reports DOWNLOAD
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -308,9 +313,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(activeActionExistsForControllerId(DEFAULT_CONTROLLER_ID)).isTrue();
}
/**
* Verifies that management get access react as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
@@ -330,9 +337,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.hasTargetArtifactAssigned(target.getId(), "XXX")).isFalse();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
@@ -368,9 +377,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
() -> controllerManagement.updateControllerAttributes(NOT_EXIST_ID, new HashMap<>(), null), "Target");
}
@Test
@Description("Controller confirms successful update with FINISHED status.")
@ExpectEvents({
/**
* Controller confirms successful update with FINISHED status.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -395,9 +405,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(7);
}
@Test
@Description("Controller confirmation fails with invalid messages.")
@ExpectEvents({
/**
* Controller confirmation fails with invalid messages.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -427,9 +438,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(6);
}
/**
* Controller confirms successful update with FINISHED status on a action that is on canceling.
* Reason: The decision to ignore the cancellation is in fact up to the controller.
*/
@Test
@Description("Controller confirms successful update with FINISHED status on a action that is on canceling. "
+ "Reason: The decision to ignore the cancellation is in fact up to the controller.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -455,9 +468,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(3);
}
@Test
@Description("Update server rejects cancellation feedback if action is not in CANCELING state.")
@ExpectEvents({
/**
* Update server rejects cancellation feedback if action is not in CANCELING state.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -480,9 +494,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(1);
}
@Test
@Description("Controller confirms action cancellation with FINISHED status.")
@ExpectEvents({
/**
* Controller confirms action cancellation with FINISHED status.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -511,9 +526,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(8);
}
@Test
@Description("Controller confirms action cancellation with FINISHED status.")
@ExpectEvents({
/**
* Controller confirms action cancellation with FINISHED status.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -542,9 +558,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(8);
}
/**
* Controller rejects action cancellation with CANCEL_REJECTED status. Action goes back to RUNNING status as it expects
* that the controller will continue the original update.
*/
@Test
@Description("Controller rejects action cancellation with CANCEL_REJECTED status. Action goes back to RUNNING status as it expects "
+ "that the controller will continue the original update.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -574,9 +592,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(8);
}
/**
* Controller rejects action cancellation with ERROR status. Action goes back to RUNNING status as it expects
* that the controller will continue the original update.
*/
@Test
@Description("Controller rejects action cancellation with ERROR status. Action goes back to RUNNING status as it expects "
+ "that the controller will continue the original update.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -606,9 +626,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(8);
}
/**
* Verifies that assignment verification works based on SHA1 hash. By design it is not important which artifact
* is actually used for the check as long as they have an identical binary, i.e. same SHA1 hash.
*/
@Test
@Description("Verifies that assignment verification works based on SHA1 hash. By design it is not important which artifact "
+ "is actually used for the check as long as they have an identical binary, i.e. same SHA1 hash. ")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@@ -645,9 +667,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isTrue();
}
@Test
@Description("Register a controller which does not exist")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 2) })
@@ -660,9 +683,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registered").isEqualTo(1L);
}
@Test
@Description("Register a controller with name which does not exist and update its name")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller with name which does not exist and update its name
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 2),
@@ -677,9 +701,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Register a controller which does not exist with existing target type and update its target type to another existing one")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist with existing target type and update its target type to another existing one
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetTypeCreatedEvent.class, count = 2),
@Expect(type = TargetCreatedEvent.class, count = 1),
@@ -700,9 +725,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Register a controller which does not exist with existing target type and update its target type to non existing one")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist with existing target type and update its target type to non existing one
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetTypeCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 1),
@@ -719,9 +745,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Register a controller which does not exist with existing target type and unassign its target type")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist with existing target type and unassign its target type
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetTypeCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 1),
@@ -739,9 +766,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Register a controller which does not exist without target type and update its target type to existing one")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist without target type and update its target type to existing one
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetTypeCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 1),
@@ -761,9 +789,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Register a controller which does not exist with non existing target type and update its target type to existing one")
@WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
/**
* Register a controller which does not exist with non existing target type and update its target type to existing one
*/
@Test @WithUser(principal = "controller", authorities = { CONTROLLER_ROLE })
@ExpectEvents({
@Expect(type = TargetTypeCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 1),
@@ -783,9 +812,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L);
}
@Test
@Description("Tries to register a target with an invalid controller id")
void findOrRegisterTargetIfItDoesNotExistThrowsExceptionForInvalidControllerIdParam() {
/**
* Tries to register a target with an invalid controller id
*/
@Test void findOrRegisterTargetIfItDoesNotExistThrowsExceptionForInvalidControllerIdParam() {
assertThatExceptionOfType(ConstraintViolationException.class)
.as("register target with null as controllerId should fail")
.isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(null, LOCALHOST));
@@ -805,9 +835,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
controllerId, LOCALHOST));
}
/**
* Register a controller which does not exist, when a ConcurrencyFailureException is raised, the
* exception is rethrown after max retries
*/
@Test
@Description("Register a controller which does not exist, when a ConcurrencyFailureException is raised, the "
+ "exception is rethrown after max retries")
void findOrRegisterTargetIfItDoesNotExistThrowsExceptionAfterMaxRetries() {
final TargetRepository mockTargetRepository = Mockito.mock(TargetRepository.class);
when(mockTargetRepository.findOne(any())).thenThrow(ConcurrencyFailureException.class);
@@ -825,9 +857,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Register a controller which does not exist, when a ConcurrencyFailureException is raised, the
* exception is not rethrown when the max retries are not yet reached
*/
@Test
@Description("Register a controller which does not exist, when a ConcurrencyFailureException is raised, the "
+ "exception is not rethrown when the max retries are not yet reached")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 1) })
@@ -853,9 +887,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Register a controller which does not exist, then update the controller twice, first time by providing a name property and second time without a new name")
@ExpectEvents({
/**
* Register a controller which does not exist, then update the controller twice, first time by providing a name property and second time without a new name
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 3),
@Expect(type = TargetUpdatedEvent.class, count = 1) })
@@ -875,9 +910,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(secondTimeUpdatedTarget.getName()).isEqualTo(targetName);
}
/**
* Register a controller which does not exist, if a EntityAlreadyExistsException is raised, the
* exception is rethrown and no further retries will be attempted
*/
@Test
@Description("Register a controller which does not exist, if a EntityAlreadyExistsException is raised, the "
+ "exception is rethrown and no further retries will be attempted")
void findOrRegisterTargetIfItDoesNotExistDoesntRetryWhenEntityAlreadyExistsException() {
final TargetRepository mockTargetRepository = Mockito.mock(TargetRepository.class);
@@ -898,9 +935,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Retry is aborted when an unchecked exception is thrown and the exception should also be
* rethrown
*/
@Test
@Description("Retry is aborted when an unchecked exception is thrown and the exception should also be "
+ "rethrown")
void recoverFindOrRegisterTargetIfItDoesNotExistIsNotInvokedForOtherExceptions() {
final TargetRepository mockTargetRepository = Mockito.mock(TargetRepository.class);
@@ -919,9 +958,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verify that targetVisible metadata is returned from repository")
@ExpectEvents({
/**
* Verify that targetVisible metadata is returned from repository
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = SoftwareModuleUpdatedEvent.class, count = 6) })
@@ -936,9 +976,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
result.forEach((key, value) -> assertThat(value).hasSize(1));
}
@Test
@Description("Verify that controller registration does not result in a TargetPollEvent if feature is disabled")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
/**
* Verify that controller registration does not result in a TargetPollEvent if feature is disabled
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
@SuppressWarnings("java:S2699")
// java:S2699 - test tests the fired events, no need for assert
void targetPollEventNotSendIfDisabled() {
@@ -947,9 +988,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
repositoryProperties.setPublishTargetPollEvent(true);
}
@Test
@Description("Controller tries to finish an update process after it has been finished by an error action status.")
@ExpectEvents({
/**
* Controller tries to finish an update process after it has been finished by an error action status.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -988,9 +1030,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(3);
}
@Test
@Description("Controller tries to finish an update process after it has been finished by an FINISHED action status.")
@ExpectEvents({
/**
* Controller tries to finish an update process after it has been finished by an FINISHED action status.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1021,9 +1064,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(actionId, PAGE).getNumberOfElements()).isEqualTo(3);
}
/**
* Controller tries to send an update feedback after it has been finished which is reject as the repository is configured to reject that.
*/
@Test
@Description("Controller tries to send an update feedback after it has been finished which is reject as the repository is "
+ "configured to reject that.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -1051,9 +1095,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(3);
}
/**
* Controller tries to send an update feedback after it has been finished which is accepted as the repository is
* configured to accept them.
*/
@Test
@Description("Controller tries to send an update feedback after it has been finished which is accepted as the repository is "
+ "configured to accept them.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -1078,9 +1124,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActionStatusByAction(action.getId(), PAGE).getNumberOfElements()).isEqualTo(4);
}
@Test
@Description("Ensures that target attribute update is reflected by the repository.")
@ExpectEvents({
/**
* Ensures that target attribute update is reflected by the repository.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 3) })
void updateTargetAttributes() throws Exception {
@@ -1104,9 +1151,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetVerify.getLastModifiedAt()).isEqualTo(target.getLastModifiedAt());
}
@Test
@Description("Ensures that target attributes can be updated using different update modes.")
@ExpectEvents({
/**
* Ensures that target attributes can be updated using different update modes.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4) })
void updateTargetAttributesWithDifferentUpdateModes() {
@@ -1126,9 +1174,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
updateTargetAttributesWithUpdateModeRemove(controllerId);
}
@Test
@Description("Verifies that a DOWNLOAD_ONLY action is marked complete once the controller reports DOWNLOADED")
@ExpectEvents({
/**
* Verifies that a DOWNLOAD_ONLY action is marked complete once the controller reports DOWNLOADED
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1152,9 +1201,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(activeActionExistsForControllerId(DEFAULT_CONTROLLER_ID)).isFalse();
}
@Test
@Description("Verifies that a controller can report a FINISHED event for a DOWNLOAD_ONLY non-active action.")
@ExpectEvents({
/**
* Verifies that a controller can report a FINISHED event for a DOWNLOAD_ONLY non-active action.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1179,9 +1229,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(activeActionExistsForControllerId(DEFAULT_CONTROLLER_ID)).isFalse();
}
@Test
@Description("Verifies that multiple DOWNLOADED events for a DOWNLOAD_ONLY action are handled.")
@ExpectEvents({
/**
* Verifies that multiple DOWNLOADED events for a DOWNLOAD_ONLY action are handled.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1207,9 +1258,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(activeActionExistsForControllerId(DEFAULT_CONTROLLER_ID)).isFalse();
}
/**
* Verifies that quota is asserted when a controller reports too many DOWNLOADED events for a
* DOWNLOAD_ONLY action.
*/
@Test
@Description("Verifies that quota is asserted when a controller reports too many DOWNLOADED events for a "
+ "DOWNLOAD_ONLY action.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@@ -1233,9 +1286,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> forNTimes(maxMessages, op));
}
@Test
@Description("Verifies that quota is enforced for UpdateActionStatus events for DOWNLOAD_ONLY assignments.")
@ExpectEvents({
/**
* Verifies that quota is enforced for UpdateActionStatus events for DOWNLOAD_ONLY assignments.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1280,9 +1334,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Verifies that quota is enforced for UpdateActionStatus events for FORCED assignments.")
@ExpectEvents({
/**
* Verifies that quota is enforced for UpdateActionStatus events for FORCED assignments.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1326,9 +1381,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Verify that the attaching externalRef to an action is properly stored")
void updatedExternalRefOnActionIsReallyUpdated() {
/**
* Verify that the attaching externalRef to an action is properly stored
*/
@Test void updatedExternalRefOnActionIsReallyUpdated() {
final List<String> allExternalRef = new ArrayList<>();
final List<Long> allActionId = new ArrayList<>();
final int numberOfActions = 3;
@@ -1357,9 +1413,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verify that getting a single action using externalRef works")
void getActionUsingSingleExternalRef() {
/**
* Verify that getting a single action using externalRef works
*/
@Test void getActionUsingSingleExternalRef() {
final String knownControllerId = "controllerId";
final String knownExternalRef = "externalRefId";
@@ -1380,9 +1437,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(foundAction.get().getId()).isEqualTo(actionId);
}
@Test
@Description("Verify that assigning version form target works")
@ExpectEvents({
/**
* Verify that assigning version form target works
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1),
@@ -1412,17 +1470,20 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(updated2).isFalse();
}
@Test
@Description("Verify that a null externalRef cannot be assigned to an action")
void externalRefCannotBeNull() {
/**
* Verify that a null externalRef cannot be assigned to an action
*/
@Test void externalRefCannotBeNull() {
assertThatExceptionOfType(ConstraintViolationException.class)
.as("No ConstraintViolationException thrown when a null externalRef was set on an action")
.isThrownBy(() -> controllerManagement.updateActionExternalRef(1L, null));
}
/**
* Verifies that a target can report FINISHED/ERROR updates for DOWNLOAD_ONLY assignments regardless of
* repositoryProperties.rejectActionStatusForClosedAction value.
*/
@Test
@Description("Verifies that a target can report FINISHED/ERROR updates for DOWNLOAD_ONLY assignments regardless of " +
"repositoryProperties.rejectActionStatusForClosedAction value.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 4),
@@ -1466,9 +1527,11 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
});
}
/**
* Verifies that a controller can report a FINISHED event for a DOWNLOAD_ONLY action after having
* installed an intermediate update.
*/
@Test
@Description("Verifies that a controller can report a FINISHED event for a DOWNLOAD_ONLY action after having"
+ " installed an intermediate update.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@@ -1507,9 +1570,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertNoActiveActionsExistsForControllerId(DEFAULT_CONTROLLER_ID);
}
@Test
@Description("Actions are exposed according to thier weight in multi assignment mode.")
void actionsAreExposedAccordingToTheirWeight() {
/**
* Actions are exposed according to thier weight in multi assignment mode.
*/
@Test void actionsAreExposedAccordingToTheirWeight() {
final String targetId = testdataFactory.createTarget().getControllerId();
final DistributionSet ds = testdataFactory.createDistributionSet();
final Long actionWeightNull = assignDistributionSet(ds.getId(), targetId).getAssignedEntity().get(0).getId();
@@ -1540,9 +1604,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(controllerManagement.findActiveActionWithHighestWeight(targetId)).isEmpty();
}
@Test
@Description("Delete a target on requested target deletion from client side")
@ExpectEvents({
/**
* Delete a target on requested target deletion from client side
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 1),
@Expect(type = TargetDeletedEvent.class, count = 1) })
@@ -1556,9 +1621,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("target should not exist anymore").isZero();
}
@Test
@Description("Delete a target with a non existing thingId")
@ExpectEvents({ @Expect(type = TargetDeletedEvent.class, count = 0) })
/**
* Delete a target with a non existing thingId
*/
@Test @ExpectEvents({ @Expect(type = TargetDeletedEvent.class, count = 0) })
void deleteTargetWithInvalidThingId() {
assertThatExceptionOfType(EntityNotFoundException.class)
.as("No EntityNotFoundException thrown when deleting a non-existing target")
@@ -1566,9 +1632,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetRepository.count()).as("target should not exist").isZero();
}
@Test
@Description("Delete a target after it has been deleted already")
@ExpectEvents({
/**
* Delete a target after it has been deleted already
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 1),
@Expect(type = TargetDeletedEvent.class, count = 1) })
@@ -1586,9 +1653,10 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> controllerManagement.deleteExistingTarget(controllerId));
}
@Test
@Description("When action status code is provided in feedback it is also stored in the action field lastActionStatusCode")
void lastActionStatusCodeIsSet() {
/**
* When action status code is provided in feedback it is also stored in the action field lastActionStatusCode
*/
@Test void lastActionStatusCodeIsSet() {
final Long actionId = createTargetAndAssignDs();
addUpdateActionStatusAndAssert(actionId, Action.Status.RUNNING, 10);
@@ -1619,7 +1687,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
@Step
private Long createTargetAndAssignDs() {
final Long dsId = testdataFactory.createDistributionSet().getId();
testdataFactory.createTarget();
@@ -1630,7 +1697,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
return deploymentManagement.findActiveActionsByTarget(DEFAULT_CONTROLLER_ID, PAGE).getContent().get(0).getId();
}
@Step
private Long createAndAssignDsAsDownloadOnly(final String dsName, final String defaultControllerId) {
final DistributionSet ds = testdataFactory.createDistributionSet(dsName);
final Long dsId = ds.getId();
@@ -1642,7 +1708,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
return id;
}
@Step
private Long assignDs(final Long dsId, final String defaultControllerId, final Action.ActionType actionType) {
assignDistributionSet(dsId, defaultControllerId, actionType);
assertThat(targetManagement.getByControllerID(defaultControllerId).get().getUpdateStatus())
@@ -1654,7 +1719,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
return id;
}
@Step
private void simulateIntermediateStatusOnCancellation(final Long actionId) {
controllerManagement
.addCancelActionStatus(entityFactory.actionStatus().create(actionId).status(Action.Status.RUNNING));
@@ -1682,7 +1746,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
Action.Status.WARNING, true);
}
@Step
private void simulateIntermediateStatusOnUpdate(final Long actionId) {
addUpdateActionStatusAndAssert(actionId, Action.Status.RUNNING);
@@ -1731,7 +1794,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
systemSecurityContext.runAsSystem(() -> targetTypeManagement.create(entityFactory.targetType().create().name(targetTypeName)));
}
@Step
private void addAttributeAndVerify(final String controllerId) {
final Map<String, String> testData = new HashMap<>(1);
testData.put("test1", "testdata1");
@@ -1741,7 +1803,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(testData);
}
@Step
private void addSecondAttributeAndVerify(final String controllerId) {
final Map<String, String> testData = new HashMap<>(2);
testData.put("test2", "testdata20");
@@ -1752,7 +1813,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(testData);
}
@Step
private void updateAttributeAndVerify(final String controllerId) {
final Map<String, String> testData = new HashMap<>(2);
testData.put("test1", "testdata12");
@@ -1764,7 +1824,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(testData);
}
@Step
private void updateTargetAttributesWithUpdateModeRemove(final String controllerId) {
final int previousSize = targetManagement.getControllerAttributes(controllerId).size();
@@ -1780,7 +1839,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(updatedAttributes).doesNotContainKeys("k1", "k3");
}
@Step
private void updateTargetAttributesWithUpdateModeMerge(final String controllerId) {
// get the current attributes
final HashMap<String, String> attributes = new HashMap<>(targetManagement.getControllerAttributes(controllerId));
@@ -1799,7 +1857,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
attributes.keySet().forEach(assertThat(updatedAttributes)::containsKey);
}
@Step
private void updateTargetAttributesWithUpdateModeReplace(final String controllerId) {
// get the current attributes
final HashMap<String, String> attributes = new HashMap<>(targetManagement.getControllerAttributes(controllerId));
@@ -1819,7 +1876,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
attributes.entrySet().forEach(assertThat(updatedAttributes)::doesNotContain);
}
@Step
private void updateTargetAttributesWithoutUpdateMode(final String controllerId) {
// set the initial attributes
final Map<String, String> attributes = new HashMap<>();
@@ -1849,7 +1905,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
}
}
@Step
private void finishDownloadOnlyUpdateAndSendUpdateActionStatus(final Long actionId, final Status status) {
// finishing action
controllerManagement
@@ -1859,7 +1914,6 @@ class ControllerManagementTest extends AbstractJpaIntegrationTest {
assertThat(activeActionExistsForControllerId(DEFAULT_CONTROLLER_ID)).isFalse();
}
@Step
private void addUpdateActionStatus(final Long actionId, final String controllerId, final Status actionStatus) {
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId).status(actionStatus));
assertActionStatus(actionId, controllerId, TargetUpdateStatus.IN_SYNC, actionStatus, actionStatus, false);

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Set;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.Action;
@@ -23,74 +20,86 @@ import org.eclipse.hawkbit.repository.model.DistributionSetInvalidation;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
@Feature("SecurityTests - DeploymentManagement")
@Story("SecurityTests DeploymentManagement")
/**
* Feature: SecurityTests - DeploymentManagement<br/>
* Story: SecurityTests DeploymentManagement
*/
class DeploymentManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignDistributionSetsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignDistributionSetsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.assignDistributionSets(
List.of(new DeploymentRequest("controllerId", 1L, Action.ActionType.SOFT, 1L, 1, "maintenanceSchedule",
"maintenanceWindowDuration", "maintenanceWindowTimeZone", true))),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignDistributionSetsWithInitiatedByPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignDistributionSetsWithInitiatedByPermissionsCheck() {
assertPermissions(() -> deploymentManagement.assignDistributionSets("initiator",
List.of(new DeploymentRequest("controllerId", 1L, Action.ActionType.SOFT, 1L, 1, "maintenanceSchedule",
"maintenanceWindowDuration", "maintenanceWindowTimeZone", true)), "message"),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void offlineAssignedDistributionSetsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void offlineAssignedDistributionSetsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.offlineAssignedDistributionSets(List.of()), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void offlineAssignedDistributionSetsWithInitiatedByPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void offlineAssignedDistributionSetsWithInitiatedByPermissionsCheck() {
assertPermissions(() -> deploymentManagement.offlineAssignedDistributionSets(List.of(), "initiator"),
List.of(SpPermission.READ_REPOSITORY, SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void cancelActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void cancelActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.cancelAction(1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionsByTargetWithFilterPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionsByTargetWithFilterPermissionsCheck() {
assertPermissions(() -> deploymentManagement.countActionsByTarget("rsqlParam", "controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionsByTargetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionsByTargetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.countActionsByTarget("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionsAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionsAllPermissionsCheck() {
assertPermissions(() -> deploymentManagement.countActionsAll(), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.countActions("id==1"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findAction(1L), List.of(SpPermission.READ_TARGET));
}
@@ -99,137 +108,157 @@ class DeploymentManagementSecurityTest extends AbstractJpaIntegrationTest {
assertPermissions(() -> deploymentManagement.findActionsAll(Pageable.unpaged()), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActions("id==1", Pageable.unpaged()), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionsByTargetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionsByTargetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActionsByTarget("rsql==param", "controllerId", Pageable.unpaged()),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionsByTargetWithControllerIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionsByTargetWithControllerIdPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActionsByTarget("controllerId", Pageable.unpaged()),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionStatusByActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionStatusByActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActionStatusByAction(1L, Pageable.unpaged()), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionStatusByActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionStatusByActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.countActionStatusByAction(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findMessagesByActionStatusIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findMessagesByActionStatusIdPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findMessagesByActionStatusId(1L, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActionWithDetailsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActionWithDetailsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActionWithDetails(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActiveActionsByTargetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActiveActionsByTargetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActiveActionsByTarget("controllerId", Pageable.unpaged()),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findInActiveActionsByTargetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findInActiveActionsByTargetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findInActiveActionsByTarget("controllerId", Pageable.unpaged()),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActiveActionsWithHighestWeightPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActiveActionsWithHighestWeightPermissionsCheck() {
assertPermissions(() -> deploymentManagement.findActiveActionsWithHighestWeight("controllerId", 1), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void forceQuitActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void forceQuitActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.forceQuitAction(1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void forceTargetActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void forceTargetActionPermissionsCheck() {
assertPermissions(() -> deploymentManagement.forceTargetAction(1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void cancelInactiveScheduledActionsForTargetsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void cancelInactiveScheduledActionsForTargetsPermissionsCheck() {
assertPermissions(() -> {
deploymentManagement.cancelInactiveScheduledActionsForTargets(List.of(1L));
return null;
}, List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void startScheduledActionsByRolloutGroupParentPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void startScheduledActionsByRolloutGroupParentPermissionsCheck() {
assertPermissions(() -> {
deploymentManagement.startScheduledActionsByRolloutGroupParent(1L, 1L, 1L);
return null;
}, List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void startScheduledActionsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void startScheduledActionsPermissionsCheck() {
assertPermissions(() -> {
deploymentManagement.startScheduledActions(List.of());
return null;
}, List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getAssignedDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getAssignedDistributionSetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.getAssignedDistributionSet("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getInstalledDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getInstalledDistributionSetPermissionsCheck() {
assertPermissions(() -> deploymentManagement.getInstalledDistributionSet("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteActionsByStatusAndLastModifiedBeforePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteActionsByStatusAndLastModifiedBeforePermissionsCheck() {
assertPermissions(() -> deploymentManagement.deleteActionsByStatusAndLastModifiedBefore(Set.of(Action.Status.CANCELED), 1L),
List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void hasPendingCancellationsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void hasPendingCancellationsPermissionsCheck() {
assertPermissions(() -> deploymentManagement.hasPendingCancellations(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void cancelActionsForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void cancelActionsForDistributionSetPermissionsCheck() {
assertPermissions(() -> {
deploymentManagement.cancelActionsForDistributionSet(DistributionSetInvalidation.CancelationType.FORCE,
entityFactory.distributionSet().create().build());

View File

@@ -29,9 +29,6 @@ import java.util.stream.Stream;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.Getter;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.repository.ActionStatusFields;
@@ -96,17 +93,19 @@ import org.springframework.data.domain.Sort.Direction;
/**
* Test class testing the functionality of triggering a deployment of {@link DistributionSet}s to {@link Target}s.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Deployment Management
*/
@Feature("Component Tests - Repository")
@Story("Deployment Management")
class DeploymentManagementTest extends AbstractJpaIntegrationTest {
private static final boolean STATE_ACTIVE = true;
private static final boolean STATE_INACTIVE = false;
@Test
@Description("Tests that an exception is thrown when a target is assigned to an incomplete distribution set")
void verifyAssignTargetsToIncompleteDistribution() {
/**
* Tests that an exception is thrown when a target is assigned to an incomplete distribution set
*/
@Test void verifyAssignTargetsToIncompleteDistribution() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
final Target target = testdataFactory.createTarget();
@@ -115,9 +114,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> assignDistributionSet(distributionSet, target));
}
@Test
@Description("Tests that an exception is thrown when a target is assigned to an invalidated distribution set")
void verifyAssignTargetsToInvalidDistribution() {
/**
* Tests that an exception is thrown when a target is assigned to an invalidated distribution set
*/
@Test void verifyAssignTargetsToInvalidDistribution() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
final Target target = testdataFactory.createTarget();
@@ -126,18 +126,22 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> assignDistributionSet(distributionSet, target));
}
/**
* Verifies that management get access react as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means " +
"of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(deploymentManagement.findAction(1234L)).isNotPresent();
assertThat(deploymentManagement.findActionWithDetails(NOT_EXIST_IDL)).isNotPresent();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities " +
" by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final Target target = testdataFactory.createTarget();
@@ -160,9 +164,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> deploymentManagement.forceTargetAction(NOT_EXIST_IDL), "Action");
}
@Test
@Description("Test verifies that the repistory retrieves the action including all defined (lazy) details.")
void findActionWithLazyDetails() {
/**
* Test verifies that the repistory retrieves the action including all defined (lazy) details.
*/
@Test void findActionWithLazyDetails() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
new ArrayList<>());
final List<Target> testTarget = testdataFactory.createTargets(1);
@@ -177,9 +182,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isNotNull();
}
@Test
@Description("Test verifies that actions of a target are found by using id-based search.")
void findActionByTargetId() {
/**
* Test verifies that actions of a target are found by using id-based search.
*/
@Test void findActionByTargetId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", new ArrayList<>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
@@ -193,9 +199,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(actions.getContent().get(0).getId()).as("Action of target").isEqualTo(actionId);
}
@Test
@Description("Test verifies that the 'max actions per target' quota is enforced.")
void assertMaxActionsPerTargetQuotaIsEnforced() {
/**
* Test verifies that the 'max actions per target' quota is enforced.
*/
@Test void assertMaxActionsPerTargetQuotaIsEnforced() {
enableMultiAssignments();
final int maxActions = quotaManagement.getMaxActionsPerTarget();
@@ -211,9 +218,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> assignDistributionSet(ds1Id, controllerId, 77));
}
@Test
@Description("An assignment request with more assignments than allowed by 'maxTargetDistributionSetAssignmentsPerManualAssignment' quota throws an exception.")
void assignmentRequestThatIsTooLarge() {
/**
* An assignment request with more assignments than allowed by 'maxTargetDistributionSetAssignmentsPerManualAssignment' quota throws an exception.
*/
@Test void assignmentRequestThatIsTooLarge() {
final int maxActions = quotaManagement.getMaxTargetDistributionSetAssignmentsPerManualAssignment();
final DistributionSet ds1 = testdataFactory.createDistributionSet("1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("2");
@@ -225,9 +233,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThatExceptionOfType(AssignmentQuotaExceededException.class).isThrownBy(() -> assignDistributionSet(ds2, targets));
}
@Test
@Description("Test verifies that action-states of an action are found by using id-based search.")
void findActionStatusByActionId() {
/**
* Test verifies that action-states of an action are found by using id-based search.
*/
@Test void findActionStatusByActionId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", Collections.emptyList());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
@@ -242,9 +251,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(actionStates.getContent().get(0)).as("Action-status of action").isEqualTo(expectedActionStatus);
}
@Test
@Description("Test verifies that messages of an action-status are found by using id-based search.")
void findMessagesByActionStatusId() {
/**
* Test verifies that messages of an action-status are found by using id-based search.
*/
@Test void findMessagesByActionStatusId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", new ArrayList<>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
@@ -268,9 +278,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(messages.getContent().get(0)).as("Message of action-status").isEqualTo(expectedMsg);
}
@Test
@Description("Ensures that tag to distribution set assignment that does not exist will cause EntityNotFoundException.")
void assignDistributionSetToTagThatDoesNotExistThrowsException() {
/**
* Ensures that tag to distribution set assignment that does not exist will cause EntityNotFoundException.
*/
@Test void assignDistributionSetToTagThatDoesNotExistThrowsException() {
final List<Long> assignDS = new ArrayList<>(5);
for (int i = 0; i < 4; i++) {
assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", Collections.emptyList()).getId());
@@ -286,9 +297,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.withMessageContaining(String.valueOf(100L));
}
@Test
@Description("Test verifies that an assignment with automatic cancelation works correctly even if the update is split into multiple partitions on the database.")
@ExpectEvents({
/**
* Test verifies that an assignment with automatic cancelation works correctly even if the update is split into multiple partitions on the database.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 20),
@Expect(type = TargetUpdatedEvent.class, count = 40),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 2),
@@ -313,10 +325,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2L * quotaManagement.getMaxTargetsPerAutoAssignment());
}
/**
* Cancels multiple active actions on a target. Expected behaviour is that with two active
* After canceling the first one also the target goes back to IN_SYNC as no open action is left.
*/
@Test
@Description("Cancels multiple active actions on a target. Expected behaviour is that with two active " +
"actions after canceling the second active action the first one is still running as it is not touched by the cancelation. " +
"After canceling the first one also the target goes back to IN_SYNC as no open action is left.")
void manualCancelWithMultipleAssignmentsCancelLastOneFirst() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
@@ -360,10 +373,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
/**
* Cancels multiple active actions on a target. Expected behaviour is that with two active
* also the target goes back to IN_SYNC as no open action is left.
*/
@Test
@Description("Cancels multiple active actions on a target. Expected behaviour is that with two active "
+ "actions after canceling the first active action the system switched to second one. After canceling this one "
+ "also the target goes back to IN_SYNC as no open action is left.")
void manualCancelWithMultipleAssignmentsCancelMiddleOneFirst() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
@@ -411,9 +425,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@Test
@Description("Force Quit an Assignment. Expected behaviour is that the action is canceled and is marked as deleted. The assigned Software module")
void forceQuitSetActionToInactive() {
/**
* Force Quit an Assignment. Expected behaviour is that the action is canceled and is marked as deleted. The assigned Software module
*/
@Test void forceQuitSetActionToInactive() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
final DistributionSet dsInstalled = action.getDistributionSet();
@@ -446,9 +461,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@Test
@Description("Force Quit an not canceled Assignment. Expected behaviour is that the action can not be force quit and there is thrown an exception.")
void forceQuitNotAllowedThrowsException() {
/**
* Force Quit an not canceled Assignment. Expected behaviour is that the action can not be force quit and there is thrown an exception.
*/
@Test void forceQuitNotAllowedThrowsException() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
// verify initial status
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong update status")
@@ -468,9 +484,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> deploymentManagement.forceQuitAction(assigningActionId));
}
/**
* Simple offline deployment of a distribution set to a list of targets. Verifies that offline assigment
* is correctly executed for targets that do not have a running update already. Those are ignored.
*/
@Test
@Description("Simple offline deployment of a distribution set to a list of targets. Verifies that offline assigment "
+ "is correctly executed for targets that do not have a running update already. Those are ignored.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 20),
@Expect(type = TargetUpdatedEvent.class, count = 20),
@@ -512,9 +530,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.allMatch(target -> target.getLastModifiedAt() == target.getInstallationDate());
}
@Test
@Description("Offline assign multiple DSs to a single Target in multiassignment mode.")
@ExpectEvents({
/**
* Offline assign multiple DSs to a single Target in multiassignment mode.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4),
@Expect(type = ActionCreatedEvent.class, count = 4),
@@ -548,9 +567,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Verifies that if an account is set to action autoclose running actions in case of a new assigned set get closed and set to CANCELED.")
@ExpectEvents({
/**
* Verifies that if an account is set to action autoclose running actions in case of a new assigned set get closed and set to CANCELED.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 10),
@Expect(type = TargetUpdatedEvent.class, count = 20),
@Expect(type = ActionCreatedEvent.class, count = 20),
@@ -591,9 +611,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("If multi-assignment is enabled, verify that the previous Distribution Set assignment is not canceled when a new one is assigned.")
@ExpectEvents({
/**
* If multi-assignment is enabled, verify that the previous Distribution Set assignment is not canceled when a new one is assigned.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 10),
@Expect(type = TargetUpdatedEvent.class, count = 20),
@Expect(type = ActionCreatedEvent.class, count = 20),
@@ -622,9 +643,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertDsExclusivelyAssignedToTargets(targets, ds1.getId(), STATE_ACTIVE, RUNNING);
}
@Test
@Description("Assign multiple DSs to a single Target in one request in multiassignment mode.")
@ExpectEvents({
/**
* Assign multiple DSs to a single Target in one request in multiassignment mode.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4),
@Expect(type = ActionCreatedEvent.class, count = 4),
@@ -659,9 +681,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Assign multiple DSs to single Target in one request in multiAssignment mode and cancel each created action afterwards.")
@ExpectEvents({
/**
* Assign multiple DSs to single Target in one request in multiAssignment mode and cancel each created action afterwards.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4),
@Expect(type = ActionCreatedEvent.class, count = 4),
@@ -695,9 +718,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}));
}
@Test
@Description("A Request resulting in multiple assignments to a single target is only allowed when multiassignment is enabled.")
void multipleAssignmentsToTargetOnlyAllowedInMultiAssignMode() {
/**
* A Request resulting in multiple assignments to a single target is only allowed when multiassignment is enabled.
*/
@Test void multipleAssignmentsToTargetOnlyAllowedInMultiAssignMode() {
final Target target = testdataFactory.createTarget();
final List<DistributionSet> distributionSets = testdataFactory.createDistributionSets(2);
@@ -716,9 +740,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
deploymentManagement.assignDistributionSets(Arrays.asList(targetToDS0, targetToDS1)))).isEqualTo(2);
}
@Test
@Description("Assigning distribution set to the list of targets with a non-existing one leads to successful assignment of valid targets, while not found targets are silently ignored.")
void assignDistributionSetToNotExistingTarget() {
/**
* Assigning distribution set to the list of targets with a non-existing one leads to successful assignment of valid targets, while not found targets are silently ignored.
*/
@Test void assignDistributionSetToNotExistingTarget() {
final String notExistingId = "notExistingTarget";
final DistributionSet createdDs = testdataFactory.createDistributionSet();
@@ -741,9 +766,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}
}
/**
* Assignments with confirmation flow active will result in actions in 'WAIT_FOR_CONFIRMATION' state
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
@Description("Assignments with confirmation flow active will result in actions in 'WAIT_FOR_CONFIRMATION' state")
void assignmentWithConfirmationFlowActive(final boolean confirmationRequired) {
final List<String> controllerIds = testdataFactory.createTargets(1).stream().map(Target::getControllerId).toList();
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
@@ -767,9 +794,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}));
}
/**
* Verify auto confirmation assignments and check action status with messages
*/
@ParameterizedTest
@ValueSource(booleans = { true, false })
@Description("Verify auto confirmation assignments and check action status with messages")
void assignmentWithAutoConfirmationWillBeHandledCorrectly(final boolean confirmationRequired) {
enableConfirmationFlow();
@@ -816,9 +845,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Multiple assignments with confirmation flow active will result in correct cancel behaviour")
void multipleAssignmentWithConfirmationFlowActiveVerifyCancelBehaviour() {
/**
* Multiple assignments with confirmation flow active will result in correct cancel behaviour
*/
@Test void multipleAssignmentWithConfirmationFlowActiveVerifyCancelBehaviour() {
final Target target = testdataFactory.createTarget("firstDevice");
final DistributionSet firstDs = testdataFactory.createDistributionSet();
final DistributionSet secondDs = testdataFactory.createDistributionSet();
@@ -852,9 +882,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Assignments with confirmation flow deactivated will result in actions in only in 'RUNNING' state")
void verifyConfirmationRequiredFlagHaveNoInfluenceIfFlowIsDeactivated() {
/**
* Assignments with confirmation flow deactivated will result in actions in only in 'RUNNING' state
*/
@Test void verifyConfirmationRequiredFlagHaveNoInfluenceIfFlowIsDeactivated() {
final List<String> targets1 = testdataFactory.createTargets("group1", 1).stream().map(Target::getControllerId).toList();
final List<String> targets2 = testdataFactory.createTargets("group2", 1).stream().map(Target::getControllerId).toList();
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
@@ -877,9 +908,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}));
}
@Test
@Description("Duplicate Assignments are removed from a request when multiassignment is disabled, otherwise not")
@ExpectEvents({
/**
* Duplicate Assignments are removed from a request when multiassignment is disabled, otherwise not
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -907,9 +939,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(1);
}
@Test
@Description("An assignment request is not accepted if it would lead to a target exceeding the max actions per target quota.")
@ExpectEvents({
/**
* An assignment request is not accepted if it would lead to a target exceeding the max actions per target quota.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 21), // max actions per target are 20 for test
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3 * 21),
@@ -936,9 +969,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(actionRepository.countByTargetControllerId(controllerId)).isZero();
}
@Test
@Description("An assignment request without a weight is ok when multi assignment in enabled.")
void weightNotRequiredInMultiAssignmentMode() {
/**
* An assignment request without a weight is ok when multi assignment in enabled.
*/
@Test void weightNotRequiredInMultiAssignmentMode() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
@@ -949,9 +983,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.assignDistributionSets(List.of(assignWithoutWeight, assignWithWeight))).isNotNull();
}
@Test
@Description("An assignment request containing a weight don't causes an error when multi assignment in disabled.")
void weightAllowedWhenMultiAssignmentModeNotEnabled() {
/**
* An assignment request containing a weight don't causes an error when multi assignment in disabled.
*/
@Test void weightAllowedWhenMultiAssignmentModeNotEnabled() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
@@ -959,9 +994,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(deploymentManagement.assignDistributionSets(Collections.singletonList(assignWithoutWeight))).isNotNull().size().isEqualTo(1);
}
@Test
@Description("Weights are validated and contained in the resulting Action.")
@ExpectEvents({
/**
* Weights are validated and contained in the resulting Action.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1002,9 +1038,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
* {@link TargetRepository#assignDistributionSet(DistributionSet, Iterable)} and
* checking the active action and the action history of the targets.
*/
@Test
@Description("Simple deployment or distribution set to target assignment test.")
@ExpectEvents({
/**
* Simple deployment or distribution set to target assignment test.
*/
@Test @ExpectEvents({
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@@ -1058,9 +1095,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Test that it is not possible to assign a distribution set that is not complete.")
@ExpectEvents({
/**
* Test that it is not possible to assign a distribution set that is not complete.
*/
@Test @ExpectEvents({
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 2),
@@ -1089,9 +1127,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(10);
}
/**
* Multiple deployments or distribution set to target assignment test. Expected behaviour is that a new deployment
* overides unfinished old one which are canceled as part of the operation.
*/
@Test
@Description("Multiple deployments or distribution set to target assignment test. Expected behaviour is that a new deployment "
+ "overides unfinished old one which are canceled as part of the operation.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 5 + 4),
@Expect(type = TargetUpdatedEvent.class, count = 3 * 4),
@@ -1153,10 +1193,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.doesNotContain(toArray(deployedTargetsFromDB, JpaTarget.class));
}
/**
* Multiple deployments or distribution set to target assignment test including finished response
* IN_SYNC status and installed DS is set to the assigned DS entry.
*/
@Test
@Description("Multiple deployments or distribution set to target assignment test including finished response "
+ "from target/controller. Expected behaviour is that in case of OK finished update the target will go to "
+ "IN_SYNC status and installed DS is set to the assigned DS entry.")
void assignDistributionSetAndAddFinishedActionStatus() {
final PageRequest pageRequest = PageRequest.of(0, 100, Direction.ASC, ActionStatusFields.ID.getJpaEntityFieldName());
@@ -1247,9 +1288,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
* {@link Target}s are assigned by {@link Target#getAssignedDistributionSet()}
* or {@link Target#getInstalledDistributionSet()}
*/
/**
* Deletes distribution set. Expected behaviour is that a soft delete is performed
* if the DS is assigned to a target and a hard delete if the DS is not in use at all.
*/
@Test
@Description("Deletes distribution set. Expected behaviour is that a soft delete is performed "
+ "if the DS is assigned to a target and a hard delete if the DS is not in use at all.")
void deleteDistributionSet() {
final PageRequest pageRequest = PageRequest.of(0, 100, Direction.ASC, "id");
@@ -1304,9 +1347,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Deletes multiple targets and verifies that all related metadata is also deleted.")
void deletesTargetsAndVerifyCascadeDeletes() {
/**
* Deletes multiple targets and verifies that all related metadata is also deleted.
*/
@Test void deletesTargetsAndVerifyCascadeDeletes() {
final String undeployedTargetPrefix = "undep-T";
final int noOfUndeployedTargets = 2;
@@ -1330,9 +1374,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(actionStatusRepository.count()).as("size of action status is wrong").isZero();
}
@Test
@Description("Testing if changing target and the status without refreshing the entities from the DB (e.g. concurrent changes from UI and from controller) works")
void alternatingAssignmentAndAddUpdateActionStatus() {
/**
* Testing if changing target and the status without refreshing the entities from the DB (e.g. concurrent changes from UI and from controller) works
*/
@Test void alternatingAssignmentAndAddUpdateActionStatus() {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
final DistributionSet dsB = testdataFactory.createDistributionSet("b");
@@ -1402,9 +1447,11 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.get(0).getDistributionSet(), "Active ds is wrong");
}
/**
* The test verifies that the DS itself is not changed because of an target assignment
* which is a relationship but not a changed on the entity itself..
*/
@Test
@Description("The test verifies that the DS itself is not changed because of an target assignment"
+ " which is a relationship but not a changed on the entity itself..")
void checkThatDsRevisionsIsNotChangedWithTargetAssignment() {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
testdataFactory.createDistributionSet("b");
@@ -1421,9 +1468,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
}
@Test
@Description("Tests the switch from a soft to hard update by API")
void forceSoftAction() {
/**
* Tests the switch from a soft to hard update by API
*/
@Test void forceSoftAction() {
// prepare
final Target target = testdataFactory.createTarget("knownControllerId");
final DistributionSet ds = testdataFactory.createDistributionSet("a");
@@ -1443,9 +1491,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
}
@Test
@Description("Tests the switch from a hard to hard update by API, e.g. which in fact should not change anything.")
void forceAlreadyForcedActionNothingChanges() {
/**
* Tests the switch from a hard to hard update by API, e.g. which in fact should not change anything.
*/
@Test void forceAlreadyForcedActionNothingChanges() {
// prepare
final Target target = testdataFactory.createTarget("knownControllerId");
final DistributionSet ds = testdataFactory.createDistributionSet("a");
@@ -1466,9 +1515,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
}
@Test
@Description("Tests the computation of already assigned entities returned as a result of an assignment")
void testAlreadyAssignedAndAssignedActionsInAssignmentResult() {
/**
* Tests the computation of already assigned entities returned as a result of an assignment
*/
@Test void testAlreadyAssignedAndAssignedActionsInAssignmentResult() {
// create target1, distributionSet, assign ds to target1 and finish
// update (close all actions)
final Action action = prepareFinishedUpdate("target1", "ds", false);
@@ -1495,9 +1545,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.noneMatch(a -> a.getTarget().getControllerId().equals("target1"));
}
@Test
@Description("Verify that the DistributionSetAssignmentResult not contains already assigned targets.")
void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() {
/**
* Verify that the DistributionSetAssignmentResult not contains already assigned targets.
*/
@Test void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() {
final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3");
// create assigned DS
@@ -1512,9 +1563,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetRepository.findAll()).hasSize(1);
}
@Test
@Description("Verify that the DistributionSet assignments work for multiple targets of the same target type within the same request.")
void verifyDSAssignmentForMultipleTargetsWithSameTargetType() {
/**
* Verify that the DistributionSet assignments work for multiple targets of the same target type within the same request.
*/
@Test void verifyDSAssignmentForMultipleTargetsWithSameTargetType() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType targetType = testdataFactory.createTargetType("test-type",
Collections.singletonList(ds.getType()));
@@ -1537,9 +1589,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.forEach(jpaTarget -> assertThat(jpaTarget.getAssignedDistributionSet()).isEqualTo(ds));
}
@Test
@Description("Verify that the DistributionSet assignments work for multiple targets of different target types.")
void verifyDSAssignmentForMultipleTargetsWithDifferentTargetTypes() {
/**
* Verify that the DistributionSet assignments work for multiple targets of different target types.
*/
@Test void verifyDSAssignmentForMultipleTargetsWithDifferentTargetTypes() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType targetType1 = testdataFactory.createTargetType("test-type1", Collections.singletonList(ds.getType()));
final TargetType targetType2 = testdataFactory.createTargetType("test-type2", Collections.singletonList(ds.getType()));
@@ -1562,9 +1615,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
assertThat(assignedDsTarget2).isEqualTo(ds);
}
@Test
@Description("Verify that the DistributionSet assignment fails for target with incompatible target type.")
void verifyDSAssignmentFailsForTargetsWithIncompatibleTargetTypes() {
/**
* Verify that the DistributionSet assignment fails for target with incompatible target type.
*/
@Test void verifyDSAssignmentFailsForTargetsWithIncompatibleTargetTypes() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final DistributionSetType dsType = testdataFactory.findOrCreateDistributionSetType("test-ds-type", "dsType");
final TargetType targetType = testdataFactory.createTargetType("target-type",
@@ -1579,9 +1633,10 @@ class DeploymentManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
}
@Test
@Description("Verify that the DistributionSet assignment fails for target with target type that is not compatible with any dsType.")
void verifyDSAssignmentFailsForTargetsWithTargetTypesThatAreNotCompatibleWithAnyDs() {
/**
* Verify that the DistributionSet assignment fails for target with target type that is not compatible with any dsType.
*/
@Test void verifyDSAssignmentFailsForTargetsWithTargetTypesThatAreNotCompatibleWithAnyDs() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType emptyTargetType = testdataFactory.createTargetType("target-type", Collections.emptyList());
final Target targetWithEmptyType = testdataFactory.createTarget("test-target", "test-target",

View File

@@ -15,9 +15,6 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.Collections;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -41,14 +38,16 @@ import org.springframework.data.repository.query.Param;
/**
* Test class testing the functionality of invalidating a
* {@link DistributionSet}
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Distribution set invalidation management
*/
@Feature("Component Tests - Repository")
@Story("Distribution set invalidation management")
class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verify invalidation of distribution sets that only removes distribution sets from auto assignments")
void verifyInvalidateDistributionSetStopAutoAssignment() {
/**
* Verify invalidation of distribution sets that only removes distribution sets from auto assignments
*/
@Test void verifyInvalidateDistributionSetStopAutoAssignment() {
final InvalidationTestData invalidationTestData = createInvalidationTestData("verifyInvalidateDistributionSetStopAutoAssignment");
final DistributionSetInvalidation distributionSetInvalidation = new DistributionSetInvalidation(
@@ -74,9 +73,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
}
}
@Test
@Description("Verify invalidation of distribution sets that removes distribution sets from auto assignments and stops rollouts")
void verifyInvalidateDistributionSetStopRollouts() {
/**
* Verify invalidation of distribution sets that removes distribution sets from auto assignments and stops rollouts
*/
@Test void verifyInvalidateDistributionSetStopRollouts() {
final InvalidationTestData invalidationTestData = createInvalidationTestData(
"verifyInvalidateDistributionSetStopRollouts");
@@ -106,9 +106,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
}
}
@Test
@Description("Verify invalidation of distribution sets that removes distribution sets from auto assignments, stops rollouts and force cancels assignments")
void verifyInvalidateDistributionSetStopAllAndForceCancel() {
/**
* Verify invalidation of distribution sets that removes distribution sets from auto assignments, stops rollouts and force cancels assignments
*/
@Test void verifyInvalidateDistributionSetStopAllAndForceCancel() {
final InvalidationTestData invalidationTestData = createInvalidationTestData(
"verifyInvalidateDistributionSetStopAllAndForceCancel");
@@ -136,9 +137,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
}
}
@Test
@Description("Verify invalidation of distribution sets that removes distribution sets from auto assignments, stops rollouts and cancels assignments")
void verifyInvalidateDistributionSetStopAll() {
/**
* Verify invalidation of distribution sets that removes distribution sets from auto assignments, stops rollouts and cancels assignments
*/
@Test void verifyInvalidateDistributionSetStopAll() {
final InvalidationTestData invalidationTestData = createInvalidationTestData(
"verifyInvalidateDistributionSetStopAll");
@@ -163,9 +165,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
}
}
@Test
@Description("Verify that invalidating an incomplete distribution set throws an exception")
void verifyInvalidateIncompleteDistributionSetThrowsException() {
/**
* Verify that invalidating an incomplete distribution set throws an exception
*/
@Test void verifyInvalidateIncompleteDistributionSetThrowsException() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
final DistributionSetInvalidation distributionSetInvalidation = new DistributionSetInvalidation(
@@ -175,9 +178,11 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
.isThrownBy(() -> distributionSetInvalidationManagement.invalidateDistributionSet(distributionSetInvalidation));
}
/**
* Verify that invalidating an invalidated distribution set don't throws an exception
* -> should be able to cancel actions again (if previous time there was a problem
*/
@Test
@Description("Verify that invalidating an invalidated distribution set don't throws an exception" +
" -> should be able to cancel actions again (if previous time there was a problem")
@SuppressWarnings("java:S2699") // test that no exception is thrown
void verifyInvalidateInvalidatedDistributionSetDontThrowsException() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
@@ -186,9 +191,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
CancelationType.SOFT, true));
}
@Test
@Description("Verify that a user that has authority READ_REPOSITORY and UPDATE_REPOSITORY is allowed to invalidate a distribution set")
@WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY" })
/**
* Verify that a user that has authority READ_REPOSITORY and UPDATE_REPOSITORY is allowed to invalidate a distribution set
*/
@Test @WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY" })
void verifyInvalidateWithReadAndUpdateRepoAuthority() {
final InvalidationTestData invalidationTestData = systemSecurityContext
.runAsSystem(() -> createInvalidationTestData("verifyInvalidateWithUpdateRepoAuthority"));
@@ -201,9 +207,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
.isFalse();
}
@Test
@Description("Verify that a user that has authority READ_REPOSITORY, UPDATE_REPOSITORY and UPDATE_TARGET is allowed to invalidate a distribution set only without canceling rollouts")
@WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY", "UPDATE_TARGET" })
/**
* Verify that a user that has authority READ_REPOSITORY, UPDATE_REPOSITORY and UPDATE_TARGET is allowed to invalidate a distribution set only without canceling rollouts
*/
@Test @WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY", "UPDATE_TARGET" })
void verifyInvalidateWithReadAndUpdateRepoAndUpdateTargetAuthority() {
final InvalidationTestData invalidationTestData = systemSecurityContext.runAsSystem(
() -> createInvalidationTestData("verifyInvalidateWithUpdateRepoAndUpdateTargetAuthority"));
@@ -222,9 +229,10 @@ class DistributionSetInvalidationManagementTest extends AbstractJpaIntegrationTe
.isFalse();
}
@Test
@Description("Verify that a user that has authority READ_REPOSITORY, UPDATE_REPOSITORY, UPDATE_ROLLOUT and UPDATE_TARGET is allowed to invalidate a distribution")
@WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY", "UPDATE_TARGET", "UPDATE_ROLLOUT" })
/**
* Verify that a user that has authority READ_REPOSITORY, UPDATE_REPOSITORY, UPDATE_ROLLOUT and UPDATE_TARGET is allowed to invalidate a distribution
*/
@Test @WithUser(authorities = { "READ_REPOSITORY", "UPDATE_REPOSITORY", "UPDATE_TARGET", "UPDATE_ROLLOUT" })
void verifyInvalidateWithReadAndUpdateRepoAndUpdateTargetAndUpdateRolloutAuthority() {
final InvalidationTestData invalidationTestData = systemSecurityContext.runAsSystem(
() -> createInvalidationTestData("verifyInvalidateWithUpdateRepoAndUpdateTargetAuthority"));

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Map;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
@@ -24,8 +21,10 @@ import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetFilter;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - DistributionSetManagement")
@Story("SecurityTests DistributionSetManagement")
/**
* Feature: SecurityTests - DistributionSetManagement<br/>
* Story: SecurityTests DistributionSetManagement
*/
class DistributionSetManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<DistributionSet, DistributionSetCreate, DistributionSetUpdate> {
@@ -45,29 +44,33 @@ class DistributionSetManagementSecurityTest
.description("a new description").version("a new version").requiredMigrationStep(true);
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignSoftwareModulesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignSoftwareModulesPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.assignSoftwareModules(1L, List.of(1L)), List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignTagPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.assignTag(List.of(1L), 1L),
List.of(SpPermission.UPDATE_REPOSITORY, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests that the method throws InsufficientPermissionException when the user does not have the correct permission")
void unassignTagPermissionsCheck() {
/**
* Tests that the method throws InsufficientPermissionException when the user does not have the correct permission
*/
@Test void unassignTagPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.unassignTag(List.of(1L), 1L),
List.of(SpPermission.UPDATE_REPOSITORY, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createMetadataPermissionsCheck() {
assertPermissions(
() -> {
distributionSetManagement.createMetadata(1L, Map.of("key", "value"));
@@ -76,15 +79,17 @@ class DistributionSetManagementSecurityTest
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getMetadataPermissiosCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getMetadataPermissiosCheck() {
assertPermissions(() -> distributionSetManagement.getMetadata(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updateMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updateMetadataPermissionsCheck() {
assertPermissions(() -> {
distributionSetManagement.updateMetadata(1L,"key", "value");
return null;
@@ -92,146 +97,168 @@ class DistributionSetManagementSecurityTest
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteMetadataPermissionsCheck() {
assertPermissions(() -> {
distributionSetManagement.deleteMetadata(1L, "key");
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void lockPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void lockPermissionsCheck() {
assertPermissions(() -> {
distributionSetManagement.lock(1L);
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unlockPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unlockPermissionsCheck() {
assertPermissions(() -> {
distributionSetManagement.unlock(1L);
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByActionPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByAction(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getWithDetailsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getWithDetailsPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.getWithDetails(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNameAndVersionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNameAndVersionPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByNameAndVersion("name", "version"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getValidAndCompletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getValidAndCompletePermissionsCheck() {
assertPermissions(() -> distributionSetManagement.getValidAndComplete(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getValidPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getValidPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.getValid(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getOrElseThrowExceptionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getOrElseThrowExceptionPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.getOrElseThrowException(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByCompletedPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByCompletedPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByCompleted(true, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByCompletedPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByCompletedPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countByCompleted(true), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByDistributionSetFilterPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByDistributionSetFilterPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByDistributionSetFilter(DistributionSetFilter.builder().build(), PAGE),
List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByDistributionSetFilterPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByDistributionSetFilterPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countByDistributionSetFilter(DistributionSetFilter.builder().build()),
List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTagPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByTag(1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlAndTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlAndTagPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.findByRsqlAndTag("rsql", 1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void isInUsePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void isInUsePermissionsCheck() {
assertPermissions(() -> distributionSetManagement.isInUse(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignSoftwareModulePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignSoftwareModulePermissionsCheck() {
assertPermissions(() -> distributionSetManagement.unassignSoftwareModule(1L, 1L), List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByTypeIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByTypeIdPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countByTypeId(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countRolloutsByStatusForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countRolloutsByStatusForDistributionSetPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countRolloutsByStatusForDistributionSet(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countActionsByStatusForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countActionsByStatusForDistributionSetPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countActionsByStatusForDistributionSet(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countAutoAssignmentsForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countAutoAssignmentsForDistributionSetPermissionsCheck() {
assertPermissions(() -> distributionSetManagement.countAutoAssignmentsForDistributionSet(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void invalidatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void invalidatePermissionsCheck() {
distributionSetTypeManagement.create(entityFactory.distributionSetType().create().key("type").name("name"));
assertPermissions(() -> {
distributionSetManagement.invalidate(entityFactory.distributionSet().create().name("name").version("1.0").type("type").build());

View File

@@ -28,10 +28,6 @@ import java.util.stream.Stream;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.assertj.core.api.Condition;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.RepositoryProperties;
@@ -73,9 +69,10 @@ import org.springframework.beans.factory.annotation.Autowired;
/**
* {@link DistributionSetManagement} tests.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: DistributionSet Management
*/
@Feature("Component Tests - Repository")
@Story("DistributionSet Management")
class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
private static final String TAG1_NAME = "Tag1";
@@ -83,9 +80,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
@Autowired
RepositoryProperties repositoryProperties;
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means of Optional not present.")
@ExpectEvents({
/**
* Verifies that management get access react as specified on calls for non existing entities by means of Optional not present.
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
void nonExistingEntityAccessReturnsNotPresent() {
@@ -96,9 +94,11 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.getMetadata(set.getId()).get(NOT_EXIST_ID)).isNull();
}
/**
* Verifies that management queries react as specified on calls for non existing entities by means of
* throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities by means of " +
"throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetTagCreatedEvent.class, count = 1),
@@ -165,9 +165,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> distributionSetManagement.getValid(NOT_EXIST_IDL), "DistributionSet");
}
@Test
@Description("Verify that a DistributionSet with invalid properties cannot be created or updated")
@ExpectEvents({
/**
* Verify that a DistributionSet with invalid properties cannot be created or updated
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetUpdatedEvent.class) })
@@ -179,18 +180,20 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
createAndUpdateDistributionSetWithInvalidVersion(set);
}
@Test
@Description("Ensures that it is not possible to create a DS that already exists (unique constraint is on name,version for DS).")
void createDuplicateDistributionSetsFailsWithException() {
/**
* Ensures that it is not possible to create a DS that already exists (unique constraint is on name,version for DS).
*/
@Test void createDuplicateDistributionSetsFailsWithException() {
testdataFactory.createDistributionSet("a");
assertThatThrownBy(() -> testdataFactory.createDistributionSet("a"))
.isInstanceOf(EntityAlreadyExistsException.class);
}
@Test
@Description("Verifies that a DS is of default type if not specified explicitly at creation time.")
void createDistributionSetWithImplicitType() {
/**
* Verifies that a DS is of default type if not specified explicitly at creation time.
*/
@Test void createDistributionSetWithImplicitType() {
final DistributionSet set = distributionSetManagement
.create(entityFactory.distributionSet().create().name("newtypesoft").version("1"));
@@ -200,18 +203,20 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that a DS cannot be created if another DS with same name and version exists.")
void createDistributionSetWithDuplicateNameAndVersionFails() {
/**
* Verifies that a DS cannot be created if another DS with same name and version exists.
*/
@Test void createDistributionSetWithDuplicateNameAndVersionFails() {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create().name("newtypesoft").version("1");
distributionSetManagement.create(distributionSetCreate);
assertThatExceptionOfType(EntityAlreadyExistsException.class).isThrownBy(() -> distributionSetManagement.create(distributionSetCreate));
}
@Test
@Description("Verifies that multiple DS are of default type if not specified explicitly at creation time.")
void createMultipleDistributionSetsWithImplicitType() {
/**
* Verifies that multiple DS are of default type if not specified explicitly at creation time.
*/
@Test void createMultipleDistributionSetsWithImplicitType() {
final List<DistributionSetCreate> creates = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
creates.add(entityFactory.distributionSet().create().name("newtypesoft" + i).version("1" + i));
@@ -228,9 +233,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Checks that metadata for a distribution set can be created.")
void createMetadata() {
/**
* Checks that metadata for a distribution set can be created.
*/
@Test void createMetadata() {
final String knownKey = "dsMetaKnownKey";
final String knownValue = "dsMetaKnownValue";
@@ -239,9 +245,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
insertMetadata(knownKey, knownValue, ds); // and validate
}
@Test
@Description("Verifies the enforcement of the metadata quota per distribution set.")
void createMetadataUntilQuotaIsExceeded() {
/**
* Verifies the enforcement of the metadata quota per distribution set.
*/
@Test void createMetadataUntilQuotaIsExceeded() {
// add meta data one by one
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
@@ -283,9 +290,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.createMetadata(ds3Id, metaData3));
}
@Test
@Description("Ensures that distribution sets can assigned and unassigned to a distribution set tag.")
void assignAndUnassignDistributionSetToTag() {
/**
* Ensures that distribution sets can assigned and unassigned to a distribution set tag.
*/
@Test void assignAndUnassignDistributionSetToTag() {
final List<Long> assignDS = new ArrayList<>(4);
for (int i = 0; i < 4; i++) {
assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", Collections.emptyList()).getId());
@@ -319,9 +327,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.getNumberOfElements()).as("ds tag ds has wrong ds size").isEqualTo(3);
}
@Test
@Description("Ensures that updates concerning the internal software structure of a DS are not possible if the DS is already assigned.")
void updateDistributionSetForbiddenWithIllegalUpdate() {
/**
* Ensures that updates concerning the internal software structure of a DS are not possible if the DS is already assigned.
*/
@Test void updateDistributionSetForbiddenWithIllegalUpdate() {
// prepare data
final Target target = testdataFactory.createTarget();
@@ -348,9 +357,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Ensures that it is not possible to add a software module that is not defined of the DS's type.")
void updateDistributionSetUnsupportedModuleFails() {
/**
* Ensures that it is not possible to add a software module that is not defined of the DS's type.
*/
@Test void updateDistributionSetUnsupportedModuleFails() {
final Long setId = distributionSetManagement.create(
entityFactory.distributionSet().create()
.type(distributionSetTypeManagement.create(
@@ -369,9 +379,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isInstanceOf(UnsupportedSoftwareModuleForThisDistributionSetException.class);
}
@Test
@Description("Legal updates of a DS, e.g. name or description and module addition, removal while still unassigned.")
void updateDistributionSet() {
/**
* Legal updates of a DS, e.g. name or description and module addition, removal while still unassigned.
*/
@Test void updateDistributionSet() {
// prepare data
DistributionSet ds = testdataFactory.createDistributionSet("");
final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
@@ -398,9 +409,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(ds.isRequiredMigrationStep()).isTrue();
}
@Test
@Description("Verifies that an exception is thrown when trying to update an invalid distribution set")
void updateInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to update an invalid distribution set
*/
@Test void updateInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
final DistributionSetUpdate update = entityFactory.distributionSet().update(distributionSet.getId()).name("new_name");
@@ -408,9 +420,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.as("Invalid distributionSet should throw an exception").isThrownBy(() -> distributionSetManagement.update(update));
}
@Test
@Description("Verifies the enforcement of the software module quota per distribution set.")
void assignSoftwareModulesUntilQuotaIsExceeded() {
/**
* Verifies the enforcement of the software module quota per distribution set.
*/
@Test void assignSoftwareModulesUntilQuotaIsExceeded() {
// create some software modules
final int maxModules = quotaManagement.getMaxSoftwareModulesPerDistributionSet();
@@ -451,9 +464,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that an exception is thrown when trying to assign software modules to an invalidated distribution set.")
void verifyAssignSoftwareModulesToInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to assign software modules to an invalidated distribution set.
*/
@Test void verifyAssignSoftwareModulesToInvalidDistributionSet() {
final Long distributionSetId = testdataFactory.createAndInvalidateDistributionSet().getId();
final List<Long> softwareModuleIds = List.of(testdataFactory.createSoftwareModuleOs().getId());
@@ -462,9 +476,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.assignSoftwareModules(distributionSetId, softwareModuleIds));
}
@Test
@Description("Verifies that an exception is thrown when trying to unassign a software module from an invalidated distribution set.")
void verifyUnassignSoftwareModulesToInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to unassign a software module from an invalidated distribution set.
*/
@Test void verifyUnassignSoftwareModulesToInvalidDistributionSet() {
final Long distributionSetId = testdataFactory.createDistributionSet().getId();
final Long softwareModuleId = testdataFactory.createSoftwareModuleOs().getId();
distributionSetManagement.assignSoftwareModules(distributionSetId, singletonList(softwareModuleId));
@@ -476,9 +491,11 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.unassignSoftwareModule(distributionSetId, softwareModuleId));
}
/**
* Checks that metadata for a distribution set can be updated.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that metadata for a distribution set can be updated.")
void updateMetadata() {
final String knownKey = "myKnownKey";
final String knownValue = "myKnownValue";
@@ -509,9 +526,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.getMetadata(ds.getId()).get(knownKey)).isEqualTo(knownUpdateValue);
}
@Test
@Description("searches for distribution sets based on the various filter options, e.g. name, version, desc., tags.")
void searchDistributionSetsOnFilters() {
/**
* searches for distribution sets based on the various filter options, e.g. name, version, desc., tags.
*/
@Test void searchDistributionSetsOnFilters() {
DistributionSetTag dsTagA = distributionSetTagManagement
.create(entityFactory.tag().create().name("DistributionSetTag-A"));
final DistributionSetTag dsTagB = distributionSetTagManagement
@@ -574,17 +592,19 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
validateDeletedAndCompletedAndTypeAndSearchTextAndTag(dsGroup2, dsTagA, dsGroup2Prefix);
}
@Test
@Description("Simple DS load without the related data that should be loaded lazy.")
void findDistributionSetsWithoutLazy() {
/**
* Simple DS load without the related data that should be loaded lazy.
*/
@Test void findDistributionSetsWithoutLazy() {
testdataFactory.createDistributionSets(20);
assertThat(distributionSetManagement.findByCompleted(true, PAGE)).hasSize(20);
}
@Test
@Description("Locks a DS.")
void lockDistributionSet() {
/**
* Locks a DS.
*/
@Test void lockDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
assertThat(
distributionSetManagement.get(distributionSet.getId()).map(DistributionSet::isLocked).orElse(true))
@@ -599,9 +619,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.orElseThrow().forEach(module -> assertThat(module.isLocked()).isTrue());
}
@Test
@Description("Locked a DS could be hard deleted.")
void deleteUnassignedLockedDistributionSet() {
/**
* Locked a DS could be hard deleted.
*/
@Test void deleteUnassignedLockedDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
distributionSetManagement.lock(distributionSet.getId());
assertThat(
@@ -613,9 +634,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.get(distributionSet.getId())).isEmpty();
}
@Test
@Description("Locked an assigned DS could be soft deleted.")
void deleteAssignedLockedDistributionSet() {
/**
* Locked an assigned DS could be soft deleted.
*/
@Test void deleteAssignedLockedDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
distributionSetManagement.lock(distributionSet.getId());
assertThat(
@@ -630,9 +652,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.getOrElseThrowException(distributionSet.getId()).isDeleted()).isTrue();
}
@Test
@Description("Unlocks a DS.")
void unlockDistributionSet() {
/**
* Unlocks a DS.
*/
@Test void unlockDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
distributionSetManagement.lock(distributionSet.getId());
assertThat(
@@ -650,9 +673,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.orElseThrow().forEach(module -> assertThat(module.isLocked()).isTrue());
}
@Test
@Description("Software modules of a locked DS can't be modified. Expected behaviour is to throw an exception and to do not modify them.")
void lockDistributionSetApplied() {
/**
* Software modules of a locked DS can't be modified. Expected behaviour is to throw an exception and to do not modify them.
*/
@Test void lockDistributionSetApplied() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
final int softwareModuleCount = distributionSet.getModules().size();
assertThat(softwareModuleCount).isNotZero();
@@ -679,9 +703,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.hasSize(softwareModuleCount);
}
@Test
@Description("Test implicit locks for a DS and skip tags.")
void isImplicitLockApplicableForDistributionSet() {
/**
* Test implicit locks for a DS and skip tags.
*/
@Test void isImplicitLockApplicableForDistributionSet() {
final JpaDistributionSetManagement distributionSetManagement = (JpaDistributionSetManagement) this.distributionSetManagement;
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-non-skip");
// assert that implicit lock is applicable for non skip tags
@@ -706,9 +731,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Locks an incomplete DS. Expected behaviour is to throw an exception and to do not lock it.")
void lockIncompleteDistributionSetFails() {
/**
* Locks an incomplete DS. Expected behaviour is to throw an exception and to do not lock it.
*/
@Test void lockIncompleteDistributionSetFails() {
final long incompleteDistributionSetId = testdataFactory.createIncompleteDistributionSet().getId();
assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("Locking an incomplete distribution set should throw an exception")
@@ -718,9 +744,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isFalse();
}
@Test
@Description("Deletes a DS that is no in use. Expected behaviour is a hard delete on the database.")
void deleteUnassignedDistributionSet() {
/**
* Deletes a DS that is no in use. Expected behaviour is a hard delete on the database.
*/
@Test void deleteUnassignedDistributionSet() {
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds-1");
testdataFactory.createDistributionSet("ds-2");
@@ -732,27 +759,30 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.findByCompleted(true, PAGE)).hasSize(1);
}
@Test
@Description("Deletes an invalid distribution set")
void deleteInvalidDistributionSet() {
/**
* Deletes an invalid distribution set
*/
@Test void deleteInvalidDistributionSet() {
final DistributionSet set = testdataFactory.createAndInvalidateDistributionSet();
assertThat(distributionSetRepository.findById(set.getId())).isNotEmpty();
distributionSetManagement.delete(set.getId());
assertThat(distributionSetRepository.findById(set.getId())).isEmpty();
}
@Test
@Description("Deletes an incomplete distribution set")
void deleteIncompleteDistributionSet() {
/**
* Deletes an incomplete distribution set
*/
@Test void deleteIncompleteDistributionSet() {
final DistributionSet set = testdataFactory.createIncompleteDistributionSet();
assertThat(distributionSetRepository.findById(set.getId())).isNotEmpty();
distributionSetManagement.delete(set.getId());
assertThat(distributionSetRepository.findById(set.getId())).isEmpty();
}
@Test
@Description("Queries and loads the metadata related to a given distribution set.")
void getMetadata() {
/**
* Queries and loads the metadata related to a given distribution set.
*/
@Test void getMetadata() {
// create a DS
final DistributionSet ds1 = testdataFactory.createDistributionSet("testDs1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("testDs2");
@@ -769,9 +799,11 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.getMetadata(ds2.getId())).hasSize(quotaManagement.getMaxMetaDataEntriesPerDistributionSet() - 1);
}
/**
* Deletes a DS that is in use by either target assignment or rollout. Expected behaviour is a soft delete on the database, i.e. only marked as
* deleted, kept as reference but unavailable for future use..
*/
@Test
@Description("Deletes a DS that is in use by either target assignment or rollout. Expected behaviour is a soft delete on the database, i.e. only marked as "
+ "deleted, kept as reference but unavailable for future use..")
void deleteAssignedDistributionSet() {
testdataFactory.createDistributionSet("ds-1");
testdataFactory.createDistributionSet("ds-2");
@@ -797,9 +829,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.count()).isEqualTo(2);
}
@Test
@Description("Verify that the find all by ids contains the entities which are looking for")
@ExpectEvents({
/**
* Verify that the find all by ids contains the entities which are looking for
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 12),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 36) })
void verifyFindDistributionSetAllById() {
@@ -819,9 +852,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(collect).containsAll(searchIds);
}
@Test
@Description("Verify that an exception is thrown when trying to get an invalid distribution set")
void verifyGetValid() {
/**
* Verify that an exception is thrown when trying to get an invalid distribution set
*/
@Test void verifyGetValid() {
final Long distributionSetId = testdataFactory.createAndInvalidateDistributionSet().getId();
assertThatExceptionOfType(InvalidDistributionSetException.class)
@@ -832,18 +866,20 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.getValidAndComplete(distributionSetId));
}
@Test
@Description("Verify that an exception is thrown when trying to get an incomplete distribution set")
void verifyGetValidAndComplete() {
/**
* Verify that an exception is thrown when trying to get an incomplete distribution set
*/
@Test void verifyGetValidAndComplete() {
final Long distributionSetId = testdataFactory.createIncompleteDistributionSet().getId();
assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("Incomplete distributionSet should throw an exception")
.isThrownBy(() -> distributionSetManagement.getValidAndComplete(distributionSetId));
}
@Test
@Description("Verify that an exception is thrown when trying to create or update metadata for an invalid distribution set.")
void createMetadataForInvalidDistributionSet() {
/**
* Verify that an exception is thrown when trying to create or update metadata for an invalid distribution set.
*/
@Test void createMetadataForInvalidDistributionSet() {
final String knownKey1 = "myKnownKey1";
final String knownKey2 = "myKnownKey2";
final String knownValue = "myKnownValue";
@@ -866,9 +902,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.updateMetadata(dsId, knownKey1, knownUpdateValue));
}
@Test
@Description("Get the Rollouts count by status statistics for a specific Distribution Set")
void getRolloutsCountStatisticsForDistributionSet() {
/**
* Get the Rollouts count by status statistics for a specific Distribution Set
*/
@Test void getRolloutsCountStatisticsForDistributionSet() {
DistributionSet ds1 = testdataFactory.createDistributionSet("DS1");
DistributionSet ds2 = testdataFactory.createDistributionSet("DS2");
DistributionSet ds3 = testdataFactory.createDistributionSet("DS3");
@@ -895,9 +932,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
value.getStatus()));
}
@Test
@Description("Get the Rollouts count by status statistics for a specific Distribution Set")
void getActionsCountStatisticsForDistributionSet() {
/**
* Get the Rollouts count by status statistics for a specific Distribution Set
*/
@Test void getActionsCountStatisticsForDistributionSet() {
final DistributionSet ds = testdataFactory.createDistributionSet("DS");
final DistributionSet ds2 = testdataFactory.createDistributionSet("DS2");
testdataFactory.createTargets("targets", 4);
@@ -914,9 +952,10 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
statistics.forEach(statistic -> assertThat(Status.valueOf(String.valueOf(statistic.getName()))).isEqualTo(Status.RUNNING));
}
@Test
@Description("Get the Rollouts count by status statistics for a specific Distribution Set")
void getAutoAssignmentsCountStatisticsForDistributionSet() {
/**
* Get the Rollouts count by status statistics for a specific Distribution Set
*/
@Test void getAutoAssignmentsCountStatisticsForDistributionSet() {
DistributionSet ds = testdataFactory.createDistributionSet("DS");
DistributionSet ds2 = testdataFactory.createDistributionSet("DS2");
testdataFactory.createTargets("targets", 4);
@@ -930,7 +969,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.countAutoAssignmentsForDistributionSet(ds2.getId())).isNull();
}
@Step
private void createAndUpdateDistributionSetWithInvalidDescription(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate =
entityFactory.distributionSet().create().name("a").version("a").description(randomString(513));
@@ -956,7 +994,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.update(distributionSetUpdate2));
}
@Step
private void createAndUpdateDistributionSetWithInvalidName(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create()
.version("a").name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
@@ -991,7 +1028,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.update(distributionSetUpdate3));
}
@Step
private void createAndUpdateDistributionSetWithInvalidVersion(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create()
.name("a").version(randomString(NamedVersionedEntity.VERSION_MAX_SIZE + 1));
@@ -1016,13 +1052,11 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.update(distributionSetUpdate2));
}
@Step
private void validateFindAll(final List<DistributionSet> expectedDistributionsets) {
assertThatFilterContainsOnlyGivenDistributionSets(DistributionSetFilter.builder(), expectedDistributionsets);
}
@Step
private void validateDeleted(final DistributionSet deletedDistributionSet, final int notDeletedSize) {
assertThatFilterContainsOnlyGivenDistributionSets(DistributionSetFilter.builder().isDeleted(Boolean.TRUE),
@@ -1032,7 +1066,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
DistributionSetFilter.builder().isDeleted(Boolean.FALSE), notDeletedSize, deletedDistributionSet);
}
@Step
private void validateCompleted(final DistributionSet dsIncomplete, final int completedSize) {
assertThatFilterHasSizeAndDoesNotContainDistributionSet(
@@ -1042,7 +1075,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
DistributionSetFilter.builder().isComplete(Boolean.FALSE), singletonList(dsIncomplete));
}
@Step
private void validateType(final DistributionSetType newType, final DistributionSet dsNewType,
final int standardDsTypeSize) {
assertThatFilterContainsOnlyGivenDistributionSets(DistributionSetFilter.builder().typeId(newType.getId()),
@@ -1051,7 +1083,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
DistributionSetFilter.builder().typeId(standardDsType.getId()), standardDsTypeSize, dsNewType);
}
@Step
private void validateSearchText(final List<DistributionSet> allDistributionSets, final String dsNamePrefix) {
final List<DistributionSet> withTestNamePrefix = allDistributionSets.stream()
@@ -1093,7 +1124,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
allDistributionSets);
}
@Step
private void validateTags(final DistributionSetTag dsTagA, final DistributionSetTag dsTagB,
final DistributionSetTag dsTagC, final List<DistributionSet> dsWithTagA,
final List<DistributionSet> dsWithTagB) {
@@ -1116,7 +1146,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
DistributionSetFilter.builder().tagNames(singletonList(dsTagC.getName())));
}
@Step
private void validateDeletedAndCompleted(final List<DistributionSet> completedStandardType,
final DistributionSet dsNewType, final DistributionSet dsDeleted) {
@@ -1134,7 +1163,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
DistributionSetFilter.builder().isComplete(Boolean.FALSE).isDeleted(Boolean.TRUE));
}
@Step
private void validateDeletedAndCompletedAndType(final List<DistributionSet> deletedAndCompletedAndStandardType,
final DistributionSet dsDeleted, final DistributionSetType newType, final DistributionSet dsNewType) {
assertThatFilterContainsOnlyGivenDistributionSets(DistributionSetFilter.builder().isDeleted(Boolean.FALSE)
@@ -1148,7 +1176,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
singletonList(dsNewType));
}
@Step
private void validateDeletedAndCompletedAndTypeAndSearchText(
final List<DistributionSet> completedAndStandardTypeAndSearchText, final DistributionSetType newType,
final String text) {
@@ -1168,7 +1195,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
.searchText(text).isComplete(Boolean.TRUE).isDeleted(Boolean.FALSE));
}
@Step
private void validateDeletedAndCompletedAndTypeAndSearchText(
final List<DistributionSet> completedAndNotDeletedStandardTypeAndFilterString,
final DistributionSet dsDeleted, final DistributionSet dsInComplete, final DistributionSet dsNewType,
@@ -1200,7 +1226,6 @@ class DistributionSetManagementTest extends AbstractJpaIntegrationTest {
singletonList(dsNewType));
}
@Step
private void validateDeletedAndCompletedAndTypeAndSearchTextAndTag(
final List<DistributionSet> completedAndStandartTypeAndSearchTextAndTagA, final DistributionSetTag dsTagA,
final String text) {

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Random;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.eclipse.hawkbit.repository.builder.TagCreate;
@@ -24,8 +21,10 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Pageable;
@Feature("SecurityTests - DistributionSetTagManagement")
@Story("SecurityTests DistributionSetTagManagement")
/**
* Feature: SecurityTests - DistributionSetTagManagement<br/>
* Story: SecurityTests DistributionSetTagManagement
*/
class DistributionSetTagManagementSecurityTest extends AbstractRepositoryManagementSecurityTest<DistributionSetTag, TagCreate, TagUpdate> {
@Override
@@ -43,22 +42,25 @@ class DistributionSetTagManagementSecurityTest extends AbstractRepositoryManagem
return entityFactory.tag().update(1L).name("tag");
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNameWitPermissionWorks() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNameWitPermissionWorks() {
assertPermissions(() -> distributionSetTagManagement.findByName("tagName"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByDistributionSetPermissionsCheck() {
assertPermissions(() -> distributionSetTagManagement.findByDistributionSet(1L, Pageable.unpaged()),
List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteDistributionSetTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteDistributionSetTagPermissionsCheck() {
assertPermissions(() -> {
distributionSetTagManagement.delete("tagName");
return null;

View File

@@ -21,10 +21,6 @@ import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.DistributionSetTagManagement;
import org.eclipse.hawkbit.repository.builder.TagCreate;
import org.eclipse.hawkbit.repository.builder.TagUpdate;
@@ -45,24 +41,28 @@ import org.springframework.data.domain.Pageable;
/**
* {@link DistributionSetTagManagement} tests.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: DistributionSet Tag Management
*/
@Feature("Component Tests - Repository")
@Story("DistributionSet Tag Management")
class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
private static final Random RND = new Random();
@Test
@Description("Verifies that management get access reacts as specified on calls for non existing entities by means of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
/**
* Verifies that management get access reacts as specified on calls for non existing entities by means of Optional not present.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(distributionSetTagManagement.findByName(NOT_EXIST_ID)).isNotPresent();
assertThat(distributionSetTagManagement.get(NOT_EXIST_IDL)).isNotPresent();
}
/**
* Verifies that management queries react as specified on calls for non existing entities by means of throwing
* EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities by means of throwing " +
"EntityNotFoundException.")
@ExpectEvents({
@Expect(type = DistributionSetTagUpdatedEvent.class, count = 0),
@Expect(type = TargetTagUpdatedEvent.class, count = 0) })
@@ -74,9 +74,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
"DistributionSetTag");
}
@Test
@Description("Full DS tag lifecycle tested. Create tags, assign them to sets and delete the tags.")
void createAndAssignAndDeleteDistributionSetTags() {
/**
* Full DS tag lifecycle tested. Create tags, assign them to sets and delete the tags.
*/
@Test void createAndAssignAndDeleteDistributionSetTags() {
final Collection<DistributionSet> dsAs = testdataFactory.createDistributionSets("DS-A", 20);
final Collection<DistributionSet> dsBs = testdataFactory.createDistributionSets("DS-B", 10);
final Collection<DistributionSet> dsCs = testdataFactory.createDistributionSets("DS-C", 25);
@@ -136,9 +137,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
Stream.of(dsCs, dsACs, dsBCs, dsABCs));
}
@Test
@Description("Verifies assign/unassign.")
void assignAndUnassignDistributionSetTags() {
/**
* Verifies assign/unassign.
*/
@Test void assignAndUnassignDistributionSetTags() {
final Collection<DistributionSet> groupA = testdataFactory.createDistributionSets(20);
final Collection<DistributionSet> groupB = testdataFactory.createDistributionSets("unassigned", 20);
@@ -176,9 +178,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetManagement.findByTag(tag.getId(), Pageable.unpaged()).getContent()).isEmpty();
}
@Test
@Description("Verifies that tagging of set containing missing DS throws meaningful and correct exception.")
void failOnMissingDs() {
/**
* Verifies that tagging of set containing missing DS throws meaningful and correct exception.
*/
@Test void failOnMissingDs() {
final Collection<Long> group = testdataFactory.createDistributionSets(5).stream().map(DistributionSet::getId).toList();
final DistributionSetTag tag = distributionSetTagManagement.create(entityFactory.tag().create().name("tag1").description("tagdesc1"));
final List<Long> missing = new ArrayList<>();
@@ -204,9 +207,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Ensures that a created tag is persisted in the repository as defined.")
void createDistributionSetTag() {
/**
* Ensures that a created tag is persisted in the repository as defined.
*/
@Test void createDistributionSetTag() {
final Tag tag = distributionSetTagManagement
.create(entityFactory.tag().create().name("kai1").description("kai2").colour("colour"));
@@ -218,9 +222,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo("colour");
}
@Test
@Description("Ensures that a deleted tag is removed from the repository as defined.")
void deleteDistributionSetTag() {
/**
* Ensures that a deleted tag is removed from the repository as defined.
*/
@Test void deleteDistributionSetTag() {
// create test data
final Iterable<DistributionSetTag> tags = createDsSetsWithTags();
final DistributionSetTag toDelete = tags.iterator().next();
@@ -245,9 +250,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).")
void failedDuplicateDsTagNameException() {
/**
* Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).
*/
@Test void failedDuplicateDsTagNameException() {
final TagCreate tag = entityFactory.tag().create().name("A");
distributionSetTagManagement.create(tag);
@@ -255,9 +261,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetTagManagement.create(tag));
}
@Test
@Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).")
void failedDuplicateDsTagNameExceptionAfterUpdate() {
/**
* Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).
*/
@Test void failedDuplicateDsTagNameExceptionAfterUpdate() {
distributionSetTagManagement.create(entityFactory.tag().create().name("A"));
final DistributionSetTag tag = distributionSetTagManagement.create(entityFactory.tag().create().name("B"));
@@ -266,9 +273,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetTagManagement.update(tagUpdate));
}
@Test
@Description("Tests the name update of a target tag.")
void updateDistributionSetTag() {
/**
* Tests the name update of a target tag.
*/
@Test void updateDistributionSetTag() {
// create test data
final List<DistributionSetTag> tags = createDsSetsWithTags();
// change data
@@ -282,9 +290,10 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
.as("Wrong ds tag found").isEqualTo("test123");
}
@Test
@Description("Ensures that all tags are retrieved through repository.")
void findDistributionSetTagsAll() {
/**
* Ensures that all tags are retrieved through repository.
*/
@Test void findDistributionSetTagsAll() {
final List<DistributionSetTag> tags = createDsSetsWithTags();
// test
@@ -293,14 +302,14 @@ class DistributionSetTagManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags").hasSize(20);
}
@Test
@Description("Ensures that a created tags are persisted in the repository as defined.")
void createDistributionSetTags() {
/**
* Ensures that a created tags are persisted in the repository as defined.
*/
@Test void createDistributionSetTags() {
final List<DistributionSetTag> tags = createDsSetsWithTags();
assertThat(distributionSetTagRepository.findAll()).as("Wrong size of tags created").hasSize(tags.size());
}
@Step
private void verifyExpectedFilteredDistributionSets(final DistributionSetFilter.DistributionSetFilterBuilder distributionSetFilterBuilder,
final Stream<Collection<DistributionSet>> expectedFilteredDistributionSets) {
final Collection<Long> retrievedFilteredDsIds = distributionSetManagement

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Random;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetTypeCreate;
@@ -23,8 +20,10 @@ import org.eclipse.hawkbit.repository.jpa.AbstractRepositoryManagementSecurityTe
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - DistributionSetTypeManagement")
@Story("SecurityTests DistributionSetTypeManagement")
/**
* Feature: SecurityTests - DistributionSetTypeManagement<br/>
* Story: SecurityTests DistributionSetTypeManagement
*/
class DistributionSetTypeManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<DistributionSetType, DistributionSetTypeCreate, DistributionSetTypeUpdate> {
@@ -43,35 +42,40 @@ class DistributionSetTypeManagementSecurityTest
return entityFactory.distributionSetType().update(1L).description("description");
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByKeyPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByKeyPermissionsCheck() {
assertPermissions(() -> distributionSetTypeManagement.findByKey("key"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNamePermissionsCheck() {
assertPermissions(() -> distributionSetTypeManagement.findByName("name"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignOptionalSoftwareModuleTypesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignOptionalSoftwareModuleTypesPermissionsCheck() {
assertPermissions(() -> distributionSetTypeManagement.assignOptionalSoftwareModuleTypes(1L, List.of(1L)),
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignMandatorySoftwareModuleTypesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignMandatorySoftwareModuleTypesPermissionsCheck() {
assertPermissions(() -> distributionSetTypeManagement.assignMandatorySoftwareModuleTypes(1L, List.of(1L)),
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignSoftwareModuleTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignSoftwareModuleTypePermissionsCheck() {
assertPermissions(() -> distributionSetTypeManagement.unassignSoftwareModuleType(1L, 1L), List.of(SpPermission.UPDATE_REPOSITORY));
}
}

View File

@@ -21,10 +21,6 @@ import java.util.Set;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.builder.DistributionSetUpdate;
@@ -48,14 +44,17 @@ import org.junit.jupiter.api.Test;
/**
* {@link DistributionSetManagement} tests.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: DistributionSet Management
*/
@Feature("Component Tests - Repository")
@Story("DistributionSet Management")
class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
/**
* Verifies that management get access react as specfied on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access react as specfied on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = DistributionSetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(distributionSetTypeManagement.get(NOT_EXIST_IDL)).isNotPresent();
@@ -63,9 +62,11 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetTypeManagement.findByName(NOT_EXIST_ID)).isNotPresent();
}
/**
* Verifies that management queries react as specfied on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 0),
@Expect(type = DistributionSetTypeCreatedEvent.class, count = 1) })
@@ -93,9 +94,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
"DistributionSet");
}
@Test
@Description("Verify that a DistributionSet with invalid properties cannot be created or updated")
@ExpectEvents({
/**
* Verify that a DistributionSet with invalid properties cannot be created or updated
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = DistributionSetUpdatedEvent.class, count = 0) })
@@ -107,9 +109,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
createAndUpdateDistributionSetWithInvalidVersion(set);
}
@Test
@Description("Tests the successful module update of unused distribution set type which is in fact allowed.")
void updateUnassignedDistributionSetTypeModules() {
/**
* Tests the successful module update of unused distribution set type which is in fact allowed.
*/
@Test void updateUnassignedDistributionSetTypeModules() {
final DistributionSetType updatableType = distributionSetTypeManagement
.create(entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(distributionSetTypeManagement.findByKey("updatableType").get().getMandatoryModuleTypes()).isEmpty();
@@ -132,9 +135,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
.containsOnly(runtimeType);
}
@Test
@Description("Verifies that the quota for software module types per distribution set type is enforced as expected.")
void quotaMaxSoftwareModuleTypes() {
/**
* Verifies that the quota for software module types per distribution set type is enforced as expected.
*/
@Test void quotaMaxSoftwareModuleTypes() {
final int quota = quotaManagement.getMaxSoftwareModuleTypesPerDistributionSetType();
// create software module types
final List<Long> moduleTypeIds = new ArrayList<>();
@@ -179,9 +183,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Tests the successfull update of used distribution set type meta data which is in fact allowed.")
void updateAssignedDistributionSetTypeMetaData() {
/**
* Tests the successfull update of used distribution set type meta data which is in fact allowed.
*/
@Test void updateAssignedDistributionSetTypeMetaData() {
final DistributionSetType nonUpdatableType = createDistributionSetTypeUsedByDs();
distributionSetTypeManagement.update(
@@ -192,9 +197,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetTypeManagement.findByKey("updatableType").get().getColour()).isEqualTo("test123");
}
@Test
@Description("Tests the unsuccessful update of used distribution set type (module addition).")
void addModuleToAssignedDistributionSetTypeFails() {
/**
* Tests the unsuccessful update of used distribution set type (module addition).
*/
@Test void addModuleToAssignedDistributionSetTypeFails() {
final Long nonUpdatableTypeId = createDistributionSetTypeUsedByDs().getId();
final Set<Long> osTypeId = Set.of(osType.getId());
assertThatThrownBy(() -> distributionSetTypeManagement
@@ -202,9 +208,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the unsuccessful update of used distribution set type (module removal).")
void removeModuleToAssignedDistributionSetTypeFails() {
/**
* Tests the unsuccessful update of used distribution set type (module removal).
*/
@Test void removeModuleToAssignedDistributionSetTypeFails() {
DistributionSetType nonUpdatableType = distributionSetTypeManagement
.create(entityFactory.distributionSetType().create().key("updatableType").name("to be deleted"));
assertThat(distributionSetTypeManagement.findByKey("updatableType").get().getMandatoryModuleTypes()).isEmpty();
@@ -219,9 +226,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
.isInstanceOf(EntityReadOnlyException.class);
}
@Test
@Description("Tests the successfull deletion of unused (hard delete) distribution set types.")
void deleteUnassignedDistributionSetType() {
/**
* Tests the successfull deletion of unused (hard delete) distribution set types.
*/
@Test void deleteUnassignedDistributionSetType() {
final JpaDistributionSetType hardDelete = (JpaDistributionSetType) distributionSetTypeManagement
.create(entityFactory.distributionSetType().create().key("delete").name("to be deleted"));
@@ -231,9 +239,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetTypeRepository.findAll()).doesNotContain(hardDelete);
}
@Test
@Description("Tests the successfull deletion of used (soft delete) distribution set types.")
void deleteAssignedDistributionSetType() {
/**
* Tests the successfull deletion of used (soft delete) distribution set types.
*/
@Test void deleteAssignedDistributionSetType() {
final int existing = (int) distributionSetTypeManagement.count();
final JpaDistributionSetType toBeDeleted = (JpaDistributionSetType) distributionSetTypeManagement
.create(entityFactory.distributionSetType().create().key("softdeleted").name("to be deleted"));
@@ -251,9 +260,10 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(distributionSetTypeManagement.count()).isEqualTo(existing);
}
@Test
@Description("Verifies that when no SoftwareModules are assigned to a Distribution then the DistributionSet is not complete.")
void shouldFailWhenDistributionSetHasNoSoftwareModulesAssigned() {
/**
* Verifies that when no SoftwareModules are assigned to a Distribution then the DistributionSet is not complete.
*/
@Test void shouldFailWhenDistributionSetHasNoSoftwareModulesAssigned() {
final JpaDistributionSetType jpaDistributionSetType = (JpaDistributionSetType) distributionSetTypeManagement
.create(entityFactory.distributionSetType().create().key("newType").name("new Type"));
@@ -266,7 +276,6 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(jpaDistributionSetType.checkComplete(distributionSet)).isFalse();
}
@Step
private void createAndUpdateDistributionSetWithInvalidDescription(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create()
.name("a").version("a").description(randomString(513));
@@ -292,7 +301,6 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.update(distributionSetUpdate2));
}
@Step
private void createAndUpdateDistributionSetWithInvalidName(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create()
.version("a").name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
@@ -332,7 +340,6 @@ class DistributionSetTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> distributionSetManagement.update(distributionSetUpdate3));
}
@Step
private void createAndUpdateDistributionSetWithInvalidVersion(final DistributionSet set) {
final DistributionSetCreate distributionSetCreate = entityFactory.distributionSet().create()
.name("a").version(randomString(NamedVersionedEntity.VERSION_MAX_SIZE + 1));

View File

@@ -13,9 +13,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.TimeUnit;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.RepositoryProperties;
import org.eclipse.hawkbit.repository.event.remote.TargetPollEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
@@ -27,8 +24,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestPropertySource;
@Feature("Component Tests - Repository")
@Story("Controller Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Controller Management
*/
@TestPropertySource(locations = "classpath:/jpa-test.properties", properties = {
"hawkbit.server.repository.eagerPollPersistence=false",
"hawkbit.server.repository.pollPersistenceFlushTime=1000" })
@@ -37,9 +36,10 @@ class LazyControllerManagementTest extends AbstractJpaIntegrationTest {
@Autowired
private RepositoryProperties repositoryProperties;
@Test
@Description("Verifies that lazy target poll update is executed as specified.")
@ExpectEvents({
/**
* Verifies that lazy target poll update is executed as specified.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 2) })
void lazyFindOrRegisterTargetIfItDoesNotExist() throws InterruptedException {

View File

@@ -11,77 +11,86 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - RolloutGroupManagement")
@Story("SecurityTests RolloutGroupManagement")
/**
* Feature: SecurityTests - RolloutGroupManagement<br/>
* Story: SecurityTests RolloutGroupManagement
*/
class RolloutGroupManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.get(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.getWithDetailedStatus(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRolloutPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRolloutPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.countByRollout(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countTargetsOfRolloutsGroupPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countTargetsOfRolloutsGroupPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.countTargetsOfRolloutsGroup(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRolloutPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRolloutPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRollout(1L, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRolloutAndRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRolloutAndRsqlPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRolloutAndRsql(1L, "name==*", PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findTargetsOfRolloutGroupPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findTargetsOfRolloutGroupPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findTargetsOfRolloutGroup(1L, PAGE),
List.of(SpPermission.READ_ROLLOUT, SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findTargetsOfRolloutGroupByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findTargetsOfRolloutGroupByRsqlPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findTargetsOfRolloutGroupByRsql(1L, "name==*", PAGE),
List.of(SpPermission.READ_ROLLOUT, SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRolloutAndRsqlWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRolloutAndRsqlWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRolloutAndRsqlWithDetailedStatus(1L, "name==*", PAGE),
List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRolloutWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRolloutWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRolloutWithDetailedStatus(1L, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
}

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.event.remote.RolloutDeletedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
@@ -31,22 +28,28 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository")
@Story("Rollout Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Rollout Management
*/
class RolloutGroupManagementTest extends AbstractJpaIntegrationTest {
/**
* Verifies that management get access reacts as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access reacts as specified on calls for non existing entities by means " +
"of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(rolloutGroupManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(rolloutGroupManagement.getWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities " +
" by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = RolloutCreatedEvent.class, count = 1),
@Expect(type = RolloutUpdatedEvent.class, count = 1),
@@ -70,9 +73,10 @@ class RolloutGroupManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> rolloutGroupManagement.findTargetsOfRolloutGroupByRsql(NOT_EXIST_IDL, "name==*", PAGE), "RolloutGroup");
}
@Test
@Description("Tests the rollout group status mapping.")
void testRolloutGroupStatusConvert() {
/**
* Tests the rollout group status mapping.
*/
@Test void testRolloutGroupStatusConvert() {
final long id = rolloutGroupRepository.findByRolloutId(
testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId(), PAGE).getContent()
.get(0).getId();

View File

@@ -14,9 +14,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.OffsetBasedPageRequest;
import org.eclipse.hawkbit.repository.builder.DynamicRolloutGroupTemplate;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -35,9 +32,10 @@ import org.springframework.test.context.TestPropertySource;
/**
* Junit tests for RolloutManagement.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Rollout Management (Flow)
*/
@Feature("Component Tests - Repository")
@Story("Rollout Management (Flow)")
@TestPropertySource(properties = { "hawkbit.server.repository.dynamicRolloutsMinInvolvePeriodMS=-1" })
class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
@@ -46,9 +44,10 @@ class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
this.approvalStrategy.setApprovalNeeded(false);
}
@Test
@Description("Verifies a simple rollout flow")
void rolloutFlow() {
/**
* Verifies a simple rollout flow
*/
@Test void rolloutFlow() {
final String rolloutName = "rollout-std";
final int amountGroups = 5; // static only
final String targetPrefix = "controller-rollout-std-";
@@ -86,9 +85,10 @@ class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
assertAndGetRunning(rollout, 1); // keep running
}
@Test
@Description("Verifies a simple dynamic rollout flow")
void dynamicRolloutFlow() {
/**
* Verifies a simple dynamic rollout flow
*/
@Test void dynamicRolloutFlow() {
final String rolloutName = "dynamic-rollout-std";
final int amountGroups = 2; // static only
final String targetPrefix = "controller-dynamic-rollout-std-";
@@ -200,9 +200,10 @@ class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
assertThat(refresh(dynamic2).getStatus()).isEqualTo(RolloutGroupStatus.FINISHED);
}
@Test
@Description("Verifies a simple dynamic rollout flow with a dynamic group template")
void dynamicRolloutTemplateFlow() {
/**
* Verifies a simple dynamic rollout flow with a dynamic group template
*/
@Test void dynamicRolloutTemplateFlow() {
final String rolloutName = "dynamic-template-rollout-std";
final int amountGroups = 3; // static only
final String targetPrefix = "controller-template-dynamic-rollout-std-";
@@ -298,9 +299,10 @@ class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
assertGroup(dynamic2, true, RolloutGroupStatus.RUNNING, 4); // assign the target created when paused
}
@Test
@Description("Verifies a simple pure (no static groups) dynamic rollout flow with a dynamic group template")
void dynamicRolloutPureFlow() {
/**
* Verifies a simple pure (no static groups) dynamic rollout flow with a dynamic group template
*/
@Test void dynamicRolloutPureFlow() {
final String rolloutName = "pure-dynamic-rollout-std";
final String targetPrefix = "controller-pure-dynamic-rollout-std-";
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName);
@@ -379,9 +381,10 @@ class RolloutManagementFlowTest extends AbstractJpaIntegrationTest {
assertGroup(dynamic2, true, RolloutGroupStatus.RUNNING, 4); // assign the target created when paused
}
@Test
@Description("Verifies a simple rollout flow")
void rollout0ThresholdFlow() {
/**
* Verifies a simple rollout flow
*/
@Test void rollout0ThresholdFlow() {
final String rolloutName = "rollout-std-0threshold";
final int amountGroups = 5; // static only
final String targetPrefix = "controller-rollout-std-0threshold-";

View File

@@ -13,9 +13,6 @@ import java.util.List;
import jakarta.validation.ConstraintDeclarationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
@@ -29,63 +26,73 @@ import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - RolloutManagement")
@Story("SecurityTests RolloutManagement")
/**
* Feature: SecurityTests - RolloutManagement<br/>
* Story: SecurityTests RolloutManagement
*/
class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> rolloutManagement.get(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNamePermissionsCheck() {
assertPermissions(() -> rolloutManagement.getByName("name"), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutManagement.getWithDetailedStatus(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void approveOrDenyPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void approveOrDenyPermissionsCheck() {
assertPermissions(() -> rolloutManagement.approveOrDeny(1L, Rollout.ApprovalDecision.APPROVED), List.of(SpPermission.APPROVE_ROLLOUT));
assertPermissions(() -> rolloutManagement.approveOrDeny(1L, Rollout.ApprovalDecision.APPROVED, "comment"),
List.of(SpPermission.APPROVE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void pauseRolloutPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void pauseRolloutPermissionsCheck() {
assertPermissions(() -> {
rolloutManagement.pauseRollout(1L);
return null;
}, List.of(SpPermission.HANDLE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void resumeRolloutPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void resumeRolloutPermissionsCheck() {
assertPermissions(() -> {
rolloutManagement.resumeRollout(1L);
return null;
}, List.of(SpPermission.HANDLE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findActiveRolloutsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findActiveRolloutsPermissionsCheck() {
assertPermissions(() -> rolloutManagement.findActiveRollouts(), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void cancelRolloutsForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void cancelRolloutsForDistributionSetPermissionsCheck() {
final DistributionSetTypeCreate key = entityFactory.distributionSetType().create().name("type").key("type");
distributionSetTypeManagement.create(key);
final DistributionSetCreate dsCreate = entityFactory.distributionSet().create().name("name").version("1.0.0").type("type");
@@ -96,21 +103,24 @@ class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest {
}, List.of(SpPermission.UPDATE_ROLLOUT, SpPermission.READ_REPOSITORY, SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countPermissionsCheck() {
assertPermissions(() -> rolloutManagement.count(), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByDistributionSetIdAndRolloutIsStoppablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByDistributionSetIdAndRolloutIsStoppablePermissionsCheck() {
assertPermissions(() -> rolloutManagement.countByDistributionSetIdAndRolloutIsStoppable(1L), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionsCheck() {
assertPermissions(() -> rolloutManagement.create(entityFactory.rollout().create().distributionSetId(1L), 1, false,
new RolloutGroupConditionBuilder().withDefaults().build()), List.of(SpPermission.CREATE_ROLLOUT, SpPermission.READ_REPOSITORY));
assertPermissions(() -> rolloutManagement.create(entityFactory.rollout().create().distributionSetId(1L), 1, false,
@@ -123,64 +133,73 @@ class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest {
List.of(SpPermission.CREATE_ROLLOUT, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllPermissionsCheck() {
assertPermissions(() -> rolloutManagement.findAll(false, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlPermissionsCheck() {
assertPermissions(() -> rolloutManagement.findByRsql("id==1", false, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutManagement.findAllWithDetailedStatus(false, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlWithDetailedStatusPermissionsCheck() {
assertPermissions(() ->
rolloutManagement.findByRsqlWithDetailedStatus("name==*", false, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void startPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void startPermissionsCheck() {
assertPermissions(() -> rolloutManagement.start(1L), List.of(SpPermission.HANDLE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionsCheck() {
assertPermissions(() -> rolloutManagement.update(entityFactory.rollout().update(1L)), List.of(SpPermission.UPDATE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionsCheck() {
assertPermissions(() -> {
rolloutManagement.delete(1L);
return null;
}, List.of(SpPermission.DELETE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void triggerNextGroupPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void triggerNextGroupPermissionsCheck() {
assertPermissions(() -> {
rolloutManagement.triggerNextGroup(1L);
return null;
}, List.of(SpPermission.UPDATE_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
// @WithUser(principal = "user", authorities = { SpPermission.CREATE_TARGET, SpPermission.CREATE_ROLLOUT, SpPermission.READ_ROLLOUT,
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test// @WithUser(principal = "user", authorities = { SpPermission.CREATE_TARGET, SpPermission.CREATE_ROLLOUT, SpPermission.READ_ROLLOUT,
// SpPermission.READ_TARGET })
void validateTargetsInGroupsPermissionsCheck() {
try {
@@ -196,17 +215,19 @@ class RolloutManagementSecurityTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
@WithUser(principal = "user", authorities = { SpPermission.READ_ROLLOUT })
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test @WithUser(principal = "user", authorities = { SpPermission.READ_ROLLOUT })
void findByRolloutAndRsqlWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRolloutAndRsqlWithDetailedStatus(1L, "name==*", PAGE),
List.of(SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRolloutWithDetailedStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRolloutWithDetailedStatusPermissionsCheck() {
assertPermissions(() -> rolloutGroupManagement.findByRolloutWithDetailedStatus(1L, PAGE), List.of(SpPermission.READ_ROLLOUT));
}
}

View File

@@ -28,10 +28,6 @@ import java.util.stream.Stream;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
import org.awaitility.Awaitility;
@@ -103,17 +99,19 @@ import org.springframework.data.domain.Sort.Direction;
/**
* Junit tests for RolloutManagement.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Rollout Management
*/
@Feature("Component Tests - Repository")
@Story("Rollout Management")
class RolloutManagementTest extends AbstractJpaIntegrationTest {
/**
* Tests static assignment aspects of the dynamic group assignment filters.
*/
@Test
@Description("Dynamic group doesn't override newer static group assignments")
void dynamicGroupDoesntOverrideItsOrNewerStaticGroups() {
/**
* Dynamic group doesn't override newer static group assignments
*/
@Test void dynamicGroupDoesntOverrideItsOrNewerStaticGroups() {
final int amountGroups = 1; // static only
final String targetPrefix = "controller-dynamic-rollout-";
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds");
@@ -175,9 +173,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
this.approvalStrategy.setApprovalNeeded(false);
}
@Test
@Description("Verifies that a running action with distribution-set (A) is not canceled by a rollout which tries to also assign a distribution-set (A)")
void rolloutShouldNotCancelRunningActionWithTheSameDistributionSet() {
/**
* Verifies that a running action with distribution-set (A) is not canceled by a rollout which tries to also assign a distribution-set (A)
*/
@Test void rolloutShouldNotCancelRunningActionWithTheSameDistributionSet() {
// manually assign distribution set to target
final String knownControllerId = "controller12345";
final DistributionSet knownDistributionSet = testdataFactory.createDistributionSet();
@@ -209,9 +208,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rolloutCreatedAction.getStatus()).isEqualTo(Status.FINISHED);
}
/**
* Verifies that action states are correctly initialized after starting a rollout with different options in regard to the confirmation.
*/
@ParameterizedTest
@MethodSource("simpleRolloutsPossibilities")
@Description("Verifies that action states are correctly initialized after starting a rollout with different options in regard to the confirmation.")
void runRolloutWithConfirmationFlagAndCoonfirmationFlowOptions(final boolean confirmationFlowActive,
final boolean confirmationRequired, final Status expectedStatus) {
// manually assign distribution set to target
@@ -238,9 +239,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(actionsByKnownTarget.get(0).getStatus()).isEqualTo(expectedStatus);
}
@Test
@Description("Verifies that a running action is auto canceled by a rollout which assigns another distribution-set.")
void rolloutAssignsNewDistributionSetAndAutoCloseActiveActions() {
/**
* Verifies that a running action is auto canceled by a rollout which assigns another distribution-set.
*/
@Test void rolloutAssignsNewDistributionSetAndAutoCloseActiveActions() {
tenantConfigurationManagement
.addOrUpdateConfiguration(TenantConfigurationKey.REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED, true);
@@ -281,9 +283,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
/**
* Verifies that management get access reacts as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access reacts as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(rolloutManagement.get(NOT_EXIST_IDL)).isNotPresent();
@@ -291,9 +295,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rolloutManagement.getWithDetailedStatus(NOT_EXIST_IDL)).isNotPresent();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = RolloutDeletedEvent.class, count = 0),
@Expect(type = RolloutGroupCreatedEvent.class, count = 5),
@@ -319,9 +325,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> rolloutManagement.triggerNextGroup(NOT_EXIST_IDL), "Rollout");
}
@Test
@Description("Verifying that the rollout is created correctly, executing the filter and split up the targets in the correct group size.")
void creatingRolloutIsCorrectPersisted() {
/**
* Verifying that the rollout is created correctly, executing the filter and split up the targets in the correct group size.
*/
@Test void creatingRolloutIsCorrectPersisted() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -338,9 +345,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rolloutGroups).hasSize(amountGroups);
}
@Test
@Description("Verifying that when the rollout is started the actions for all targets in the rollout is created and the state of the first group is running as well as the corresponding actions")
void startRolloutSetFirstGroupAndActionsInRunningStateAndOthersInScheduleState() {
/**
* Verifying that when the rollout is started the actions for all targets in the rollout is created and the state of the first group is running as well as the corresponding actions
*/
@Test void startRolloutSetFirstGroupAndActionsInRunningStateAndOthersInScheduleState() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -374,9 +382,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.hasSize(amountTargetsForRollout - (amountTargetsForRollout / amountGroups));
}
@Test
@Description("Verifying that a finish condition of a group is hit the next group of the rollout is also started")
void checkRunningRolloutsDoesNotStartNextGroupIfFinishConditionIsNotHit() {
/**
* Verifying that a finish condition of a group is hit the next group of the rollout is also started
*/
@Test void checkRunningRolloutsDoesNotStartNextGroupIfFinishConditionIsNotHit() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -416,9 +425,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(RolloutGroupStatus.SCHEDULED));
}
@Test
@Description("Verifying that next group is started when targets of the group have been deleted.")
void checkRunningRolloutsStartsNextGroupIfTargetsDeleted() {
/**
* Verifying that next group is started when targets of the group have been deleted.
*/
@Test void checkRunningRolloutsStartsNextGroupIfTargetsDeleted() {
final int amountTargetsForRollout = 15;
final int amountOtherTargets = 0;
final int amountGroups = 3;
@@ -436,9 +446,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
verifyRolloutAndAllGroupsAreFinished(createdRollout);
}
@Test
@Description("Verifying that the error handling action of a group is executed to pause the current rollout")
void checkErrorHitOfGroupCallsErrorActionToPauseTheRollout() {
/**
* Verifying that the error handling action of a group is executed to pause the current rollout
*/
@Test void checkErrorHitOfGroupCallsErrorActionToPauseTheRollout() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -480,9 +491,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
scheduleGroups.forEach(group -> assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.SCHEDULED));
}
@Test
@Description("Verifying a paused rollout in case of error action hit can be resumed again")
void errorActionPausesRolloutAndRolloutGetsResumedStartsNextScheduledGroup() {
/**
* Verifying a paused rollout in case of error action hit can be resumed again
*/
@Test void errorActionPausesRolloutAndRolloutGetsResumedStartsNextScheduledGroup() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -532,9 +544,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(resumedGroups.get(0).getStatus()).isEqualTo(RolloutGroupStatus.RUNNING);
}
@Test
@Description("Verifying that the rollout is starting group after group and gets finished at the end")
void rolloutStartsGroupAfterGroupAndGetsFinished() {
/**
* Verifying that the rollout is starting group after group and gets finished at the end
*/
@Test void rolloutStartsGroupAfterGroupAndGetsFinished() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 15;
final int amountGroups = 5;
@@ -570,9 +583,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(findRolloutById.getStatus()).isEqualTo(RolloutStatus.FINISHED);
}
@Test
@Description("Verify that the targets have the right status during the rollout.")
void countCorrectStatusForEachTargetDuringRollout() {
/**
* Verify that the targets have the right status during the rollout.
*/
@Test void countCorrectStatusForEachTargetDuringRollout() {
final int amountTargetsForRollout = 8;
final int amountOtherTargets = 15;
@@ -634,9 +648,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify that the targets have the right status during a download_only rollout.")
void countCorrectStatusForEachTargetDuringDownloadOnlyRollout() {
/**
* Verify that the targets have the right status during a download_only rollout.
*/
@Test void countCorrectStatusForEachTargetDuringDownloadOnlyRollout() {
final int amountTargetsForRollout = 8;
final int amountOtherTargets = 15;
@@ -702,9 +717,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify that the targets have the right status during the rollout when an error emerges.")
void countCorrectStatusForEachTargetDuringRolloutWithError() {
/**
* Verify that the targets have the right status during the rollout when an error emerges.
*/
@Test void countCorrectStatusForEachTargetDuringRolloutWithError() {
final int amountTargetsForRollout = 8;
final int amountOtherTargets = 15;
@@ -740,9 +756,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(createdRollout.getId(), validationMap);
}
@Test
@Description("Verify that the targets have the right status during the rollout when receiving the status of rollout groups.")
void countCorrectStatusForEachTargetGroupDuringRollout() {
/**
* Verify that the targets have the right status during the rollout when receiving the status of rollout groups.
*/
@Test void countCorrectStatusForEachTargetGroupDuringRollout() {
final int amountTargetsForRollout = 9;
final int amountOtherTargets = 15;
@@ -782,9 +799,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify that target actions of rollout get canceled when a manuel distribution sets assignment is done.")
void targetsOfRolloutGetsManuelDsAssignment() {
/**
* Verify that target actions of rollout get canceled when a manuel distribution sets assignment is done.
*/
@Test void targetsOfRolloutGetsManuelDsAssignment() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 0;
@@ -826,9 +844,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(createdRollout.getId(), validationMap);
}
@Test
@Description("Verify that target actions of a rollout get cancelled when another rollout with same targets gets started.")
void targetsOfRolloutGetDistributionSetAssignmentByOtherRollout() {
/**
* Verify that target actions of a rollout get cancelled when another rollout with same targets gets started.
*/
@Test void targetsOfRolloutGetDistributionSetAssignmentByOtherRollout() {
final int amountTargetsForRollout = 15;
final int amountOtherTargets = 5;
@@ -868,9 +887,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(rolloutOne.getId(), expectedTargetCountStatus);
}
@Test
@Description("Verify that error status of DistributionSet installation during rollout can get rerun with second rollout so that all targets have some DistributionSet installed at the end.")
void startSecondRolloutAfterFirstRolloutEndsWithErrors() {
/**
* Verify that error status of DistributionSet installation during rollout can get rerun with second rollout so that all targets have some DistributionSet installed at the end.
*/
@Test void startSecondRolloutAfterFirstRolloutEndsWithErrors() {
final int amountTargetsForRollout = 15;
final int amountOtherTargets = 0;
@@ -927,9 +947,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.forEach(d -> assertThat(d).contains(distributionSet));
}
@Test
@Description("Verify that the rollout moves to the next group when the success condition was achieved and the error condition was not exceeded.")
void successConditionAchievedAndErrorConditionNotExceeded() {
/**
* Verify that the rollout moves to the next group when the success condition was achieved and the error condition was not exceeded.
*/
@Test void successConditionAchievedAndErrorConditionNotExceeded() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 0;
@@ -953,9 +974,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify that the rollout does not move to the next group when the success condition was not achieved.")
void successConditionNotAchieved() {
/**
* Verify that the rollout does not move to the next group when the success condition was not achieved.
*/
@Test void successConditionNotAchieved() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 0;
@@ -979,9 +1001,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutGroupActionStatus(rolloutGruops.get(1), expectedTargetCountStatus);
}
@Test
@Description("Verify that the rollout pauses when the error condition was exceeded.")
void errorConditionExceeded() {
/**
* Verify that the rollout pauses when the error condition was exceeded.
*/
@Test void errorConditionExceeded() {
final int amountTargetsForRollout = 10;
final int amountOtherTargets = 0;
@@ -1001,9 +1024,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rolloutOne.getStatus()).isEqualTo(RolloutStatus.PAUSED);
}
@Test
@Description("Verify that all rollouts are return with expected target statuses.")
void findAllRolloutsWithDetailedStatus() {
/**
* Verify that all rollouts are return with expected target statuses.
*/
@Test void findAllRolloutsWithDetailedStatus() {
final int amountTargetsForRollout = 12;
final int amountGroups = 2;
@@ -1077,9 +1101,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(rolloutList.get(3).getId(), expectedTargetCountStatus);
}
@Test
@Description("Verify the count of existing rollouts.")
void rightCountForAllRollouts() {
/**
* Verify the count of existing rollouts.
*/
@Test void rightCountForAllRollouts() {
final int amountTargetsForRollout = 6;
final int amountGroups = 2;
@@ -1093,9 +1118,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(count).isEqualTo(10L);
}
@Test
@Description("Verify that the filtering and sorting ascending for rollout is working correctly.")
void findRolloutByFilters() {
/**
* Verify that the filtering and sorting ascending for rollout is working correctly.
*/
@Test void findRolloutByFilters() {
final int amountTargetsForRollout = 6;
final int amountGroups = 2;
final String successCondition = "50";
@@ -1120,9 +1146,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Verify that the expected rollout is found by name.")
void findRolloutByName() {
/**
* Verify that the expected rollout is found by name.
*/
@Test void findRolloutByName() {
final int amountTargetsForRollout = 12;
final int amountGroups = 2;
@@ -1137,9 +1164,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify that the percent count is acting like aspected when targets move to the status finished or error.")
void getFinishedPercentForRunningGroup() {
/**
* Verify that the percent count is acting like aspected when targets move to the status finished or error.
*/
@Test void getFinishedPercentForRunningGroup() {
final int amountTargetsForRollout = 10;
final int amountGroups = 2;
@@ -1183,9 +1211,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(percent).isEqualTo(80);
}
@Test
@Description("Verify that the expected targets are returned for the rollout groups.")
void findRolloutGroupTargetsWithRsqlParam() {
/**
* Verify that the expected targets are returned for the rollout groups.
*/
@Test void findRolloutGroupTargetsWithRsqlParam() {
final int amountTargetsForRollout = 15;
final int amountGroups = 3;
@@ -1234,9 +1263,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify the creation of a Rollout without targets throws an Exception.")
void createRolloutNotMatchingTargets() {
/**
* Verify the creation of a Rollout without targets throws an Exception.
*/
@Test void createRolloutNotMatchingTargets() {
final int amountGroups = 5;
final String successCondition = "50";
final String errorCondition = "80";
@@ -1251,9 +1281,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify the creation of a Rollout with the same name throws an Exception.")
void createDuplicateRollout() {
/**
* Verify the creation of a Rollout with the same name throws an Exception.
*/
@Test void createDuplicateRollout() {
final int amountGroups = 5;
final int amountTargetsForRollout = 10;
final String successCondition = "50";
@@ -1272,9 +1303,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.withMessageContaining("already exists in database");
}
@Test
@Description("Verify the creation and the start of a Rollout with more groups than targets.")
void createAndStartRolloutWithEmptyGroups() {
/**
* Verify the creation and the start of a Rollout with more groups than targets.
*/
@Test void createAndStartRolloutWithEmptyGroups() {
final int amountTargetsForRollout = 3;
final int amountGroups = 5;
final String successCondition = "50";
@@ -1317,9 +1349,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(myRolloutId, expectedTargetCountStatus);
}
@Test
@Description("Verify the creation and the start of a rollout.")
void createAndStartRollout() {
/**
* Verify the creation and the start of a rollout.
*/
@Test void createAndStartRollout() {
final int amountTargetsForRollout = 50;
final int amountGroups = 5;
@@ -1355,9 +1388,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
validateRolloutActionStatus(myRolloutId, expectedTargetCountStatus);
}
@Test
@Description("Verify the creation and the start of a rollout.")
void createScheduledRollout() throws Exception {
/**
* Verify the creation and the start of a rollout.
*/
@Test void createScheduledRollout() throws Exception {
final String rolloutName = "scheduledRolloutTest";
testdataFactory.createTargets(50, rolloutName + "-", rolloutName);
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dsFor" + rolloutName);
@@ -1414,9 +1448,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.errorAction(RolloutGroupErrorAction.PAUSE, null).build(), null);
}
@Test
@Description("Verify that a rollout cannot be created if the 'max targets per rollout group' quota is violated.")
void createRolloutFailsIfQuotaGroupQuotaIsViolated() {
/**
* Verify that a rollout cannot be created if the 'max targets per rollout group' quota is violated.
*/
@Test void createRolloutFailsIfQuotaGroupQuotaIsViolated() {
final int maxTargets = quotaManagement.getMaxTargetsPerRolloutGroup();
@@ -1441,9 +1476,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> rolloutManagement.create(rollout, amountGroups, false, conditions));
}
@Test
@Description("Verify that a rollout cannot be created based on group definitions if the 'max targets per rollout group' quota is violated for one of the groups.")
void createRolloutWithGroupDefinitionsFailsIfQuotaGroupQuotaIsViolated() {
/**
* Verify that a rollout cannot be created based on group definitions if the 'max targets per rollout group' quota is violated for one of the groups.
*/
@Test void createRolloutWithGroupDefinitionsFailsIfQuotaGroupQuotaIsViolated() {
final int maxTargets = quotaManagement.getMaxTargetsPerRolloutGroup();
final int amountTargetsForRollout = maxTargets * 2 + 2;
@@ -1487,9 +1523,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
Arrays.asList(group5, group6, group7), conditions)).isNotNull();
}
@Test
@Description("Verify the update of a rollout")
void updateRollout() {
/**
* Verify the update of a rollout
*/
@Test void updateRollout() {
final int amountTargetsForRollout = 50;
final int amountGroups = 5;
final String successCondition = "50";
@@ -1515,9 +1552,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(myRollout.getDescription()).isEqualTo("newDesc");
}
@Test
@Description("Verify the creation of a rollout with a groups definition.")
void createRolloutWithGroupDefinition() throws Exception {
/**
* Verify the creation of a rollout with a groups definition.
*/
@Test void createRolloutWithGroupDefinition() throws Exception {
final String rolloutName = "rolloutTest3";
final int amountTargetsInGroup1 = 10;
@@ -1575,9 +1613,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify rollout execution with advanced group definition and confirmation flow active.")
void createRolloutWithGroupDefinitionAndConfirmationFlowActive() {
/**
* Verify rollout execution with advanced group definition and confirmation flow active.
*/
@Test void createRolloutWithGroupDefinitionAndConfirmationFlowActive() {
final String rolloutName = "rolloutTest4";
final int amountTargetsInGroup1 = 10;
@@ -1651,9 +1690,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify rollout creation fails if group definition does not address all targets")
void createRolloutWithGroupsNotMatchingTargets() {
/**
* Verify rollout creation fails if group definition does not address all targets
*/
@Test void createRolloutWithGroupsNotMatchingTargets() {
final String rolloutName = "rolloutTest4";
final int amountTargetsForRollout = 500;
final int percentTargetsInGroup1 = 20;
@@ -1672,9 +1712,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify rollout creation fails if group definition specifies illegal target percentage")
void createRolloutWithIllegalPercentage() {
/**
* Verify rollout creation fails if group definition specifies illegal target percentage
*/
@Test void createRolloutWithIllegalPercentage() {
final String rolloutName = "rolloutTest6";
final int amountTargetsForRollout = 10;
final int percentTargetsInGroup1 = 101;
@@ -1693,9 +1734,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verify rollout creation fails if the 'max rollout groups per rollout' quota is violated.")
void createRolloutWithIllegalAmountOfGroups() {
/**
* Verify rollout creation fails if the 'max rollout groups per rollout' quota is violated.
*/
@Test void createRolloutWithIllegalAmountOfGroups() {
final String rolloutName = "rolloutTest5";
final int targets = 10;
final int maxGroups = quotaManagement.getMaxRolloutGroupsPerRollout();
@@ -1708,9 +1750,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.withMessageContaining("not be greater than " + maxGroups);
}
@Test
@Description("Verify the start of a Rollout does not work during creation phase.")
void createAndStartRolloutDuringCreationFails() {
/**
* Verify the start of a Rollout does not work during creation phase.
*/
@Test void createAndStartRolloutDuringCreationFails() {
final int amountTargetsForRollout = 3;
final int amountGroups = 5;
final String successCondition = "50";
@@ -1737,9 +1780,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.withMessageContaining("can only be started in state ready");
}
/**
* Creating a rollout with approval role or approval engine disabled results in the rollout being in
* READY state.
*/
@Test
@Description("Creating a rollout with approval role or approval engine disabled results in the rollout being in "
+ "READY state.")
void createdRolloutWithApprovalRoleOrApprovalDisabledTransitionsToReadyState() {
approvalStrategy.setApprovalNeeded(false);
final String successCondition = "50";
@@ -1750,9 +1795,11 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rollout.getStatus()).isEqualTo(Rollout.RolloutStatus.READY);
}
/**
* Creating a rollout without approve role and approval enabled leads to transition to
* WAITING_FOR_APPROVAL state.
*/
@Test
@Description("Creating a rollout without approve role and approval enabled leads to transition to "
+ "WAITING_FOR_APPROVAL state.")
void createdRolloutWithoutApprovalRoleTransitionsToWaitingForApprovalState() {
approvalStrategy.setApprovalNeeded(true);
final String successCondition = "50";
@@ -1763,9 +1810,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rollout.getStatus()).isEqualTo(Rollout.RolloutStatus.WAITING_FOR_APPROVAL);
}
@Test
@Description("Approving a rollout leads to transition to READY state.")
void approvedRolloutTransitionsToReadyState() {
/**
* Approving a rollout leads to transition to READY state.
*/
@Test void approvedRolloutTransitionsToReadyState() {
approvalStrategy.setApprovalNeeded(true);
final String successCondition = "50";
final String errorCondition = "80";
@@ -1778,9 +1826,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(resultingRollout.getStatus()).isEqualTo(Rollout.RolloutStatus.READY);
}
@Test
@Description("Denying approval for a rollout leads to transition to APPROVAL_DENIED state.")
void deniedRolloutTransitionsToApprovalDeniedState() {
/**
* Denying approval for a rollout leads to transition to APPROVAL_DENIED state.
*/
@Test void deniedRolloutTransitionsToApprovalDeniedState() {
approvalStrategy.setApprovalNeeded(true);
final String successCondition = "50";
final String errorCondition = "80";
@@ -1890,9 +1939,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.getNumberOfElements()).isEqualTo(2);
}
@Test
@Description("Verifies that returned result considers provided sort parameter.")
void findAllRolloutsConsidersSorting() {
/**
* Verifies that returned result considers provided sort parameter.
*/
@Test void findAllRolloutsConsidersSorting() {
final String randomString = randomString(5);
final DistributionSet testDs = testdataFactory.createDistributionSet(randomString + "-testDs");
testdataFactory.createTargets(10, randomString + "-testTarget-");
@@ -1929,9 +1979,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rolloutsOrderedByName).containsSubsequence(List.of(rolloutRunning, rolloutReady));
}
@Test
@Description("Creating a rollout without weight value when multi assignment in enabled.")
void weightNotRequiredInMultiAssignmentMode() {
/**
* Creating a rollout without weight value when multi assignment in enabled.
*/
@Test void weightNotRequiredInMultiAssignmentMode() {
enableMultiAssignments();
final Rollout rollout = testdataFactory.createSimpleTestRolloutWithTargetsAndDistributionSet(10, 10, 2, "50",
"80",
@@ -1939,18 +1990,20 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(rollout).isNotNull();
}
@Test
@Description("Creating a rollout with a weight causes an error when multi assignment in disabled.")
void weightAllowedWhenMultiAssignmentModeNotEnabled() {
/**
* Creating a rollout with a weight causes an error when multi assignment in disabled.
*/
@Test void weightAllowedWhenMultiAssignmentModeNotEnabled() {
assertThat(
testdataFactory.createSimpleTestRolloutWithTargetsAndDistributionSet(
10, 10, 2, "50", "80", ActionType.FORCED, 66))
.isNotNull();
}
@Test
@Description("Weight is validated and saved to the Rollout.")
void weightValidatedAndSaved() {
/**
* Weight is validated and saved to the Rollout.
*/
@Test void weightValidatedAndSaved() {
final String targetPrefix = UUID.randomUUID().toString();
testdataFactory.createTargets(4, targetPrefix);
enableMultiAssignments();
@@ -1976,9 +2029,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(Action.WEIGHT_MIN);
}
@Test
@Description("A Rollout with weight creates actions with weights")
void actionsWithWeightAreCreated() {
/**
* A Rollout with weight creates actions with weights
*/
@Test void actionsWithWeightAreCreated() {
final int amountOfTargets = 5;
final int weight = 99;
enableMultiAssignments();
@@ -1993,9 +2047,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.allMatch(action -> action.getWeight().get() == weight);
}
@Test
@Description("Rollout can be created without weight in single assignment and be started in multi assignment")
void createInSingleStartInMultiassignMode() {
/**
* Rollout can be created without weight in single assignment and be started in multi assignment
*/
@Test void createInSingleStartInMultiassignMode() {
final int amountOfTargets = 5;
final Long rolloutId = testdataFactory.createSimpleTestRolloutWithTargetsAndDistributionSet(amountOfTargets, 2,
amountOfTargets,
@@ -2009,9 +2064,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(actions).hasSize(5).allMatch(action -> action.getWeight().isPresent());
}
@Test
@Description("Verifies that an exception is thrown when trying to create a rollout with an invalidated distribution set.")
void createRolloutWithInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to create a rollout with an invalidated distribution set.
*/
@Test void createRolloutWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
assertThatExceptionOfType(InvalidDistributionSetException.class)
@@ -2020,9 +2076,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
"desc", 2, "name==*", distributionSet, "50", "80"));
}
@Test
@Description("Verifies that an exception is thrown when trying to create a rollout with an incomplete distribution set.")
void createRolloutWithIncompleteDistributionSet() {
/**
* Verifies that an exception is thrown when trying to create a rollout with an incomplete distribution set.
*/
@Test void createRolloutWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
assertThatExceptionOfType(IncompleteDistributionSetException.class)
@@ -2031,9 +2088,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
"desc", 2, "name==*", distributionSet, "50", "80"));
}
@Test
@Description("Verify the that only compatible targets are part of a Rollout.")
void createAndStartRolloutWithTargetTypes() {
/**
* Verify the that only compatible targets are part of a Rollout.
*/
@Test void createAndStartRolloutWithTargetTypes() {
final String rolloutName = "rolloutTestCompatibility";
final DistributionSet testDs = testdataFactory.createDistributionSet("test-ds");
@@ -2074,9 +2132,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
.doesNotContainAnyElementsOf(incompatibleTargets);
}
@Test
@Description("Verifying that next group is started on manual trigger next group.")
void checkRunningRolloutsManualTriggerNextGroup() {
/**
* Verifying that next group is started on manual trigger next group.
*/
@Test void checkRunningRolloutsManualTriggerNextGroup() {
final int amountTargetsForRollout = 15;
final int amountOtherTargets = 0;
final int amountGroups = 3;
@@ -2116,9 +2175,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
verifyRolloutAndAllGroupsAreFinished(createdRollout);
}
@Test
@Description("Tests the rollout status mapping.")
void testRolloutStatusConvert() {
/**
* Tests the rollout status mapping.
*/
@Test void testRolloutStatusConvert() {
final long id = testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId();
for (final RolloutStatus status : RolloutStatus.values()) {
final JpaRollout rollout = ((JpaRollout) rolloutManagement.get(id).orElseThrow());
@@ -2128,9 +2188,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Tests the rollout action type mapping.")
void testActionTypeConvert() {
/**
* Tests the rollout action type mapping.
*/
@Test void testActionTypeConvert() {
final long id = testdataFactory.createAndStartRollout(1, 0, 1, "100", "80").getId();
for (final ActionType actionType : ActionType.values()) {
final JpaRollout rollout = ((JpaRollout) rolloutManagement.get(id).orElseThrow());
@@ -2140,9 +2201,10 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Trigger next rollout group if rollout is in wrong state")
void triggeringNextGroupRolloutWrongState() {
/**
* Trigger next rollout group if rollout is in wrong state
*/
@Test void triggeringNextGroupRolloutWrongState() {
final int amountTargetsForRollout = 15;
final int amountOtherTargets = 0;
@@ -2203,7 +2265,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
return map;
}
@Step("Finish three actions of the rollout group and delete two targets")
private void finishActionAndDeleteTargetsOfFirstRunningGroup(final Rollout createdRollout) {
// finish group one by finishing targets and deleting targets
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
@@ -2216,7 +2277,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
Arrays.asList(runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
@Step("Check the status of the rollout groups, second group should be in running status")
private void checkSecondGroupStatusIsRunning(final Rollout createdRollout) {
rolloutHandler.handleAll();
final List<RolloutGroup> runningRolloutGroups = rolloutGroupManagement
@@ -2227,7 +2287,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
assertThat(runningRolloutGroups.get(2).getStatus()).isEqualTo(RolloutGroupStatus.SCHEDULED);
}
@Step("Finish one action of the rollout group and delete four targets")
private void finishActionAndDeleteTargetsOfSecondRunningGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.RUNNING);
@@ -2239,7 +2298,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
}
@Step("Delete all targets of the rollout group")
private void deleteAllTargetsFromThirdGroup(final Rollout createdRollout) {
final Slice<JpaAction> runningActionsSlice = actionRepository.findByRolloutIdAndStatus(PAGE,
createdRollout.getId(), Status.SCHEDULED);
@@ -2249,7 +2307,6 @@ class RolloutManagementTest extends AbstractJpaIntegrationTest {
runningActions.get(3).getTarget().getId(), runningActions.get(4).getTarget().getId()));
}
@Step("Check the status of the rollout groups and the rollout")
private void verifyRolloutAndAllGroupsAreFinished(final Rollout createdRollout) {
rolloutHandler.handleAll();
final List<RolloutGroup> runningRolloutGroups = rolloutGroupManagement

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleCreate;
@@ -22,8 +19,10 @@ import org.eclipse.hawkbit.repository.jpa.AbstractRepositoryManagementSecurityTe
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - SoftwareManagement")
@Story("SecurityTests SoftwareManagement")
/**
* Feature: SecurityTests - SoftwareManagement<br/>
* Story: SecurityTests SoftwareManagement
*/
class SoftwareManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<SoftwareModule, SoftwareModuleCreate, SoftwareModuleUpdate> {
@@ -42,9 +41,10 @@ class SoftwareManagementSecurityTest
return entityFactory.softwareModule().update(1L).locked(true);
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createMetaDataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createMetaDataPermissionsCheck() {
assertPermissions(
() -> softwareModuleManagement.updateMetadata(entityFactory.softwareModuleMetadata().create(1L).key("key").value("value")),
List.of(SpPermission.UPDATE_REPOSITORY));
@@ -55,30 +55,34 @@ class SoftwareManagementSecurityTest
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteMetaDataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteMetaDataPermissionsCheck() {
assertPermissions(() -> {
softwareModuleManagement.deleteMetadata(1L, "key");
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByAssignedToPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByAssignedToPermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.findByAssignedTo(1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByAssignedToPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByAssignedToPermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.countByAssignedTo(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTextAndTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTextAndTypePermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.findByTextAndType("text", 1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@@ -88,60 +92,68 @@ class SoftwareManagementSecurityTest
List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getMetaDataBySoftwareModuleIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getMetaDataBySoftwareModuleIdPermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.getMetadata(1L, "key"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findMetaDataBySoftwareModuleIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findMetaDataBySoftwareModuleIdPermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.getMetadata(1L), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findMetaDataBySoftwareModuleIdAndTargetVisiblePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findMetaDataBySoftwareModuleIdAndTargetVisiblePermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.findMetaDataBySoftwareModuleIdAndTargetVisible(1L, PAGE),
List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTypePermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.findByType(1L, PAGE), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void lockPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void lockPermissionsCheck() {
assertPermissions(() -> {
softwareModuleManagement.lock(1L);
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unlockPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unlockPermissionsCheck() {
assertPermissions(() -> {
softwareModuleManagement.unlock(1L);
return null;
}, List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updateMetaDataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updateMetaDataPermissionsCheck() {
assertPermissions(
() -> softwareModuleManagement.updateMetadata(entityFactory.softwareModuleMetadata().update(1L, "key").value("value")),
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findMetaDataBySoftwareModuleIdsAndTargetVisiblePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findMetaDataBySoftwareModuleIdsAndTargetVisiblePermissionsCheck() {
assertPermissions(() -> softwareModuleManagement.findMetaDataBySoftwareModuleIdsAndTargetVisible(List.of(1L)),
List.of(SpPermission.READ_REPOSITORY));
}

View File

@@ -22,9 +22,6 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
@@ -55,15 +52,19 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("Software Module Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Software Module Management
*/
class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
private static final PageRequest PAGE_REQUEST_100 = PageRequest.of(0, 100);
/**
* Verifies that management get access reacts as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access reacts as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
void nonExistingEntityAccessReturnsNotPresent() {
final SoftwareModule module = testdataFactory.createSoftwareModuleApp();
@@ -77,9 +78,11 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> softwareModuleManagement.getMetadata(module.getId(), NOT_EXIST_ID));
}
/**
* Verifies that management queries react as specfied on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 1) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final SoftwareModule module = testdataFactory.createSoftwareModuleApp();
@@ -122,9 +125,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> softwareModuleManagement.update(entityFactory.softwareModule().update(NOT_EXIST_IDL)), "SoftwareModule");
}
@Test
@Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.")
void updateNothingResultsInUnchangedRepository() {
/**
* Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.
*/
@Test void updateNothingResultsInUnchangedRepository() {
final SoftwareModule ah = testdataFactory.createSoftwareModuleOs();
final SoftwareModule updated = softwareModuleManagement
@@ -135,9 +139,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(ah.getOptLockRevision());
}
@Test
@Description("Calling update for changed fields results in change in the repository.")
void updateSoftwareModuleFieldsToNewValue() {
/**
* Calling update for changed fields results in change in the repository.
*/
@Test void updateSoftwareModuleFieldsToNewValue() {
final SoftwareModule ah = testdataFactory.createSoftwareModuleOs();
final SoftwareModule updated = softwareModuleManagement
@@ -150,18 +155,20 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(updated.getVendor()).as("Updated vendor is").isEqualTo("changed");
}
@Test
@Description("Create Software Module call fails when called for existing entity.")
void createModuleCallFailsForExistingModule() {
/**
* Create Software Module call fails when called for existing entity.
*/
@Test void createModuleCallFailsForExistingModule() {
testdataFactory.createSoftwareModuleOs();
assertThatExceptionOfType(EntityAlreadyExistsException.class)
.as("Should not have worked as module already exists.")
.isThrownBy(() -> testdataFactory.createSoftwareModuleOs());
}
@Test
@Description("searched for software modules based on the various filter options, e.g. name,desc,type, version.")
void findSoftwareModuleByFilters() {
/**
* searched for software modules based on the various filter options, e.g. name,desc,type, version.
*/
@Test void findSoftwareModuleByFilters() {
final SoftwareModule ah = softwareModuleManagement
.create(entityFactory.softwareModule().create().type(appType).name("agent-hub").version("1.0.1"));
final SoftwareModule jvm = softwareModuleManagement
@@ -201,9 +208,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(ah);
}
@Test
@Description("Searches for software modules based on a list of IDs.")
void findSoftwareModulesById() {
/**
* Searches for software modules based on a list of IDs.
*/
@Test void findSoftwareModulesById() {
final List<Long> modules = Arrays.asList(testdataFactory.createSoftwareModuleOs().getId(),
testdataFactory.createSoftwareModuleApp().getId(), 624355263L);
@@ -211,9 +219,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleManagement.get(modules)).hasSize(2);
}
@Test
@Description("Searches for software modules by type.")
void findSoftwareModulesByType() {
/**
* Searches for software modules by type.
*/
@Test void findSoftwareModulesByType() {
// found in test
final SoftwareModule one = testdataFactory.createSoftwareModuleOs("one");
final SoftwareModule two = testdataFactory.createSoftwareModuleOs("two");
@@ -226,9 +235,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.contains(two, one);
}
@Test
@Description("Counts all software modules in the repsitory that are not marked as deleted.")
void countSoftwareModulesAll() {
/**
* Counts all software modules in the repsitory that are not marked as deleted.
*/
@Test void countSoftwareModulesAll() {
// found in test
testdataFactory.createSoftwareModuleOs("one");
testdataFactory.createSoftwareModuleOs("two");
@@ -240,9 +250,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(2);
}
@Test
@Description("Deletes an artifact, which is not assigned to a Distribution Set")
void hardDeleteOfNotAssignedArtifact() {
/**
* Deletes an artifact, which is not assigned to a Distribution Set
*/
@Test void hardDeleteOfNotAssignedArtifact() {
// [STEP1]: Create SoftwareModuleX with Artifacts
final SoftwareModule unassignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2);
@@ -266,9 +277,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactRepository.findById(artifact2.getId())).isNotPresent();
}
@Test
@Description("Deletes an artifact, which is assigned to a DistributionSet")
void softDeleteOfAssignedArtifact() {
/**
* Deletes an artifact, which is assigned to a DistributionSet
*/
@Test void softDeleteOfAssignedArtifact() {
// [STEP1]: Create SoftwareModuleX with ArtifactX
SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2);
@@ -298,9 +310,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactRepository.findById(artifact2.getId())).isNotNull();
}
@Test
@Description("Delete an artifact, which has been assigned to a rolled out DistributionSet in the past")
void softDeleteOfHistoricalAssignedArtifact() {
/**
* Delete an artifact, which has been assigned to a rolled out DistributionSet in the past
*/
@Test void softDeleteOfHistoricalAssignedArtifact() {
// Init target
final Target target = testdataFactory.createTarget();
@@ -338,9 +351,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactRepository.findById(artifact2.getId())).isNotNull();
}
@Test
@Description("Delete an software module with an artifact, which is also used by another software module.")
void deleteSoftwareModulesWithSharedArtifact() {
/**
* Delete an software module with an artifact, which is also used by another software module.
*/
@Test void deleteSoftwareModulesWithSharedArtifact() {
// Init artifact binary data, target and DistributionSets
final int artifactSize = 1024;
@@ -384,9 +398,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Delete two assigned softwaremodules which share an artifact.")
void deleteMultipleSoftwareModulesWhichShareAnArtifact() {
/**
* Delete two assigned softwaremodules which share an artifact.
*/
@Test void deleteMultipleSoftwareModulesWhichShareAnArtifact() {
// Init artifact binary data, target and DistributionSets
final int artifactSize = 1024;
final byte[] source = randomBytes(artifactSize);
@@ -443,9 +458,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(artifactRepository.findById(artifactY.getId())).isNotNull();
}
@Test
@Description("Verifies that all undeleted software modules are found in the repository.")
void countSoftwareModuleTypesAll() {
/**
* Verifies that all undeleted software modules are found in the repository.
*/
@Test void countSoftwareModuleTypesAll() {
testdataFactory.createSoftwareModuleOs();
// one soft deleted
@@ -457,9 +473,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleRepository.count()).as("Number of all modules").isEqualTo(2);
}
@Test
@Description("Verifies that software modules are returned that are assigned to given DS.")
void findSoftwareModuleByAssignedTo() {
/**
* Verifies that software modules are returned that are assigned to given DS.
*/
@Test void findSoftwareModuleByAssignedTo() {
// test modules
final SoftwareModule one = testdataFactory.createSoftwareModuleOs();
testdataFactory.createSoftwareModuleOs("notassigned");
@@ -474,9 +491,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.as("Found this number of modules").hasSize(2);
}
@Test
@Description("Checks that metadata for a software module can be created.")
void createSoftwareModuleMetadata() {
/**
* Checks that metadata for a software module can be created.
*/
@Test void createSoftwareModuleMetadata() {
final String knownKey1 = "myKnownKey1";
final String knownValue1 = "myKnownValue1";
@@ -516,9 +534,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
});
}
@Test
@Description("Verifies the enforcement of the metadata quota per software module.")
void createSoftwareModuleMetadataUntilQuotaIsExceeded() {
/**
* Verifies the enforcement of the metadata quota per software module.
*/
@Test void createSoftwareModuleMetadataUntilQuotaIsExceeded() {
// add meta data one by one
final SoftwareModule module = testdataFactory.createSoftwareModuleApp("m1");
@@ -563,9 +582,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Checks that metadata for a software module cannot be created for an existing key.")
void createSoftwareModuleMetadataFailsIfKeyExists() {
/**
* Checks that metadata for a software module cannot be created for an existing key.
*/
@Test void createSoftwareModuleMetadataFailsIfKeyExists() {
final String knownKey1 = "myKnownKey1";
final String knownValue1 = "myKnownValue1";
@@ -591,9 +611,11 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.withMessageContaining("Metadata").withMessageContaining(knownKey2);
}
/**
* Checks that metadata for a software module can be updated.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that metadata for a software module can be updated.")
void updateSoftwareModuleMetadata() {
final String knownKey = "myKnownKey";
final String knownValue = "myKnownValue";
@@ -632,9 +654,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(((JpaSoftwareModuleMetadata) updated).getSoftwareModule().getId()).isEqualTo(ah.getId());
}
@Test
@Description("Verifies that existing metadata can be deleted.")
void deleteSoftwareModuleMetadata() {
/**
* Verifies that existing metadata can be deleted.
*/
@Test void deleteSoftwareModuleMetadata() {
final String knownKey1 = "myKnownKey1";
final String knownValue1 = "myKnownValue1";
@@ -654,9 +677,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleManagement.getMetadata(swModule.getId())).as("Metadata elements are").isEmpty();
}
@Test
@Description("Verifies that non existing metadata find results in exception.")
void findSoftwareModuleMetadataFailsIfEntryDoesNotExist() {
/**
* Verifies that non existing metadata find results in exception.
*/
@Test void findSoftwareModuleMetadataFailsIfEntryDoesNotExist() {
final String knownKey1 = "myKnownKey1";
final String knownValue1 = "myKnownValue1";
@@ -669,9 +693,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> softwareModuleManagement.getMetadata(ah.getId(), "doesnotexist"));
}
@Test
@Description("Queries and loads the metadata related to a given software module.")
void findAllSoftwareModuleMetadataBySwId() {
/**
* Queries and loads the metadata related to a given software module.
*/
@Test void findAllSoftwareModuleMetadataBySwId() {
final SoftwareModule sw1 = testdataFactory.createSoftwareModuleApp();
final int metadataCountSw1 = 8;
@@ -703,9 +728,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
assertThat(metadataSw2V.getTotalElements()).isZero();
}
@Test
@Description("Locks a SM.")
void lockSoftwareModule() {
/**
* Locks a SM.
*/
@Test void lockSoftwareModule() {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1");
assertThat(
softwareModuleManagement.get(softwareModule.getId()).map(SoftwareModule::isLocked).orElse(true))
@@ -716,9 +742,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isTrue();
}
@Test
@Description("Unlocks a SM.")
void unlockSoftwareModule() {
/**
* Unlocks a SM.
*/
@Test void unlockSoftwareModule() {
final SoftwareModule softwareModule = testdataFactory.createSoftwareModule("sm-1");
softwareModuleManagement.lock(softwareModule.getId());
assertThat(
@@ -730,9 +757,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isFalse();
}
@Test
@Description("Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.")
void lockSoftwareModuleApplied() {
/**
* Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.
*/
@Test void lockSoftwareModuleApplied() {
final Long softwareModuleId = testdataFactory.createSoftwareModule("sm-1").getId();
artifactManagement.create(
new ArtifactUpload(new ByteArrayInputStream(new byte[] { 1 }), softwareModuleId, "artifact1", false, 1));
@@ -765,9 +793,10 @@ class SoftwareModuleManagementTest extends AbstractJpaIntegrationTest {
.isPresent();
}
@Test
@Description("Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.")
void lockedContainingDistributionSetApplied() {
/**
* Artifacts of a locked SM can't be modified. Expected behaviour is to throw an exception and to do not modify them.
*/
@Test void lockedContainingDistributionSetApplied() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet("ds-1");
final List<SoftwareModule> modules = distributionSet.getModules().stream().toList();
assertThat(modules).hasSizeGreaterThan(1);

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Random;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.RepositoryManagement;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
@@ -23,8 +20,10 @@ import org.eclipse.hawkbit.repository.jpa.AbstractRepositoryManagementSecurityTe
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - SoftwareModuleTypeManagement")
@Story("SecurityTests SoftwareModuleTypeManagement")
/**
* Feature: SecurityTests - SoftwareModuleTypeManagement<br/>
* Story: SecurityTests SoftwareModuleTypeManagement
*/
class SoftwareModuleTypeManagementSecurityTest
extends AbstractRepositoryManagementSecurityTest<SoftwareModuleType, SoftwareModuleTypeCreate, SoftwareModuleTypeUpdate> {
@@ -43,15 +42,17 @@ class SoftwareModuleTypeManagementSecurityTest
return entityFactory.softwareModuleType().update(1L).description("description");
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByKeyPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByKeyPermissionsCheck() {
assertPermissions(() -> softwareModuleTypeManagement.findByKey("key"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNamePermissionsCheck() {
assertPermissions(() -> softwareModuleTypeManagement.findByName("name"), List.of(SpPermission.READ_REPOSITORY));
}

View File

@@ -17,9 +17,6 @@ import java.util.List;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleTypeCreate;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
@@ -30,13 +27,17 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository")
@Story("Software Module Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Software Module Management
*/
class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
/**
* Verifies that management get access reacts as specfied on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
@@ -45,9 +46,11 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleTypeManagement.findByName(NOT_EXIST_ID)).isNotPresent();
}
/**
* Verifies that management queries react as specfied on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = SoftwareModuleCreatedEvent.class, count = 0) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
verifyThrownExceptionBy(() -> softwareModuleTypeManagement.delete(NOT_EXIST_IDL), "SoftwareModuleType");
@@ -57,9 +60,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
"SoftwareModuleType");
}
@Test
@Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.")
void updateNothingResultsInUnchangedRepositoryForType() {
/**
* Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.
*/
@Test void updateNothingResultsInUnchangedRepositoryForType() {
final SoftwareModuleType created = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
@@ -71,9 +75,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(created.getOptLockRevision());
}
@Test
@Description("Calling update for changed fields results in change in the repository.")
void updateSoftwareModuleTypeFieldsToNewValue() {
/**
* Calling update for changed fields results in change in the repository.
*/
@Test void updateSoftwareModuleTypeFieldsToNewValue() {
final SoftwareModuleType created = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test-key").name("test-name"));
@@ -86,9 +91,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(updated.getColour()).as("Updated vendor is").isEqualTo("changed");
}
@Test
@Description("Create Software Module Types call fails when called for existing entities.")
void createModuleTypesCallFailsForExistingTypes() {
/**
* Create Software Module Types call fails when called for existing entities.
*/
@Test void createModuleTypesCallFailsForExistingTypes() {
final List<SoftwareModuleTypeCreate> created = Arrays.asList(
entityFactory.softwareModuleType().create().key("test-key").name("test-name"),
entityFactory.softwareModuleType().create().key("test-key2").name("test-name2"));
@@ -98,9 +104,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> softwareModuleTypeManagement.create(created));
}
@Test
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
void deleteAssignedAndUnassignedSoftwareModuleTypes() {
/**
* Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).
*/
@Test void deleteAssignedAndUnassignedSoftwareModuleTypes() {
assertThat(softwareModuleTypeManagement.findAll(PAGE)).hasSize(3).contains(osType, runtimeType, appType);
SoftwareModuleType type = softwareModuleTypeManagement
@@ -134,9 +141,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
softwareModuleTypeRepository.findById(type.getId()).get());
}
@Test
@Description("Checks that software module typeis found based on given name.")
void findSoftwareModuleTypeByName() {
/**
* Checks that software module typeis found based on given name.
*/
@Test void findSoftwareModuleTypeByName() {
testdataFactory.createSoftwareModuleOs();
final SoftwareModuleType found = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
@@ -146,9 +154,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(softwareModuleTypeManagement.findByName("thename")).as("Type with given name").contains(found);
}
@Test
@Description("Verifies that it is not possible to create a type that alrady exists.")
void createSoftwareModuleTypeFailsWithExistingEntity() {
/**
* Verifies that it is not possible to create a type that alrady exists.
*/
@Test void createSoftwareModuleTypeFailsWithExistingEntity() {
final SoftwareModuleTypeCreate create = entityFactory.softwareModuleType().create().key("thetype").name("thename");
softwareModuleTypeManagement.create(create);
assertThatExceptionOfType(EntityAlreadyExistsException.class)
@@ -157,9 +166,10 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
.create(create));
}
@Test
@Description("Verifies that it is not possible to create a list of types where one already exists.")
void createSoftwareModuleTypesFailsWithExistingEntity() {
/**
* Verifies that it is not possible to create a list of types where one already exists.
*/
@Test void createSoftwareModuleTypesFailsWithExistingEntity() {
softwareModuleTypeManagement.create(entityFactory.softwareModuleType().create().key("thetype").name("thename"));
final List<SoftwareModuleTypeCreate> creates = List.of(
entityFactory.softwareModuleType().create().key("thetype").name("thename"),
@@ -169,18 +179,20 @@ class SoftwareModuleTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> softwareModuleTypeManagement.create(creates));
}
@Test
@Description("Verifies that the creation of a softwareModuleType is failing because of invalid max assignment")
void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() {
/**
* Verifies that the creation of a softwareModuleType is failing because of invalid max assignment
*/
@Test void createSoftwareModuleTypesFailsWithInvalidMaxAssignment() {
final SoftwareModuleTypeCreate create = entityFactory.softwareModuleType().create().key("type").name("name").maxAssignments(0);
assertThatExceptionOfType(ConstraintViolationException.class)
.as("should not have worked as max assignment is invalid. Should be greater than 0")
.isThrownBy(() -> softwareModuleTypeManagement.create(create));
}
@Test
@Description("Verifies that multiple types are created as requested.")
void createMultipleSoftwareModuleTypes() {
/**
* Verifies that multiple types are created as requested.
*/
@Test void createMultipleSoftwareModuleTypes() {
final List<SoftwareModuleType> created = softwareModuleTypeManagement
.create(Arrays.asList(entityFactory.softwareModuleType().create().key("thetype").name("thename"),
entityFactory.softwareModuleType().create().key("thetype2").name("thename2")));

View File

@@ -11,88 +11,97 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - SystemManagement")
@Story("SecurityTests SystemManagement")
/**
* Feature: SecurityTests - SystemManagement<br/>
* Story: SecurityTests SystemManagement
*/
class SystemManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findTenantsPermissionWorks() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findTenantsPermissionWorks() {
assertPermissions(() -> systemManagement.findTenants(PAGE), List.of(SpPermission.SYSTEM_ADMIN));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteTenantPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteTenantPermissionsCheck() {
assertPermissions(() -> {
systemManagement.deleteTenant("tenant");
return null;
}, List.of(SpPermission.SYSTEM_ADMIN));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void forEachTenantTenantPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void forEachTenantTenantPermissionsCheck() {
assertPermissions(() -> {
systemManagement.forEachTenant(log::info);
return null;
}, List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getSystemUsageStatisticsWithTenantsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getSystemUsageStatisticsWithTenantsPermissionsCheck() {
assertPermissions(() -> systemManagement.getSystemUsageStatisticsWithTenants(), List.of(SpPermission.SYSTEM_ADMIN));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getSystemUsageStatisticsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getSystemUsageStatisticsPermissionsCheck() {
assertPermissions(() -> systemManagement.getSystemUsageStatistics(), List.of(SpPermission.SYSTEM_ADMIN));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTenantMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTenantMetadataPermissionsCheck() {
assertPermissions(() -> systemManagement.getTenantMetadata(), List.of(SpPermission.READ_REPOSITORY), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadata(), List.of(SpPermission.READ_TARGET), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadata(), List.of(SpPermission.READ_TENANT_CONFIGURATION), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadata(), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTenantMetadataWithoutDetailsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTenantMetadataWithoutDetailsPermissionsCheck() {
assertPermissions(() -> systemManagement.getTenantMetadataWithoutDetails(), List.of(SpPermission.READ_REPOSITORY), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadataWithoutDetails(), List.of(SpPermission.READ_TARGET), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadataWithoutDetails(), List.of(SpPermission.READ_TENANT_CONFIGURATION), List.of(SpPermission.CREATE_REPOSITORY));
assertPermissions(() -> systemManagement.getTenantMetadataWithoutDetails(), List.of(SpPermission.SpringEvalExpressions.CONTROLLER_ROLE), List.of(SpPermission.CREATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTenantMetadataByTenantPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTenantMetadataByTenantPermissionsCheck() {
assertPermissions(() -> systemManagement.getTenantMetadata(1L), List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createTenantMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createTenantMetadataPermissionsCheck() {
assertPermissions(() -> systemManagement.createTenantMetadata("tenant"), List.of(SpPermission.SpringEvalExpressions.SYSTEM_ROLE));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updateTenantMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updateTenantMetadataPermissionsCheck() {
assertPermissions(() -> systemManagement.updateTenantMetadata(1L), List.of(SpPermission.TENANT_CONFIGURATION));
}
}

View File

@@ -15,9 +15,6 @@ import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Random;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.ArtifactUpload;
@@ -30,14 +27,17 @@ import org.eclipse.hawkbit.repository.test.util.SecurityContextSwitch;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@Feature("Component Tests - Repository")
@Story("System Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: System Management
*/
@ExtendWith(DisposableSqlTestDatabaseExtension.class)
class SystemManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in")
void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception {
/**
* Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in
*/
@Test void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception {
assertThat(systemManagement.findTenants(PAGE).getContent()).hasSize(1);
createTestTenantsForSystemStatistics(2, 0, 0, 0);
@@ -45,9 +45,10 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
assertThat(systemManagement.findTenants(PAGE).getContent()).hasSize(3);
}
@Test
@Description("Ensures that getSystemUsageStatisticsWithTenants returns the usage of all tenants and not only the first 1000 (max page size).")
void systemUsageReportCollectsStatisticsOfManyTenants() throws Exception {
/**
* Ensures that getSystemUsageStatisticsWithTenants returns the usage of all tenants and not only the first 1000 (max page size).
*/
@Test void systemUsageReportCollectsStatisticsOfManyTenants() throws Exception {
// Prepare tenants
createTestTenantsForSystemStatistics(1050, 0, 0, 0);
@@ -55,9 +56,10 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
assertThat(tenants).hasSize(1051); // +1 from the setup
}
@Test
@Description("Checks that the system report calculates correctly the artifact size of all tenants in the system. It ignores deleted software modules with their artifacts.")
void systemUsageReportCollectsArtifactsOfAllTenants() throws Exception {
/**
* Checks that the system report calculates correctly the artifact size of all tenants in the system. It ignores deleted software modules with their artifacts.
*/
@Test void systemUsageReportCollectsArtifactsOfAllTenants() throws Exception {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 1234, 0, 0);
@@ -79,9 +81,10 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
tenantUsage1);
}
@Test
@Description("Checks that the system report calculates correctly the targets size of all tenants in the system")
void systemUsageReportCollectsTargetsOfAllTenants() throws Exception {
/**
* Checks that the system report calculates correctly the targets size of all tenants in the system
*/
@Test void systemUsageReportCollectsTargetsOfAllTenants() throws Exception {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 0, 100, 0);
@@ -99,9 +102,10 @@ class SystemManagementTest extends AbstractJpaIntegrationTest {
assertThat(tenants).containsOnly(new TenantUsage("DEFAULT"), tenantUsage0, tenantUsage1);
}
@Test
@Description("Checks that the system report calculates correctly the actions size of all tenants in the system")
void systemUsageReportCollectsActionsOfAllTenants() throws Exception {
/**
* Checks that the system report calculates correctly the actions size of all tenants in the system
*/
@Test void systemUsageReportCollectsActionsOfAllTenants() throws Exception {
// Prepare tenants
createTestTenantsForSystemStatistics(2, 0, 20, 2);

View File

@@ -11,133 +11,150 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.builder.AutoAssignDistributionSetUpdate;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Feature("SecurityTests - TargetFilterQueryManagement")
@Story("SecurityTests TargetFilterQueryManagement")
/**
* Feature: SecurityTests - TargetFilterQueryManagement<br/>
* Story: SecurityTests TargetFilterQueryManagement
*/
class TargetFilterQueryManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionsCheck() {
assertPermissions(
() -> targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("name").query("controllerId==id")),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionsCheck() {
assertPermissions(() -> {
targetFilterQueryManagement.delete(1L);
return null;
}, List.of(SpPermission.DELETE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void verifyTargetFilterQuerySyntaxPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void verifyTargetFilterQuerySyntaxPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.verifyTargetFilterQuerySyntax("controllerId==id"),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findAll(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.count(), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByAutoAssignDistributionSetIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByAutoAssignDistributionSetIdPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.countByAutoAssignDistributionSetId(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByNamePermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findByName("filterName", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByNamePermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.countByName("filterName"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findByRsql("name==id", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByQueryPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByQueryPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findByQuery("controllerId==id", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByAutoAssignDistributionSetIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByAutoAssignDistributionSetIdPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findByAutoAssignDistributionSetId(1L, PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByAutoAssignDSAndRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByAutoAssignDSAndRsqlPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findByAutoAssignDSAndRsql(1L, "rsqlParam", PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findWithAutoAssignDSPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findWithAutoAssignDSPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.findWithAutoAssignDS(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTargetFilterQueryByIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTargetFilterQueryByIdPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.get(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTargetFilterQueryByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTargetFilterQueryByNamePermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.getByName("filterName"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.update(entityFactory.targetFilterQuery().update(1L)),
List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updateAutoAssignDSPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updateAutoAssignDSPermissionsCheck() {
assertPermissions(() -> targetFilterQueryManagement.updateAutoAssignDS(new AutoAssignDistributionSetUpdate(1L).weight(1)),
List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void cancelAutoAssignmentForDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void cancelAutoAssignmentForDistributionSetPermissionsCheck() {
assertPermissions(() -> {
targetFilterQueryManagement.cancelAutoAssignmentForDistributionSet(1L);
return null;

View File

@@ -23,10 +23,6 @@ import java.util.function.Supplier;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.exception.AbstractServerRtException;
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
@@ -60,22 +56,25 @@ import org.springframework.data.domain.Slice;
/**
* Test class for {@link TargetFilterQueryManagement}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Target Filter Query Management
*/
@Feature("Component Tests - Repository")
@Story("Target Filter Query Management")
class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
/**
* Verifies that management get access reacts as specfied on calls for non existing entities by means of Optional not present.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(targetFilterQueryManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(targetFilterQueryManagement.getByName(NOT_EXIST_ID)).isNotPresent();
}
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities by means of throwing EntityNotFoundException.")
@ExpectEvents({
/**
* Verifies that management queries react as specfied on calls for non existing entities by means of throwing EntityNotFoundException.
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = TargetFilterQueryCreatedEvent.class, count = 1) })
@@ -108,9 +107,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
"DistributionSet");
}
@Test
@Description("Test creation of target filter query.")
void createTargetFilterQuery() {
/**
* Test creation of target filter query.
*/
@Test void createTargetFilterQuery() {
final String filterName = "new target filter";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -118,9 +118,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
"Retrieved newly created custom target filter");
}
@Test
@Description("Create a target filter query with an auto-assign distribution set and a query string that addresses too many targets.")
void createTargetFilterQueryThatExceedsQuota() {
/**
* Create a target filter query with an auto-assign distribution set and a query string that addresses too many targets.
*/
@Test void createTargetFilterQueryThatExceedsQuota() {
// create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
@@ -134,9 +135,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
}
@Test
@Description("Test searching a target filter query.")
void searchTargetFilterQuery() {
/**
* Test searching a target filter query.
*/
@Test void searchTargetFilterQuery() {
final String filterName = "targetFilterQueryName";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -150,17 +152,19 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
assertEquals(targetFilterQuery, results.get(0), "Retrieved newly created custom target filter");
}
@Test
@Description("Test searching a target filter query with an invalid filter.")
void searchTargetFilterQueryInvalidField() {
/**
* Test searching a target filter query with an invalid filter.
*/
@Test void searchTargetFilterQueryInvalidField() {
final PageRequest pageRequest = PageRequest.of(0, 10);
Assertions.assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.isThrownBy(() -> targetFilterQueryManagement.findByRsql("unknownField==testValue", pageRequest));
}
@Test
@Description("Checks if the EntityAlreadyExistsException is thrown if a targetFilterQuery with the same name are created more than once.")
void createDuplicateTargetFilterQuery() {
/**
* Checks if the EntityAlreadyExistsException is thrown if a targetFilterQuery with the same name are created more than once.
*/
@Test void createDuplicateTargetFilterQuery() {
final String filterName = "new target filter duplicate";
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
.name(filterName).query("name==PendingTargets001");
@@ -172,9 +176,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
}
@Test
@Description("Test deletion of target filter query.")
void deleteTargetFilterQuery() {
/**
* Test deletion of target filter query.
*/
@Test void deleteTargetFilterQuery() {
final String filterName = "delete_target_filter_query";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create(entityFactory.targetFilterQuery()
.create().name(filterName).query("name==PendingTargets001"));
@@ -184,9 +189,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
"Returns null as the target filter is deleted");
}
@Test
@Description("Test update of a target filter query.")
void updateTargetFilterQuery() {
/**
* Test update of a target filter query.
*/
@Test void updateTargetFilterQuery() {
final String filterName = "target_filter_01";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -197,9 +203,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
"Returns updated target filter query");
}
@Test
@Description("Test assigning a distribution set for auto assignment with different action types")
void assignDistributionSet() {
/**
* Test assigning a distribution set for auto assignment with different action types
*/
@Test void assignDistributionSet() {
final String filterName = "target_filter_02";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -213,9 +220,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
verifyAutoAssignmentWithSoftDeletedDs(targetFilterQuery);
}
@Test
@Description("Assigns a distribution set to an existing filter query and verifies that the quota 'max targets per auto assignment' is enforced.")
void assignDistributionSetToTargetFilterQueryThatExceedsQuota() {
/**
* Assigns a distribution set to an existing filter query and verifies that the quota 'max targets per auto assignment' is enforced.
*/
@Test void assignDistributionSetToTargetFilterQueryThatExceedsQuota() {
// create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
testdataFactory.createTargets(maxTargets + 1, "target%s");
@@ -233,9 +241,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Test
@Description("Updates an existing filter query with a query string that addresses too many targets.")
void updateTargetFilterQueryWithQueryThatExceedsQuota() {
/**
* Updates an existing filter query with a query string that addresses too many targets.
*/
@Test void updateTargetFilterQueryWithQueryThatExceedsQuota() {
// create targets
final int maxTargets = quotaManagement.getMaxTargetsPerAutoAssignment();
testdataFactory.createTargets(maxTargets + 1, "target%s");
@@ -252,9 +261,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.update(targetFilterQueryUpdate));
}
@Test
@Description("Test removing distribution set while it has a relation to a target filter query")
void removeAssignDistributionSet() {
/**
* Test removing distribution set while it has a relation to a target filter query
*/
@Test void removeAssignDistributionSet() {
final String filterName = "target_filter_03";
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name(filterName).query("name==PendingTargets001"));
@@ -279,9 +289,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
assertNull(tfq.getAutoAssignActionType(), "Returns action type as null");
}
@Test
@Description("Test to implicitly remove the auto assign distribution set when the ds is soft deleted")
void implicitlyRemoveAssignDistributionSet() {
/**
* Test to implicitly remove the auto assign distribution set when the ds is soft deleted
*/
@Test void implicitlyRemoveAssignDistributionSet() {
final String filterName = "target_filter_03";
final DistributionSet distributionSet = testdataFactory.createDistributionSet("dist_set");
final Target target = testdataFactory.createTarget();
@@ -313,9 +324,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
assertNull(tfq.getAutoAssignActionType(), "Returns action type as null");
}
@Test
@Description("Test finding and auto assign distribution set")
void findFiltersWithDistributionSet() {
/**
* Test finding and auto assign distribution set
*/
@Test void findFiltersWithDistributionSet() {
final String filterName = "d";
assertEquals(0L, targetFilterQueryManagement.count());
targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*"));
@@ -344,9 +356,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
verifyFindForAllWithAutoAssignDs(tfq, tfq2);
}
@Test
@Description("Creating or updating a target filter query with autoassignment and no-value weight when multi assignment in enabled.")
void weightNotRequiredInMultiAssignmentMode() {
/**
* Creating or updating a target filter query with autoassignment and no-value weight when multi assignment in enabled.
*/
@Test void weightNotRequiredInMultiAssignmentMode() {
enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
@@ -361,9 +374,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isNotNull();
}
@Test
@Description("Creating or updating a target filter query with autoassignment with a weight causes an error when multi assignment in disabled.")
void weightAllowedWhenMultiAssignmentModeNotEnabled() {
/**
* Creating or updating a target filter query with autoassignment with a weight causes an error when multi assignment in disabled.
*/
@Test void weightAllowedWhenMultiAssignmentModeNotEnabled() {
final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement.create(entityFactory.targetFilterQuery().create().name("a").query("name==*")).getId();
@@ -378,9 +392,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isNotNull();
}
@Test
@Description("Auto assignment can be removed from filter when multi assignment in enabled.")
void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() {
/**
* Auto assignment can be removed from filter when multi assignment in enabled.
*/
@Test void removeDsFromFilterWhenMultiAssignmentModeNotEnabled() {
enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet();
final Long filterId = targetFilterQueryManagement.create(
@@ -391,9 +406,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isNotNull();
}
@Test
@Description("Weight is validated and saved to the Filter.")
void weightValidatedAndSaved() {
/**
* Weight is validated and saved to the Filter.
*/
@Test void weightValidatedAndSaved() {
enableMultiAssignments();
final DistributionSet ds = testdataFactory.createDistributionSet();
@@ -421,9 +437,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFilterQueryManagement.get(filterId).get().getAutoAssignWeight()).contains(Action.WEIGHT_MIN);
}
@Test
@Description("Verifies that an exception is thrown when trying to create a target filter with an invalidated distribution set.")
void createTargetFilterWithInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to create a target filter with an invalidated distribution set.
*/
@Test void createTargetFilterWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
@@ -433,9 +450,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
}
@Test
@Description("Verifies that an exception is thrown when trying to create a target filter with an incomplete distribution set.")
void createTargetFilterWithIncompleteDistributionSet() {
/**
* Verifies that an exception is thrown when trying to create a target filter with an incomplete distribution set.
*/
@Test void createTargetFilterWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
final TargetFilterQueryCreate targetFilterQueryCreate = entityFactory.targetFilterQuery().create()
@@ -446,9 +464,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.create(targetFilterQueryCreate));
}
@Test
@Description("Verifies that an exception is thrown when trying to update a target filter with an invalidated distribution set.")
void updateAutoAssignDsWithInvalidDistributionSet() {
/**
* Verifies that an exception is thrown when trying to update a target filter with an invalidated distribution set.
*/
@Test void updateAutoAssignDsWithInvalidDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithInvalidDistributionSet")
@@ -462,9 +481,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Test
@Description("Verifies that an exception is thrown when trying to update a target filter with an incomplete distribution set.")
void updateAutoAssignDsWithIncompleteDistributionSet() {
/**
* Verifies that an exception is thrown when trying to update a target filter with an incomplete distribution set.
*/
@Test void updateAutoAssignDsWithIncompleteDistributionSet() {
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement.create(
entityFactory.targetFilterQuery().create().name("updateAutoAssignDsWithIncompleteDistributionSet")
@@ -478,9 +498,10 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Test
@Description("Tests the auto assign action type mapping.")
void testAutoAssignActionTypeConvert() {
/**
* Tests the auto assign action type mapping.
*/
@Test void testAutoAssignActionTypeConvert() {
for (final ActionType actionType : ActionType.values()) {
final Supplier<Long> create = () ->
targetFilterQueryManagement.create(
@@ -506,7 +527,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
jpaTargetFilterQuery.setAutoAssignActionType(ActionType.TIMEFORCED));
}
@Step
private void verifyAutoAssignmentWithDefaultActionType(final String filterName,
final TargetFilterQuery targetFilterQuery, final DistributionSet distributionSet) {
targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery()
@@ -515,7 +535,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
verifyAutoAssignDsAndActionType(filterName, distributionSet, ActionType.FORCED);
}
@Step
private void verifyAutoAssignmentWithSoftActionType(final String filterName,
final TargetFilterQuery targetFilterQuery, final DistributionSet distributionSet) {
targetFilterQueryManagement.updateAutoAssignDS(entityFactory.targetFilterQuery()
@@ -523,7 +542,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
verifyAutoAssignDsAndActionType(filterName, distributionSet, ActionType.SOFT);
}
@Step
private void verifyAutoAssignmentWithDownloadOnlyActionType(final String filterName,
final TargetFilterQuery targetFilterQuery, final DistributionSet distributionSet) {
targetFilterQueryManagement
@@ -532,7 +550,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
verifyAutoAssignDsAndActionType(filterName, distributionSet, ActionType.DOWNLOAD_ONLY);
}
@Step
private void verifyAutoAssignmentWithInvalidActionType(final TargetFilterQuery targetFilterQuery,
final DistributionSet distributionSet) {
// assigning a distribution set with TIMEFORCED action is supposed to
@@ -545,7 +562,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Step
private void verifyAutoAssignmentWithIncompleteDs(final TargetFilterQuery targetFilterQuery) {
final DistributionSet incompleteDistributionSet = distributionSetManagement
.create(entityFactory.distributionSet().create().name("incomplete").version("1")
@@ -557,7 +573,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Step
private void verifyAutoAssignmentWithSoftDeletedDs(final TargetFilterQuery targetFilterQuery) {
final DistributionSet softDeletedDs = testdataFactory.createDistributionSet("softDeleted");
assignDistributionSet(softDeletedDs, testdataFactory.createTarget("forSoftDeletedDs"));
@@ -569,7 +584,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetFilterQueryManagement.updateAutoAssignDS(autoAssignDistributionSetUpdate));
}
@Step
private void verifyFindByDistributionSetAndRsql(final DistributionSet distributionSet, final String rsql,
final TargetFilterQuery... expectedFilterQueries) {
final Page<TargetFilterQuery> tfqList = targetFilterQueryManagement
@@ -585,7 +599,6 @@ class TargetFilterQueryManagementTest extends AbstractJpaIntegrationTest {
Arrays.stream(expectedFilterQueries).map(TargetFilterQuery::getId).toArray(Long[]::new));
}
@Step
private void verifyFindForAllWithAutoAssignDs(final TargetFilterQuery... expectedFilterQueries) {
final Slice<TargetFilterQuery> tfqList = targetFilterQueryManagement
.findWithAutoAssignDS(PageRequest.of(0, 500));

View File

@@ -16,10 +16,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.FilterParams;
import org.eclipse.hawkbit.repository.builder.DistributionSetCreate;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -33,15 +29,18 @@ import org.eclipse.hawkbit.repository.model.TargetType;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository")
@Story("Target Management Searches")
/**
* Feature: Component Tests - Repository<br/>
* Story: Target Management Searches
*/
class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
private static final String SPACE_AND_DESCRIPTION = " description";
@Test
@Description("Verifies that targets with given target type are returned from repository.")
void findTargetByTargetType() {
/**
* Verifies that targets with given target type are returned from repository.
*/
@Test void findTargetByTargetType() {
final TargetType testType = testdataFactory.createTargetType("testType",
Collections.singletonList(standardDsType));
final List<Target> unassigned = testdataFactory.createTargets(9, "unassigned");
@@ -61,10 +60,11 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
}
/**
* Tests different parameter combinations for target search operations.
* and query definitions by RSQL (named and un-named).
*/
@Test
@Description("Tests different parameter combinations for target search operations. "
+ "That includes both the test itself, as a count operation with the same filters "
+ "and query definitions by RSQL (named and un-named).")
void targetSearchWithVariousFilterCombinations() {
final TargetTag targTagX = targetTagManagement.create(entityFactory.tag().create().name("TargTag-X"));
final TargetTag targTagY = targetTagManagement.create(entityFactory.tag().create().name("TargTag-Y"));
@@ -187,9 +187,10 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
verifyThat198TargetsAreInStatusUnknownAndOverdue(unknown, expected);
}
@Test
@Description("Verifies that targets with given assigned DS are returned from repository.")
void findTargetByAssignedDistributionSet() {
/**
* Verifies that targets with given assigned DS are returned from repository.
*/
@Test void findTargetByAssignedDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
testdataFactory.createTargets(10, "unassigned", "unassigned");
List<Target> assignedtargets = testdataFactory.createTargets(10, "assigned", "assigned");
@@ -205,9 +206,10 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that targets without given assigned DS are returned from repository.")
void findTargetWithoutAssignedDistributionSet() {
/**
* Verifies that targets without given assigned DS are returned from repository.
*/
@Test void findTargetWithoutAssignedDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
final TargetFilterQuery tfq = targetFilterQueryManagement
.create(entityFactory.targetFilterQuery().create().name("tfq").query("name==*"));
@@ -223,9 +225,10 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that targets with given installed DS are returned from repository.")
void findTargetByInstalledDistributionSet() {
/**
* Verifies that targets with given installed DS are returned from repository.
*/
@Test void findTargetByInstalledDistributionSet() {
final DistributionSet assignedSet = testdataFactory.createDistributionSet("");
final DistributionSet installedSet = testdataFactory.createDistributionSet("another");
testdataFactory.createTargets(10, "unassigned", "unassigned");
@@ -245,9 +248,10 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Verifies that all compatible targets are returned from repository.")
void shouldFindAllTargetsCompatibleWithDS() {
/**
* Verifies that all compatible targets are returned from repository.
*/
@Test void shouldFindAllTargetsCompatibleWithDS() {
final DistributionSet testDs = testdataFactory.createDistributionSet();
final TargetType targetType = testdataFactory.createTargetType("testType",
Collections.singletonList(testDs.getType()));
@@ -264,9 +268,10 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.as("contains all targets").containsAll(targetWithCompatibleTypes).containsAll(targets);
}
@Test
@Description("Verifies that incompatible targets are not returned from repository.")
void shouldNotFindTargetsIncompatibleWithDS() {
/**
* Verifies that incompatible targets are not returned from repository.
*/
@Test void shouldNotFindTargetsIncompatibleWithDS() {
final DistributionSetType dsType = testdataFactory.findOrCreateDistributionSetType("test-ds-type",
"test-ds-type");
final DistributionSet testDs = createDistSetWithType(dsType);
@@ -295,7 +300,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.doesNotContainAnyElementsOf(targetsWithIncompatibleType);
}
@Step
private void verifyThat1TargetAIsInStatusPendingAndHasDSInstalled(final DistributionSet installedSet,
final List<TargetUpdateStatus> pending, final Target expected) {
final FilterParams filterParams = new FilterParams(pending, null, null, installedSet.getId(), Boolean.FALSE);
@@ -308,7 +312,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat200targetsWithGivenTagAreInStatusPendingOrUnknown(final TargetTag targTagW,
final List<TargetUpdateStatus> both, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(both, null, null, null, Boolean.FALSE, targTagW.getName());
@@ -322,7 +325,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat2TargetsWithGivenTagAreInPending(final TargetTag targTagW,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(pending, null, null, null, Boolean.FALSE,
@@ -337,7 +339,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat2TargetsWithGivenTagAndDSIsInPending(final TargetTag targTagW, final DistributionSet setA,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(pending, null, null, setA.getId(), Boolean.FALSE,
@@ -353,7 +354,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(final TargetTag targTagW,
final DistributionSet setA, final List<TargetUpdateStatus> pending, final Target expected) {
final FilterParams filterParams = new FilterParams(pending, null, "%targ-B%", setA.getId(), Boolean.FALSE,
@@ -369,7 +369,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(final DistributionSet setA,
final List<TargetUpdateStatus> pending, final Target expected) {
final FilterParams filterParams = new FilterParams(pending, null, "%targ-A%", setA.getId(), Boolean.FALSE);
@@ -384,7 +383,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat3TargetsWithGivenDSAreInPending(final DistributionSet setA,
final List<TargetUpdateStatus> pending, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(pending, null, null, setA.getId(), Boolean.FALSE);
@@ -399,7 +397,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat4TargetsAreInStatusPending(final List<TargetUpdateStatus> pending,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams(pending, null, null, null, Boolean.FALSE);
@@ -413,7 +410,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(final TargetTag targTagW,
final List<TargetUpdateStatus> unknown, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(unknown, null, "%targ-B%", null, Boolean.FALSE,
@@ -429,7 +425,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams(unknown, null, "%targ-A%", null, Boolean.FALSE);
@@ -443,7 +438,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(final DistributionSet setA,
final List<TargetUpdateStatus> unknown) {
final FilterParams filterParams = new FilterParams(unknown, null, null, setA.getId(), Boolean.FALSE);
@@ -459,7 +453,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.isEmpty();
}
@Step
private void verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(final TargetTag targTagY,
final TargetTag targTagW, final List<TargetUpdateStatus> unknown, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(unknown, null, null, null, Boolean.FALSE, targTagY.getName(),
@@ -475,7 +468,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat496TargetsAreInStatusUnknown(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams(unknown, null, null, null, Boolean.FALSE);
@@ -489,7 +481,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat198TargetsAreInStatusUnknownAndOverdue(final List<TargetUpdateStatus> unknown,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams(unknown, Boolean.TRUE, null, null, Boolean.FALSE);
@@ -504,7 +495,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat1TargetWithDescOrNameHasDS(final DistributionSet setA, final Target expected) {
final FilterParams filterParams = new FilterParams(null, null, "%targ-A%", setA.getId(), Boolean.FALSE);
final String query = "(name==*targ-A* or description==*targ-A*) and (assignedds.name==" + setA.getName()
@@ -518,7 +508,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat3TargetsHaveDSAssigned(final DistributionSet setA, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(null, null, null, setA.getId(), Boolean.FALSE);
final String query = "assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName();
@@ -531,7 +520,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat0TargetsWithNameOrdescAndDSHaveTag(final TargetTag targTagX, final DistributionSet setA) {
final FilterParams filterParams = new FilterParams(null, null, "%targ-C%", setA.getId(), Boolean.FALSE,
targTagX.getName());
@@ -546,7 +534,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.isEmpty();
}
@Step
private void verifyThat0TargetsWithTagAndDescOrNameHasDS(final TargetTag targTagW, final DistributionSet setA) {
final FilterParams filterParams = new FilterParams(null, null, "%targ-A%", setA.getId(), Boolean.FALSE,
targTagW.getName());
@@ -560,7 +547,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.isEmpty();
}
@Step
private void verifyThat1TargetHasTagHasDescOrNameAndDs(final TargetTag targTagW, final DistributionSet setA,
final Target expected) {
final FilterParams filterParams = new FilterParams(null, null, "%targ-C%", setA.getId(), Boolean.FALSE,
@@ -575,7 +561,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThat1TargetHasNameAndId(final String name, final String controllerId) {
final FilterParams filterParamsByName = new FilterParams(null, null, name, null, Boolean.FALSE);
assertThat(targetManagement.findByFilters(filterParamsByName, PAGE).getContent()).as("has number of elements")
@@ -588,7 +573,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.hasSize((int) targetManagement.countByFilters(filterParamsByControllerId));
}
@Step
private void verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(final TargetTag targTagY,
final TargetTag targTagW, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(null, null, "%targ-B%", null, Boolean.FALSE,
@@ -610,7 +594,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
return result;
}
@Step
private void verifyThat200TargetsHaveTagD(final TargetTag targTagD, final List<Target> expected) {
final FilterParams filterParams = new FilterParams(null, null, null, null, Boolean.FALSE, targTagD.getName());
final String query = "tag==" + targTagD.getName();
@@ -622,7 +605,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findByRsql(query, PAGE).getContent());
}
@Step
private void verifyThatRepositoryContains500Targets() {
final FilterParams filterParams = new FilterParams(null, null, null, null, null);
assertThat(targetManagement.findByFilters(filterParams, PAGE).getContent())
@@ -632,7 +614,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(targetManagement.findAll(PAGE).getContent());
}
@Step
private void verifyThat1TargetHasTypeAndDSAssigned(final TargetType type, final DistributionSet set,
final Target expected) {
final FilterParams filterParams = new FilterParams(null, set.getId(), Boolean.FALSE, type.getId());
@@ -642,7 +623,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.as("and contains the following elements").containsExactly(expected);
}
@Step
private void verifyThatTargetsHasNoTypeAndDSAssignedOrInstalled(final DistributionSet set,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams(null, set.getId(), Boolean.TRUE, null);
@@ -652,7 +632,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.as("and contains the following elements").containsAll(expected);
}
@Step
private void verifyThat100TargetsContainsGivenTextAndHaveTypeAssigned(final TargetType targetType,
final List<Target> expected) {
final FilterParams filterParams = new FilterParams("%targ-E%", null, Boolean.FALSE, targetType.getId());
@@ -667,7 +646,6 @@ class TargetManagementSearchTest extends AbstractJpaIntegrationTest {
.containsAll(expected.stream().map(Target::getControllerId).toList());
}
@Step
private void verifyThat400TargetsContainsGivenTextAndHaveNoTypeAssigned(final List<Target> expected) {
final FilterParams filterParams = new FilterParams("%targ-%", null, Boolean.TRUE, null);
assertThat(targetManagement.findByFilters(filterParams, PAGE).getContent()).as("has number of elements")

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Map;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.FilterParams;
@@ -24,372 +21,429 @@ import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - TargetManagement")
@Story("SecurityTests TargetManagement")
/**
* Feature: SecurityTests - TargetManagement<br/>
* Story: SecurityTests TargetManagement
*/
class TargetManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByAssignedDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByAssignedDistributionSetPermissionsCheck() {
assertPermissions(() -> targetManagement.countByAssignedDistributionSet(1L),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByFiltersPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByFiltersPermissionsCheck() {
assertPermissions(() -> targetManagement.countByFilters(new FilterParams(null, null, null, null, null, null)),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByInstalledDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByInstalledDistributionSetPermissionsCheck() {
assertPermissions(() -> targetManagement.countByInstalledDistributionSet(1L),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void existsByInstalledOrAssignedDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void existsByInstalledOrAssignedDistributionSetPermissionsCheck() {
assertPermissions(() -> targetManagement.existsByInstalledOrAssignedDistributionSet(1L),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlPermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsql("controllerId==id"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlAndUpdatablePermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsqlAndUpdatable("controllerId==id"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlAndCompatiblePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlAndCompatiblePermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsqlAndCompatible("controllerId==id", 1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsqlAndCompatibleAndUpdatable("controllerId==id", 1L),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByFailedInRolloutPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByFailedInRolloutPermissionsCheck() {
assertPermissions(() -> targetManagement.countByFailedInRollout("1", 1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countPermissionsCheck() {
assertPermissions(() -> targetManagement.count(), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionsCheck() {
assertPermissions(() -> targetManagement.create(entityFactory.target().create().controllerId("controller").name("name")),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createCollectionPermissionsCheck() {
assertPermissions(() -> targetManagement.create(List.of(entityFactory.target().create().controllerId("controller").name("name"))),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionsCheck() {
assertPermissions(() -> {
targetManagement.delete(List.of(1L));
return null;
}, List.of(SpPermission.DELETE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteByControllerIDPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteByControllerIDPermissionsCheck() {
assertPermissions(() -> {
targetManagement.deleteByControllerID("controllerId");
return null;
}, List.of(SpPermission.DELETE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByTargetFilterQueryPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByTargetFilterQueryPermissionsCheck() {
assertPermissions(() -> targetManagement.countByTargetFilterQuery(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTargetFilterQueryAndNonDSAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTargetFilterQueryAndNonDSAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(() -> targetManagement.findByTargetFilterQueryAndNonDSAndCompatibleAndUpdatable(1L, "controllerId==id", PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlAndNonDSAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlAndNonDSAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsqlAndNonDSAndCompatibleAndUpdatable(1L, "controllerId==id"),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(
() -> targetManagement.findByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatable(List.of(1L), "controllerId==id",
entityFactory.distributionSetType().create().build(), PAGE
), List.of(SpPermission.READ_TARGET, SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByActionsInRolloutGroupPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByActionsInRolloutGroupPermissionsCheck() {
assertPermissions(() -> targetManagement.countByActionsInRolloutGroup(1L),
List.of(SpPermission.READ_TARGET, SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(() -> targetManagement.countByRsqlAndNotInRolloutGroupsAndCompatibleAndUpdatable("controllerId==id", List.of(1L),
entityFactory.distributionSetType().create().build()), List.of(SpPermission.READ_TARGET, SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByFailedRolloutAndNotInRolloutGroupsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByFailedRolloutAndNotInRolloutGroupsPermissionsCheck() {
assertPermissions(() -> targetManagement.findByFailedRolloutAndNotInRolloutGroups("1", List.of(1L), PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByFailedRolloutAndNotInRolloutGroupsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByFailedRolloutAndNotInRolloutGroupsPermissionsCheck() {
assertPermissions(() -> targetManagement.countByFailedRolloutAndNotInRolloutGroups("1", List.of(1L)),
List.of(SpPermission.READ_TARGET, SpPermission.READ_ROLLOUT));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByInRolloutGroupWithoutActionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByInRolloutGroupWithoutActionPermissionsCheck() {
assertPermissions(() -> targetManagement.findByInRolloutGroupWithoutAction(1L, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByAssignedDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByAssignedDistributionSetPermissionsCheck() {
assertPermissions(() -> targetManagement.findByAssignedDistributionSet(1L, PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByAssignedDistributionSetAndRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByAssignedDistributionSetAndRsqlPermissionsCheck() {
assertPermissions(() -> targetManagement.findByAssignedDistributionSetAndRsql(1L, "controllerId==id", PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByControllerCollectionIDPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByControllerCollectionIDPermissionsCheck() {
assertPermissions(() -> targetManagement.getByControllerID(List.of("controllerId")), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByControllerIDPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByControllerIDPermissionsCheck() {
assertPermissions(() -> targetManagement.getByControllerID("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByFiltersPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByFiltersPermissionsCheck() {
assertPermissions(() -> targetManagement.findByFilters(new FilterParams(null, null, null, null, null, null), PAGE),
List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByInstalledDistributionSetPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByInstalledDistributionSetPermissionsCheck() {
assertPermissions(() -> targetManagement.findByInstalledDistributionSet(1L, PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByInstalledDistributionSetAndRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByInstalledDistributionSetAndRsqlPermissionsCheck() {
assertPermissions(() -> targetManagement.findByInstalledDistributionSetAndRsql(1L, "controllerId==id", PAGE),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByUpdateStatusPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByUpdateStatusPermissionsCheck() {
assertPermissions(() -> targetManagement.findByUpdateStatus(TargetUpdateStatus.IN_SYNC, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllPermissionsCheck() {
assertPermissions(() -> targetManagement.findAll(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlPermissionsCheck() {
assertPermissions(() -> targetManagement.findByRsql("controllerId==id", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTargetFilterQueryPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTargetFilterQueryPermissionsCheck() {
assertPermissions(() -> targetManagement.findByTargetFilterQuery(1L, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByTagPermissionsCheck() {
assertPermissions(() -> targetManagement.findByTag(1L, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlAndTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlAndTagPermissionsCheck() {
assertPermissions(() -> targetManagement.findByRsqlAndTag("controllerId==id", 1L, PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignTypePermissionsCheck() {
assertPermissions(() -> targetManagement.assignType(List.of("controllerId"), 1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignTypeByIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignTypeByIdPermissionsCheck() {
assertPermissions(() -> targetManagement.unassignType("controllerId"), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignTagWithHandlerPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignTagWithHandlerPermissionsCheck() {
assertPermissions(() -> targetManagement.assignTag(List.of("controllerId"), 1L, strings -> {}),
List.of(SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignTagPermissionsCheck() {
assertPermissions(() -> targetManagement.assignTag(List.of("controllerId"), 1L),
List.of(SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignTagPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignTagPermissionsCheck() {
assertPermissions(() -> targetManagement.unassignTag(List.of("controllerId"), 1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignTagWithHandlerPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignTagWithHandlerPermissionsCheck() {
assertPermissions(() -> targetManagement.unassignTag(List.of("controllerId"), 1L, strings -> {}),
List.of(SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void unassignTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void unassignTypePermissionsCheck() {
assertPermissions(() -> targetManagement.unassignType(List.of("controllerId")), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignTypeByIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignTypeByIdPermissionsCheck() {
assertPermissions(() -> targetManagement.assignType("controllerId", 1L), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionsCheck() {
assertPermissions(() -> targetManagement.update(entityFactory.target().update("controllerId")), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> targetManagement.get(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getCollectionPermissionsCheck() {
assertPermissions(() -> targetManagement.get(List.of(1L)), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void existsByControllerIdPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void existsByControllerIdPermissionsCheck() {
assertPermissions(() -> targetManagement.existsByControllerId("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatablePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatablePermissionsCheck() {
assertPermissions(
() -> targetManagement.isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatable("controllerId", 1L, "controllerId==id"),
List.of(SpPermission.READ_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getTagsPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getTagsPermissionsCheck() {
assertPermissions(() -> targetManagement.getTags("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getControllerAttributesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getControllerAttributesPermissionsCheck() {
assertPermissions(() -> targetManagement.getControllerAttributes("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void requestControllerAttributesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void requestControllerAttributesPermissionsCheck() {
assertPermissions(() -> {
targetManagement.requestControllerAttributes("controllerId");
return null;
}, List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void isControllerAttributesRequestedPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void isControllerAttributesRequestedPermissionsCheck() {
assertPermissions(() -> targetManagement.isControllerAttributesRequested("controllerId"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByControllerAttributesRequestedPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByControllerAttributesRequestedPermissionsCheck() {
assertPermissions(() -> targetManagement.findByControllerAttributesRequested(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createMetadataPermissionsCheck() {
assertPermissions(
() -> {
targetManagement.createMetadata("controllerId", Map.of("key", "value"));
@@ -398,15 +452,17 @@ class TargetManagementSecurityTest extends AbstractJpaIntegrationTest {
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getMetadataPermissionsCheck() {
assertPermissions(() -> targetManagement.getMetadata("controllerId"), List.of(SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
@WithUser(principal = "user", authorities = { SpPermission.UPDATE_REPOSITORY })
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test @WithUser(principal = "user", authorities = { SpPermission.UPDATE_REPOSITORY })
void updateMetadataPermissionsCheck() {
assertPermissions(() -> {
targetManagement.updateMetadata("controllerId", "key", "value");
@@ -415,9 +471,10 @@ class TargetManagementSecurityTest extends AbstractJpaIntegrationTest {
List.of(SpPermission.UPDATE_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteMetadataPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteMetadataPermissionsCheck() {
assertPermissions(() -> {
targetManagement.deleteMetadata("controllerId", "key");
return null;

View File

@@ -27,10 +27,6 @@ import java.util.Optional;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.awaitility.Awaitility;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.im.authentication.SpRole;
@@ -82,15 +78,19 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
@Feature("Component Tests - Repository")
@Story("Target Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Target Management
*/
class TargetManagementTest extends AbstractJpaIntegrationTest {
private static final String WHITESPACE_ERROR = "target with whitespaces in controller id should not be created";
/**
* Verifies that management get access react as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void nonExistingEntityAccessReturnsNotPresent() {
final Target target = testdataFactory.createTarget();
@@ -99,9 +99,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.getMetadata(target.getControllerId()).get(NOT_EXIST_ID)).isNull();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetTagCreatedEvent.class, count = 1) })
@@ -155,9 +157,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> targetManagement.updateMetadata(NOT_EXIST_ID, "xxx", "xxx"), "Target");
}
@Test
@Description("Ensures that retrieving the target security is only permitted with the necessary permissions.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
/**
* Ensures that retrieving the target security is only permitted with the necessary permissions.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception {
final Target createdTarget = targetManagement
.create(entityFactory.target().create().controllerId("targetWithSecurityToken").securityToken("token"));
@@ -191,9 +194,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(securityTokenWithoutPermission).isNull();
}
@Test
@Description("Verify that a target with same controller ID than another device cannot be created.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
/**
* Verify that a target with same controller ID than another device cannot be created.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void createTargetThatViolatesUniqueConstraintFails() {
final TargetCreate targetCreate = entityFactory.target().create().controllerId("123");
targetManagement.create(targetCreate);
@@ -202,9 +206,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.create(targetCreate));
}
@Test
@Description("Verify that a target with with invalid properties cannot be created or updated")
@ExpectEvents({
/**
* Verify that a target with with invalid properties cannot be created or updated
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class) })
void createAndUpdateTargetWithInvalidFields() {
@@ -217,9 +222,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
createAndUpdateTargetWithInvalidAddress(target);
}
@Test
@Description("Ensures that targets can assigned and unassigned to a target tag. Not exists target will be ignored for the assignment.")
@ExpectEvents({
/**
* Ensures that targets can assigned and unassigned to a target tag. Not exists target will be ignored for the assignment.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 4),
@Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 5) })
@@ -253,9 +259,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Ensures that targets can deleted e.g. test all cascades")
@ExpectEvents({
/**
* Ensures that targets can deleted e.g. test all cascades
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 12),
@Expect(type = TargetDeletedEvent.class, count = 12),
@Expect(type = TargetUpdatedEvent.class, count = 6) })
@@ -283,9 +290,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.count()).as("target count is wrong").isZero();
}
@Test
@Description("Finds a target by given ID and checks if all data is in the response (including the data defined as lazy).")
@ExpectEvents({
/**
* Finds a target by given ID and checks if all data is in the response (including the data defined as lazy).
*/
@Test @ExpectEvents({
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6),
@Expect(type = DistributionSetUpdatedEvent.class, count = 2), // implicit lock
@@ -353,9 +361,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(installedDs).as("Installed ds is wrong").isEqualTo(testDs1);
}
@Test
@Description("Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5) })
/**
* Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5) })
void createMultipleTargetsDuplicate() {
testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets");
assertThatExceptionOfType(EntityAlreadyExistsException.class)
@@ -363,9 +372,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> testdataFactory.createTargets(5, "mySimpleTargs", "my simple targets"));
}
@Test
@Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
/**
* Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void createTargetDuplicate() {
final TargetCreate targetCreate = entityFactory.target().create().controllerId("4711");
targetManagement.create(targetCreate);
@@ -374,9 +384,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.create(targetCreate));
}
/**
* Creates and updates a target and verifies the changes in the repository.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Creates and updates a target and verifies the changes in the repository.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 1) })
@@ -412,9 +424,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(foundTarget.getLastModifiedAt());
}
/**
* Create multiple targets as bulk operation and delete them in bulk.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Create multiple targets as bulk operation and delete them in bulk.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 101),
@Expect(type = TargetUpdatedEvent.class, count = 100),
@@ -480,9 +494,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetsLeft).as("Not all undeleted found").doesNotContain(deletedTargets);
}
@Test
@Description("Tests the assignment of tags to the a single target.")
@ExpectEvents({
/**
* Tests the assignment of tags to the a single target.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 2),
@Expect(type = TargetTagCreatedEvent.class, count = 7),
@Expect(type = TargetUpdatedEvent.class, count = 7) })
@@ -513,9 +528,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.hasSize(noT2Tags).doesNotContain(toArray(t1Tags, TargetTag.class));
}
@Test
@Description("Tests the assignment of tags to multiple targets.")
@ExpectEvents({
/**
* Tests the assignment of tags to multiple targets.
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 50),
@Expect(type = TargetTagCreatedEvent.class, count = 4),
@Expect(type = TargetUpdatedEvent.class, count = 80) })
@@ -583,9 +599,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.as("Target count is wrong").isEqualTo(targetWithTagC.size());
}
@Test
@Description("Tests the unassigment of tags to multiple targets.")
@ExpectEvents({
/**
* Tests the unassigment of tags to multiple targets.
*/
@Test @ExpectEvents({
@Expect(type = TargetTagCreatedEvent.class, count = 3),
@Expect(type = TargetCreatedEvent.class, count = 109),
@Expect(type = TargetUpdatedEvent.class, count = 227) })
@@ -642,9 +659,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
checkTargetHasNotTags(targABCs, targTagC);
}
@Test
@Description("Test that NO TAG functionality which gives all targets with no tag assigned.")
@ExpectEvents({
/**
* Test that NO TAG functionality which gives all targets with no tag assigned.
*/
@Test @ExpectEvents({
@Expect(type = TargetTagCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 50),
@Expect(type = TargetUpdatedEvent.class, count = 25) })
@@ -664,9 +682,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Tests the a target can be read with only the read target permission")
@ExpectEvents({
/**
* Tests the a target can be read with only the read target permission
*/
@Test @ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetPollEvent.class, count = 1) })
void targetCanBeReadWithOnlyReadTargetPermission() throws Exception {
@@ -683,9 +702,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Test that RSQL filter finds targets with tags or specific ids.")
void findTargetsWithTagOrId() {
/**
* Test that RSQL filter finds targets with tags or specific ids.
*/
@Test void findTargetsWithTagOrId() {
final String rsqlFilter = "tag==Targ-A-Tag,id==target-id-B-00001,id==target-id-B-00008";
final TargetTag targTagA = targetTagManagement.create(entityFactory.tag().create().name("Targ-A-Tag"));
final List<String> targAs = testdataFactory.createTargets(25, "target-id-A", "first description").stream()
@@ -702,9 +722,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(27L);
}
@Test
@Description("Verify that the find all targets by ids method contains the entities that we are looking for")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 12) })
/**
* Verify that the find all targets by ids method contains the entities that we are looking for
*/
@Test @ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 12) })
void verifyFindTargetAllById() {
final List<Long> searchIds = Arrays.asList(testdataFactory.createTarget("target-4").getId(),
testdataFactory.createTarget("target-5").getId(), testdataFactory.createTarget("target-6").getId());
@@ -720,9 +741,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(collect).containsAll(searchIds);
}
@Test
@Description("Verify that the flag for requesting controller attributes is set correctly.")
void verifyRequestControllerAttributes() {
/**
* Verify that the flag for requesting controller attributes is set correctly.
*/
@Test void verifyRequestControllerAttributes() {
final String knownControllerId = "KnownControllerId";
final Target target = createTargetWithAttributes(knownControllerId);
@@ -738,17 +760,19 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Checks that metadata for a target can be created.")
void createMetadata() {
/**
* Checks that metadata for a target can be created.
*/
@Test void createMetadata() {
insertMetadata(
"targetMetaKnownKey", "targetMetaKnownValue",
testdataFactory.createTarget("targetIdWithMetadata")); // and validate
}
@Test
@Description("Verifies the enforcement of the metadata quota per target.")
void createMetadataUntilQuotaIsExceeded() {
/**
* Verifies the enforcement of the metadata quota per target.
*/
@Test void createMetadataUntilQuotaIsExceeded() {
// add meta-data one by one
final Target target1 = testdataFactory.createTarget("target1");
final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerTarget();
@@ -789,18 +813,21 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.createMetadata(target3ControllerId, metaData3));
}
@Test
@Description("Queries and loads the metadata related to a given target.")
void getMetadata() {
/**
* Queries and loads the metadata related to a given target.
*/
@Test void getMetadata() {
// create targets
assertThat(targetManagement.getMetadata(testdataFactory.createTarget("target0").getControllerId())).isEmpty();
assertThat(targetManagement.getMetadata(createTargetWithMetadata("target1", 10).getControllerId())).hasSize(10);
assertThat(targetManagement.getMetadata(createTargetWithMetadata("target2", 8).getControllerId())).hasSize(8);
}
/**
* Checks that metadata for a target can be updated.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that metadata for a target can be updated.")
void updateMetadata() {
final String knownKey = "myKnownKey";
final String knownValue = "myKnownValue";
@@ -828,9 +855,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.getMetadata(target.getControllerId())).containsEntry(knownKey, knownUpdateValue);
}
@Test
@Description("Queries and loads the metadata related to a given target.")
void deleteMetadata() {
/**
* Queries and loads the metadata related to a given target.
*/
@Test void deleteMetadata() {
final String knownKey = "myKnownKey";
final String knownValue = "myKnownValue";
@@ -844,9 +872,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.deleteMetadata(controllerId, knownKey));
}
/**
* Checks that target type for a target can be created, updated and unassigned.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that target type for a target can be created, updated and unassigned.")
void createAndUpdateTargetTypeInTarget() {
// create a target type
final List<TargetType> targetTypes = testdataFactory.createTargetTypes("targettype", 2);
@@ -880,9 +910,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFound2.get().getTargetType()).isNull();
}
/**
* Checks that target type to a target can be assigned.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that target type to a target can be assigned.")
void assignTargetTypeInTarget() {
// create a target
final Target target = testdataFactory.createTarget("target1", "testtarget");
@@ -906,9 +938,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFound1.get().getTargetType().getId()).isEqualTo(targetType.getId());
}
/**
* Tests the assignment of types to multiple targets.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Tests the assignment of types to multiple targets.")
@ExpectEvents({
@Expect(type = TargetCreatedEvent.class, count = 20),
@Expect(type = TargetTypeCreatedEvent.class, count = 2),
@@ -949,9 +983,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
checkTargetsHaveType(typeATargets, typeB);
}
/**
* Checks that target type is not assigned to target if invalid.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that target type is not assigned to target if invalid.")
void assignInvalidTargetTypeToTarget() {
// create a target
final Target target = testdataFactory.createTarget("target1", "testtarget");
@@ -977,9 +1013,11 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFound1.get().getOptLockRevision()).isEqualTo(1);
}
/**
* Checks that target type can be unassigned from target.
*/
@Test
@WithUser(allSpPermissions = true)
@Description("Checks that target type can be unassigned from target.")
void unAssignTargetTypeFromTarget() {
// create a target type
final TargetType targetType = testdataFactory.findOrCreateTargetType("targettype");
@@ -1002,9 +1040,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetFound1.get().getTargetType()).isNull();
}
@Test
@Description("Test that RSQL filter finds targets with metadata and/or controllerId.")
void findTargetsByRsqlWithMetadata() {
/**
* Test that RSQL filter finds targets with metadata and/or controllerId.
*/
@Test void findTargetsByRsqlWithMetadata() {
final String controllerId1 = "target1";
final String controllerId2 = "target2";
createTargetWithMetadata(controllerId1, 2);
@@ -1026,9 +1065,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
validateFoundTargetsByRsql(rsqlOrControllerIdNotEqualFilter, controllerId1, controllerId2);
}
@Test
@Description("Test that RSQL filter finds targets with tag and metadata.")
void findTargetsByRsqlWithTypeAndMetadata() {
/**
* Test that RSQL filter finds targets with tag and metadata.
*/
@Test void findTargetsByRsqlWithTypeAndMetadata() {
if (RsqlConfigHolder.getInstance().getRsqlToSpecBuilder() == LEGACY_G1) {
// legacy visitor fail with that
return;
@@ -1048,9 +1088,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
validateFoundTargetsByRsql(rsqlAndControllerIdFilter);
}
@Test
@Description("Target matches filter.")
void matchesFilter() {
/**
* Target matches filter.
*/
@Test void matchesFilter() {
final Target target = createTargetWithMetadata("target1", 2);
final DistributionSet ds = testdataFactory.createDistributionSet();
final String filter = "metadata.key1==target1-value1";
@@ -1059,9 +1100,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
ds.getId(), filter)).isTrue();
}
@Test
@Description("Target does not matches filter.")
void matchesFilterWrongFilter() {
/**
* Target does not matches filter.
*/
@Test void matchesFilterWrongFilter() {
final Target target = testdataFactory.createTarget();
final DistributionSet ds = testdataFactory.createDistributionSet();
final String filter = "metadata.key==not_existing";
@@ -1070,9 +1112,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
ds.getId(), filter)).isFalse();
}
@Test
@Description("Target matches filter but DS already assigned.")
void matchesFilterDsAssigned() {
/**
* Target matches filter but DS already assigned.
*/
@Test void matchesFilterDsAssigned() {
final Target target = testdataFactory.createTarget();
final DistributionSet ds1 = testdataFactory.createDistributionSet();
final DistributionSet ds2 = testdataFactory.createDistributionSet();
@@ -1084,9 +1127,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
ds1.getId(), filter)).isFalse();
}
@Test
@Description("Target matches filter for DS with wrong type.")
void matchesFilterWrongType() {
/**
* Target matches filter for DS with wrong type.
*/
@Test void matchesFilterWrongType() {
final TargetType type = testdataFactory.createTargetType("type", Collections.emptyList());
final Target target = testdataFactory.createTarget("target", "target", type.getId());
final DistributionSet ds = testdataFactory.createDistributionSet();
@@ -1095,9 +1139,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
ds.getId(), "name==*")).isFalse();
}
@Test
@Description("Target matches filter that is invalid.")
void matchesFilterInvalidFilter() {
/**
* Target matches filter that is invalid.
*/
@Test void matchesFilterInvalidFilter() {
final String target = testdataFactory.createTarget().getControllerId();
final Long ds = testdataFactory.createDistributionSet().getId();
@@ -1107,9 +1152,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatable(target, ds, "invalid_field==1"));
}
@Test
@Description("Target matches filter for not existing target.")
void matchesFilterTargetNotExists() {
/**
* Target matches filter for not existing target.
*/
@Test void matchesFilterTargetNotExists() {
final DistributionSet ds = testdataFactory.createDistributionSet();
assertThat(targetManagement.isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatable(
@@ -1119,9 +1165,10 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
/**
* Tests action based aspects of the dynamic group assignment filters.
*/
@Test
@Description("Target matches filter no active action with ge weight.")
void findByTargetFilterQueryAndNoOverridingActionsAndNotInRolloutAndCompatibleAndUpdatable() {
/**
* Target matches filter no active action with ge weight.
*/
@Test void findByTargetFilterQueryAndNoOverridingActionsAndNotInRolloutAndCompatibleAndUpdatable() {
final String targetPrefix = "dyn_action_filter_";
final DistributionSet distributionSet = testdataFactory.createDistributionSet();
final List<Target> targets = testdataFactory.createTargets(targetPrefix, 10);
@@ -1170,18 +1217,20 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.toList()).isEqualTo(expected);
}
@Test
@Description("Target matches filter for not existing DS.")
void matchesFilterDsNotExists() {
/**
* Target matches filter for not existing DS.
*/
@Test void matchesFilterDsNotExists() {
final String target = testdataFactory.createTarget().getControllerId();
assertThatExceptionOfType(EntityNotFoundException.class).isThrownBy(
() -> targetManagement.isTargetMatchingQueryAndDSNotAssignedAndCompatibleAndUpdatable(target, 123, "name==*"));
}
@Test
@Description("Test update status convert")
void testUpdateStatusConvert() {
/**
* Test update status convert
*/
@Test void testUpdateStatusConvert() {
final long id = testdataFactory.createTarget().getId();
for (final TargetUpdateStatus status : TargetUpdateStatus.values()) {
final JpaTarget target = targetRepository.findById(id).orElseThrow(() -> new IllegalStateException("Target not found"));
@@ -1192,7 +1241,6 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
}
@Step
private void createAndUpdateTargetWithInvalidDescription(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.description(randomString(513));
@@ -1217,7 +1265,6 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.update(targetUpdateInvalidHtml));
}
@Step
private void createAndUpdateTargetWithInvalidName(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
@@ -1248,7 +1295,6 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
}
@Step
private void createAndUpdateTargetWithInvalidSecurityToken(final Target target) {
final TargetCreate targetCreateTooLong = entityFactory.target().create().controllerId("a")
.securityToken(randomString(Target.SECURITY_TOKEN_MAX_SIZE + 1));
@@ -1278,7 +1324,6 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetManagement.update(targetUpdateEmpty));
}
@Step
private void createAndUpdateTargetWithInvalidAddress(final Target target) {
final TargetCreate targetCreate = entityFactory.target().create().controllerId("a").address(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -1301,7 +1346,6 @@ class TargetManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetUpdate2.address(INVALID_TEXT_HTML));
}
@Step
private void createTargetWithInvalidControllerId() {
final TargetCreate targetCreateEmpty = entityFactory.target().create().controllerId("");
assertThatExceptionOfType(ConstraintViolationException.class)

View File

@@ -11,80 +11,89 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - TargetTagManagement")
@Story("SecurityTests TargetTagManagement")
/**
* Feature: SecurityTests - TargetTagManagement<br/>
* Story: SecurityTests TargetTagManagement
*/
class TargetTagManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countPermissionsCheck() {
assertPermissions(() -> targetTagManagement.count(), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionsCheck() {
assertPermissions(() -> targetTagManagement.create(entityFactory.tag().create().name("name")), List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createCollectionPermissionsCheck() {
assertPermissions(() -> targetTagManagement.create(List.of(entityFactory.tag().create().name("name"))),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionsCheck() {
assertPermissions(() -> {
targetTagManagement.delete("tag");
return null;
}, List.of(SpPermission.DELETE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllPermissionsCheck() {
assertPermissions(() -> targetTagManagement.findAll(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlPermissionsCheck() {
assertPermissions(() -> targetTagManagement.findByRsql("name==tag", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNamePermissionsCheck() {
assertPermissions(() -> targetTagManagement.getByName("tag"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> targetTagManagement.get(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getCollectionPermissionsCheck() {
assertPermissions(() -> targetTagManagement.get(List.of(1L)), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionsCheck() {
assertPermissions(() -> targetTagManagement.update(entityFactory.tag().update(1L)), List.of(SpPermission.UPDATE_TARGET));
}
}

View File

@@ -22,10 +22,6 @@ import java.util.Random;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.TargetTagManagement;
import org.eclipse.hawkbit.repository.builder.TagCreate;
import org.eclipse.hawkbit.repository.builder.TagUpdate;
@@ -47,16 +43,18 @@ import org.springframework.data.domain.Pageable;
/**
* Test class for {@link TargetTagManagement}.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Target Tag Management
*/
@Feature("Component Tests - Repository")
@Story("Target Tag Management")
class TargetTagManagementTest extends AbstractJpaIntegrationTest {
private static final Random RND = new Random();
@Test
@Description("Verifies that tagging of set containing missing DS throws meaningful and correct exception.")
void failOnMissingDs() {
/**
* Verifies that tagging of set containing missing DS throws meaningful and correct exception.
*/
@Test void failOnMissingDs() {
final Collection<String> group = testdataFactory.createTargets(5).stream()
.map(Target::getControllerId)
.toList();
@@ -85,18 +83,22 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
});
}
/**
* Verifies that management get access reacts as specfied on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access reacts as specfied on calls for non existing entities by means " +
"of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(targetTagManagement.getByName(NOT_EXIST_ID)).isNotPresent();
assertThat(targetTagManagement.get(NOT_EXIST_IDL)).isNotPresent();
}
/**
* Verifies that management queries react as specfied on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specfied on calls for non existing entities " +
" by means of throwing EntityNotFoundException.")
@ExpectEvents({
@Expect(type = DistributionSetTagUpdatedEvent.class),
@Expect(type = TargetTagUpdatedEvent.class) })
@@ -106,18 +108,20 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
verifyThrownExceptionBy(() -> getTargetTags(NOT_EXIST_ID), "Target");
}
@Test
@Description("Verify that a tag with with invalid properties cannot be created or updated")
void createAndUpdateTagWithInvalidFields() {
/**
* Verify that a tag with with invalid properties cannot be created or updated
*/
@Test void createAndUpdateTagWithInvalidFields() {
final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("tag1").description("tagdesc1"));
createAndUpdateTagWithInvalidDescription(tag);
createAndUpdateTagWithInvalidColour(tag);
createAndUpdateTagWithInvalidName(tag);
}
@Test
@Description("Verifies assign/unassign.")
void assignAndUnassignTargetTags() {
/**
* Verifies assign/unassign.
*/
@Test void assignAndUnassignTargetTags() {
final List<Target> groupA = testdataFactory.createTargets(20);
final List<Target> groupB = testdataFactory.createTargets(20, "groupb", "groupb");
@@ -152,18 +156,20 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetManagement.findByTag(tag.getId(), Pageable.unpaged()).getContent()).isEmpty();
}
@Test
@Description("Ensures that all tags are retrieved through repository.")
void findAllTargetTags() {
/**
* Ensures that all tags are retrieved through repository.
*/
@Test void findAllTargetTags() {
final List<JpaTargetTag> tags = createTargetsWithTags();
assertThat(targetTagRepository.findAll()).isEqualTo(targetTagRepository.findAll()).isEqualTo(tags)
.as("Wrong tag size").hasSize(20);
}
@Test
@Description("Ensures that a created tag is persisted in the repository as defined.")
void createTargetTag() {
/**
* Ensures that a created tag is persisted in the repository as defined.
*/
@Test void createTargetTag() {
final Tag tag = targetTagManagement
.create(entityFactory.tag().create().name("kai1").description("kai2").colour("colour"));
@@ -173,9 +179,10 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetTagManagement.get(tag.getId()).get().getColour()).as("wrong tag found").isEqualTo("colour");
}
@Test
@Description("Ensures that a deleted tag is removed from the repository as defined.")
void deleteTargetTags() {
/**
* Ensures that a deleted tag is removed from the repository as defined.
*/
@Test void deleteTargetTags() {
// create test data
final Iterable<JpaTargetTag> tags = createTargetsWithTags();
final TargetTag toDelete = tags.iterator().next();
@@ -196,9 +203,10 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetTagRepository.findAll()).as("Wrong target tag size").hasSize(19);
}
@Test
@Description("Tests the name update of a target tag.")
void updateTargetTag() {
/**
* Tests the name update of a target tag.
*/
@Test void updateTargetTag() {
final List<JpaTargetTag> tags = createTargetsWithTags();
// change data
@@ -216,17 +224,19 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo(2);
}
@Test
@Description("Ensures that a tag cannot be created if one exists already with that name (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTagNameException() {
/**
* Ensures that a tag cannot be created if one exists already with that name (expects EntityAlreadyExistsException).
*/
@Test void failedDuplicateTargetTagNameException() {
final TagCreate tagCreate = entityFactory.tag().create().name("A");
targetTagManagement.create(tagCreate);
assertThatExceptionOfType(EntityAlreadyExistsException.class).isThrownBy(() -> targetTagManagement.create(tagCreate));
}
@Test
@Description("Ensures that a tag cannot be updated to a name that already exists on another tag (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTagNameExceptionAfterUpdate() {
/**
* Ensures that a tag cannot be updated to a name that already exists on another tag (expects EntityAlreadyExistsException).
*/
@Test void failedDuplicateTargetTagNameExceptionAfterUpdate() {
targetTagManagement.create(entityFactory.tag().create().name("A"));
final TargetTag tag = targetTagManagement.create(entityFactory.tag().create().name("B"));
@@ -234,7 +244,6 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
assertThatExceptionOfType(EntityAlreadyExistsException.class).isThrownBy(() -> targetTagManagement.update(tagUpdate));
}
@Step
private void createAndUpdateTagWithInvalidDescription(final Tag tag) {
final TagCreate tagCraeteTooLong = entityFactory.tag().create().name("a").description(randomString(513));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -254,7 +263,6 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetTagManagement.update(tagUpdateInvalidHtml));
}
@Step
private void createAndUpdateTagWithInvalidColour(final Tag tag) {
final TagCreate tagCreateTooLong = entityFactory.tag().create().name("a").colour(randomString(17));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -275,7 +283,6 @@ class TargetTagManagementTest extends AbstractJpaIntegrationTest {
.update(tagUpdateInvalidHtml));
}
@Step
private void createAndUpdateTagWithInvalidName(final Tag tag) {
final TagCreate tagCreateTooLong = entityFactory.tag().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class)

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -21,103 +18,120 @@ import org.eclipse.hawkbit.repository.test.util.WithUser;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - TargetTypeManagement")
@Story("SecurityTests TargetTypeManagement")
/**
* Feature: SecurityTests - TargetTypeManagement<br/>
* Story: SecurityTests TargetTypeManagement
*/
class TargetTypeManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByKeyPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByKeyPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.getByKey("key"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getByNamePermissionsCheck() {
assertPermissions(() -> targetTypeManagement.getByName("name"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.count(), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void countByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void countByNamePermissionsCheck() {
assertPermissions(() -> targetTypeManagement.countByName("name"), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.create(entityFactory.targetType().create().name("name")),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void createCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void createCollectionPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.create(List.of(entityFactory.targetType().create().name("name"))),
List.of(SpPermission.CREATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deletePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deletePermissionsCheck() {
assertPermissions(() -> {
targetTypeManagement.delete(1L);
return null;
}, List.of(SpPermission.DELETE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findAllPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findAllPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.findAll(PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByRsqlPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByRsqlPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.findByRsql("name==tag", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void findByNamePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void findByNamePermissionsCheck() {
assertPermissions(() -> targetTypeManagement.findByName("name", PAGE), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.get(1L), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getCollectionPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getCollectionPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.get(List.of(1L)), List.of(SpPermission.READ_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void updatePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void updatePermissionsCheck() {
assertPermissions(() -> targetTypeManagement.update(entityFactory.targetType().update(1L)), List.of(SpPermission.UPDATE_TARGET));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void assignCompatibleDistributionSetTypesPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void assignCompatibleDistributionSetTypesPermissionsCheck() {
assertPermissions(() -> targetTypeManagement.assignCompatibleDistributionSetTypes(1L, List.of(1L)),
List.of(SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
@WithUser(principal = "user", authorities = { SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY })
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test @WithUser(principal = "user", authorities = { SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY })
void unassignDistributionSetTypePermissionsCheck() {
assertPermissions(() -> targetTypeManagement.unassignDistributionSetType(1L, 1L),
List.of(SpPermission.UPDATE_TARGET, SpPermission.READ_REPOSITORY));

View File

@@ -18,10 +18,6 @@ import java.util.Optional;
import jakarta.validation.ConstraintViolationException;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Step;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.builder.TargetTypeCreate;
import org.eclipse.hawkbit.repository.builder.TargetTypeUpdate;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetTypeCreatedEvent;
@@ -37,22 +33,28 @@ import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.junit.jupiter.api.Test;
@Feature("Component Tests - Repository")
@Story("Target Type Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Target Type Management
*/
class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
/**
* Verifies that management get access react as specified on calls for non existing entities by means
* of Optional not present.
*/
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetTypeCreatedEvent.class) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(targetTypeManagement.get(NOT_EXIST_IDL)).isNotPresent();
assertThat(targetTypeManagement.getByName(NOT_EXIST_ID)).isNotPresent();
}
/**
* Verifies that management queries react as specified on calls for non existing entities
* by means of throwing EntityNotFoundException.
*/
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = TargetTypeUpdatedEvent.class) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
verifyThrownExceptionBy(() -> targetTypeManagement.delete(NOT_EXIST_IDL), "TargetType");
@@ -60,9 +62,10 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
"TargetType");
}
@Test
@Description("Verify that a target type with invalid properties cannot be created or updated")
void createAndUpdateTargetTypeWithInvalidFields() {
/**
* Verify that a target type with invalid properties cannot be created or updated
*/
@Test void createAndUpdateTargetTypeWithInvalidFields() {
final TargetType targetType = targetTypeManagement
.create(entityFactory.targetType().create()
.name("targettype1").description("targettypedes1")
@@ -74,7 +77,6 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
createAndUpdateTargetTypeWithInvalidName(targetType);
}
@Step
void createAndUpdateTargetTypeWithInvalidDescription(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name("a").description(randomString(TargetType.DESCRIPTION_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -98,9 +100,10 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateInvalidHtml));
}
@Test
@Description("Tests the successful assignment of compatible distribution set types to a target type")
void assignCompatibleDistributionSetTypesToTargetType() {
/**
* Tests the successful assignment of compatible distribution set types to a target type
*/
@Test void assignCompatibleDistributionSetTypesToTargetType() {
final TargetType targetType = targetTypeManagement
.create(entityFactory.targetType().create()
.name("targettype1").description("targettypedes1")
@@ -113,9 +116,10 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetTypeWithDsTypes.get().getCompatibleDistributionSetTypes()).extracting("key").contains("testDst");
}
@Test
@Description("Tests the successful removal of compatible distribution set types to a target type")
void unassignCompatibleDistributionSetTypesToTargetType() {
/**
* Tests the successful removal of compatible distribution set types to a target type
*/
@Test void unassignCompatibleDistributionSetTypesToTargetType() {
final TargetType targetType = targetTypeManagement
.create(entityFactory.targetType().create()
.name("targettype1").description("targettypedes1")
@@ -131,16 +135,18 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(targetTypeWithDsTypes1.get().getCompatibleDistributionSetTypes()).isEmpty();
}
@Test
@Description("Ensures that all types are retrieved through repository.")
void findAllTargetTypes() {
/**
* Ensures that all types are retrieved through repository.
*/
@Test void findAllTargetTypes() {
testdataFactory.createTargetTypes("targettype", 10);
assertThat(targetTypeRepository.findAll()).as("Target type size").hasSize(10);
}
@Test
@Description("Ensures that a created target type is persisted in the repository as defined.")
void createTargetType() {
/**
* Ensures that a created target type is persisted in the repository as defined.
*/
@Test void createTargetType() {
final String name = "targettype1";
final String key = "targettype1.key";
targetTypeManagement
@@ -168,9 +174,10 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
.isEqualTo("colour1");
}
@Test
@Description("Ensures that a deleted target type is removed from the repository as defined.")
void deleteTargetType() {
/**
* Ensures that a deleted target type is removed from the repository as defined.
*/
@Test void deleteTargetType() {
// create test data
final TargetType targetType = targetTypeManagement
.create(entityFactory.targetType().create().name("targettype11").description("targettypedes11"));
@@ -181,9 +188,10 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Tests the name update of a target type.")
void updateTargetType() {
/**
* Tests the name update of a target type.
*/
@Test void updateTargetType() {
final TargetType targetType = targetTypeManagement
.create(entityFactory.targetType().create().name("targettype111").description("targettypedes111"));
assertThat(findByName("targettype111").get().getDescription()).as("type found")
@@ -192,24 +200,25 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
assertThat(findByName("updatedtargettype111")).as("Updated target type should be found").isPresent();
}
@Test
@Description("Ensures that a target type cannot be created if one exists already with that name (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTypeNameException() {
/**
* Ensures that a target type cannot be created if one exists already with that name (expects EntityAlreadyExistsException).
*/
@Test void failedDuplicateTargetTypeNameException() {
final TargetTypeCreate targetTypeCreate = entityFactory.targetType().create().name("targettype123");
targetTypeManagement.create(targetTypeCreate);
assertThrows(EntityAlreadyExistsException.class, () -> targetTypeManagement.create(targetTypeCreate));
}
@Test
@Description("Ensures that a target type cannot be updated to a name that already exists (expects EntityAlreadyExistsException).")
void failedDuplicateTargetTypeNameExceptionAfterUpdate() {
/**
* Ensures that a target type cannot be updated to a name that already exists (expects EntityAlreadyExistsException).
*/
@Test void failedDuplicateTargetTypeNameExceptionAfterUpdate() {
targetTypeManagement.create(entityFactory.targetType().create().name("targettype1234"));
TargetType targetType = targetTypeManagement.create(entityFactory.targetType().create().name("targettype12345"));
assertThrows(EntityAlreadyExistsException.class,
() -> targetTypeManagement.update(entityFactory.targetType().update(targetType.getId()).name("targettype1234")));
}
@Step
private void createAndUpdateTargetTypeWithInvalidColour(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name("a").colour(randomString(Type.COLOUR_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -232,7 +241,6 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetTypeManagement.update(targetTypeUpdateInvalidHtml));
}
@Step
private void createTargetTypeWithInvalidKey() {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name(randomString(Type.KEY_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class)
@@ -245,7 +253,6 @@ class TargetTypeManagementTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> targetTypeManagement.create(targetTypeCreateInvalidHtmle));
}
@Step
private void createAndUpdateTargetTypeWithInvalidName(final TargetType targetType) {
final TargetTypeCreate targetTypeCreateTooLong = entityFactory.targetType().create().name(randomString(NamedEntity.NAME_MAX_SIZE + 1));
assertThatExceptionOfType(ConstraintViolationException.class)

View File

@@ -12,66 +12,72 @@ package org.eclipse.hawkbit.repository.jpa.management;
import java.util.List;
import java.util.Map;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.hawkbit.im.authentication.SpPermission;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.Test;
@Slf4j
@Feature("SecurityTests - TargetManagement")
@Story("SecurityTests TargetManagement")
/**
* Feature: SecurityTests - TargetManagement<br/>
* Story: SecurityTests TargetManagement
*/
class TenantConfigurationManagementSecurityTest extends AbstractJpaIntegrationTest {
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void addOrUpdateConfigurationPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void addOrUpdateConfigurationPermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.addOrUpdateConfiguration("authentication.header.enabled", true),
List.of(SpPermission.TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void addOrUpdateConfigurationWithMapPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void addOrUpdateConfigurationWithMapPermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.addOrUpdateConfiguration(Map.of("authentication.header.enabled", true)),
List.of(SpPermission.TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void deleteConfigurationPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void deleteConfigurationPermissionsCheck() {
assertPermissions(() -> {
tenantConfigurationManagement.deleteConfiguration("authentication.header.enabled");
return null;
}, List.of(SpPermission.TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getConfigurationValuePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getConfigurationValuePermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.getConfigurationValue("authentication.header.enabled"),
List.of(SpPermission.READ_TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getConfigurationValueWithTypePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getConfigurationValueWithTypePermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.getConfigurationValue("authentication.header.enabled", Boolean.class),
List.of(SpPermission.READ_TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void getGlobalConfigurationValuePermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void getGlobalConfigurationValuePermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.getGlobalConfigurationValue("authentication.header.enabled", Boolean.class),
List.of(SpPermission.READ_TENANT_CONFIGURATION));
}
@Test
@Description("Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.")
void pollStatusResolverPermissionsCheck() {
/**
* Tests ManagementAPI PreAuthorized method with correct and insufficient permissions.
*/
@Test void pollStatusResolverPermissionsCheck() {
assertPermissions(() -> tenantConfigurationManagement.pollStatusResolver(), List.of(SpPermission.READ_TARGET));
}
}

View File

@@ -18,9 +18,6 @@ import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.InvalidTenantConfigurationKeyException;
import org.eclipse.hawkbit.repository.exception.TenantConfigurationValidatorException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -31,8 +28,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
@Feature("Component Tests - Repository")
@Story("Tenant Configuration Management")
/**
* Feature: Component Tests - Repository<br/>
* Story: Tenant Configuration Management
*/
class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest implements EnvironmentAware {
private Environment environment;
@@ -42,9 +41,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
this.environment = environment;
}
@Test
@Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.")
void storeTenantSpecificConfigurationAsString() {
/**
* Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.
*/
@Test void storeTenantSpecificConfigurationAsString() {
final String envPropertyDefault = environment.getProperty("hawkbit.server.ddi.security.authentication.gatewaytoken.key");
assertThat(envPropertyDefault).isNotNull();
@@ -70,9 +70,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
// assertThat(tenantConfigurationManagement.getTenantConfigurations()).hasSize(1);
}
@Test
@Description("Tests that the tenant specific configuration can be updated")
void updateTenantSpecificConfiguration() {
/**
* Tests that the tenant specific configuration can be updated
*/
@Test void updateTenantSpecificConfiguration() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
final String value1 = "firstValue";
final String value2 = "secondValue";
@@ -86,9 +87,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
assertThat(tenantConfigurationManagement.getConfigurationValue(configKey, String.class).getValue()).isEqualTo(value2);
}
@Test
@Description("Tests that the tenant specific configuration can be batch updated")
void batchUpdateTenantSpecificConfiguration() {
/**
* Tests that the tenant specific configuration can be batch updated
*/
@Test void batchUpdateTenantSpecificConfiguration() {
Map<String, Serializable> configuration = new HashMap<>() {{
put(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, "token_123");
put(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, true);
@@ -104,9 +106,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isTrue();
}
@Test
@Description("Tests that the configuration value can be converted from String to Integer automatically")
void storeAndUpdateTenantSpecificConfigurationAsBoolean() {
/**
* Tests that the configuration value can be converted from String to Integer automatically
*/
@Test void storeAndUpdateTenantSpecificConfigurationAsBoolean() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
final Boolean value1 = true;
tenantConfigurationManagement.addOrUpdateConfiguration(configKey, value1);
@@ -116,9 +119,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
assertThat(tenantConfigurationManagement.getConfigurationValue(configKey, Boolean.class).getValue()).isEqualTo(value2);
}
@Test
@Description("Tests that the get configuration throws exception in case the value cannot be automatically converted from String to Boolean")
void wrongTenantConfigurationValueTypeThrowsException() {
/**
* Tests that the get configuration throws exception in case the value cannot be automatically converted from String to Boolean
*/
@Test void wrongTenantConfigurationValueTypeThrowsException() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
final String value1 = "thisIsNotABoolean";
@@ -128,9 +132,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Tests that the get configuration throws exception in case the value is the wrong type")
void batchWrongTenantConfigurationValueTypeThrowsException() {
/**
* Tests that the get configuration throws exception in case the value is the wrong type
*/
@Test void batchWrongTenantConfigurationValueTypeThrowsException() {
final Map<String, Serializable> configuration = new HashMap<>() {{
put(TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY, "token_123");
put(TenantConfigurationKey.ROLLOUT_APPROVAL_ENABLED, true);
@@ -152,9 +157,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
}
}
@Test
@Description("Tests that a deletion of a tenant specific configuration deletes it from the database.")
void deleteConfigurationReturnNullConfiguration() {
/**
* Tests that a deletion of a tenant specific configuration deletes it from the database.
*/
@Test void deleteConfigurationReturnNullConfiguration() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
// gateway token does not have default value so no configuration value should be available
@@ -177,9 +183,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
assertThat(tenantConfigurationManagement.getConfigurationValue(configKey, String.class).getValue()).isEmpty();
}
@Test
@Description("Test that an Exception is thrown, when an integer is stored but a string expected.")
void storesIntegerWhenStringIsExpected() {
/**
* Test that an Exception is thrown, when an integer is stored but a string expected.
*/
@Test void storesIntegerWhenStringIsExpected() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
final Integer wrongDatType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDatType))
@@ -187,9 +194,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Test that an Exception is thrown, when an integer is stored but a boolean expected.")
void storesIntegerWhenBooleanIsExpected() {
/**
* Test that an Exception is thrown, when an integer is stored but a boolean expected.
*/
@Test void storesIntegerWhenBooleanIsExpected() {
final String configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED;
final Integer wrongDataType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataType))
@@ -197,9 +205,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Test that an Exception is thrown, when an integer is stored as PollingTime.")
void storesIntegerWhenPollingIntervalIsExpected() {
/**
* Test that an Exception is thrown, when an integer is stored as PollingTime.
*/
@Test void storesIntegerWhenPollingIntervalIsExpected() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final Integer wrongDataType = 123;
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataType))
@@ -207,9 +216,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.")
void storesWrongFormattedStringAsPollingInterval() {
/**
* Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.
*/
@Test void storesWrongFormattedStringAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final String wrongFormatted = "wrongFormatted";
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongFormatted))
@@ -217,9 +227,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.")
void storesTooSmallDurationAsPollingInterval() {
/**
* Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.
*/
@Test void storesTooSmallDurationAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final String tooSmallDuration = DurationHelper
@@ -229,9 +240,10 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Stores a correct formatted PollignTime and reads it again.")
void storesCorrectDurationAsPollingInterval() {
/**
* Stores a correct formatted PollignTime and reads it again.
*/
@Test void storesCorrectDurationAsPollingInterval() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
final Duration duration = DurationHelper.getDurationByTimeValues(1, 2, 0);
@@ -243,17 +255,19 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
assertThat(duration).isEqualTo(DurationHelper.formattedStringToDuration(storedDurationString));
}
@Test
@Description("Request a config value in a wrong Value")
void requestConfigValueWithWrongType() {
/**
* Request a config value in a wrong Value
*/
@Test void requestConfigValueWithWrongType() {
assertThatThrownBy(() -> tenantConfigurationManagement.getConfigurationValue(
TenantConfigurationKey.POLLING_TIME_INTERVAL, Serializable.class))
.isInstanceOf(TenantConfigurationValidatorException.class);
}
@Test
@Description("Verifies that every TenenatConfiguraationKeyName exists only once")
void verifyThatAllKeysAreDifferent() {
/**
* Verifies that every TenenatConfiguraationKeyName exists only once
*/
@Test void verifyThatAllKeysAreDifferent() {
final Map<String, Void> keyNames = new HashMap<>();
tenantConfigurationProperties.getConfigurationKeys().forEach(key -> {
assertThat(keyNames)
@@ -263,16 +277,18 @@ class TenantConfigurationManagementTest extends AbstractJpaIntegrationTest imple
});
}
@Test
@Description("Get TenantConfigurationKeyByName")
void getTenantConfigurationKeyByName() {
/**
* Get TenantConfigurationKeyByName
*/
@Test void getTenantConfigurationKeyByName() {
final String configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL;
assertThat(tenantConfigurationProperties.fromKeyName(configKey).getKeyName()).isEqualTo(configKey);
}
@Test
@Description("Tenant configuration which is not declared throws exception")
void storeTenantConfigurationWhichIsNotDeclaredThrowsException() {
/**
* Tenant configuration which is not declared throws exception
*/
@Test void storeTenantConfigurationWhichIsNotDeclaredThrowsException() {
final String configKeyWhichDoesNotExists = "configKeyWhichDoesNotExists";
assertThatThrownBy(() -> tenantConfigurationManagement.addOrUpdateConfiguration(configKeyWhichDoesNotExists, "value"))
.as("Expected InvalidTenantConfigurationKeyException for tenant configuration key which is not declared")

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.model;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.jpa.EntityInterceptor;
import org.eclipse.hawkbit.repository.jpa.model.helper.EntityInterceptorHolder;
@@ -24,9 +21,10 @@ import org.junit.jupiter.api.Test;
/**
* Test the entity listener interceptor.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Entity Listener Interceptor
*/
@Feature("Component Tests - Repository")
@Story("Entity Listener Interceptor")
class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
@AfterEach
@@ -34,21 +32,24 @@ class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
EntityInterceptorHolder.getInstance().getEntityInterceptors().clear();
}
@Test
@Description("Verifies that the pre persist is called after a entity creation.")
void prePersistIsCalledWhenPersistingATarget() {
/**
* Verifies that the pre persist is called after a entity creation.
*/
@Test void prePersistIsCalledWhenPersistingATarget() {
executePersistAndAssertCallbackResult(new PrePersistEntityListener());
}
@Test
@Description("Verifies that the post persist is called after a entity creation.")
void postPersistIsCalledWhenPersistingATarget() {
/**
* Verifies that the post persist is called after a entity creation.
*/
@Test void postPersistIsCalledWhenPersistingATarget() {
executePersistAndAssertCallbackResult(new PostPersistEntityListener());
}
@Test
@Description("Verifies that the post load is called after a entity is loaded.")
void postLoadIsCalledWhenLoadATarget() {
/**
* Verifies that the post load is called after a entity is loaded.
*/
@Test void postLoadIsCalledWhenLoadATarget() {
final PostLoadEntityListener postLoadEntityListener = new PostLoadEntityListener();
EntityInterceptorHolder.getInstance().getEntityInterceptors().add(postLoadEntityListener);
@@ -59,27 +60,31 @@ class EntityInterceptorListenerTest extends AbstractJpaIntegrationTest {
assertThat(postLoadEntityListener.getEntity()).isEqualTo(loadedTarget);
}
@Test
@Description("Verifies that the pre update is called after a entity update.")
void preUpdateIsCalledWhenUpdateATarget() {
/**
* Verifies that the pre update is called after a entity update.
*/
@Test void preUpdateIsCalledWhenUpdateATarget() {
executeUpdateAndAssertCallbackResult(new PreUpdateEntityListener());
}
@Test
@Description("Verifies that the post update is called after a entity update.")
void postUpdateIsCalledWhenUpdateATarget() {
/**
* Verifies that the post update is called after a entity update.
*/
@Test void postUpdateIsCalledWhenUpdateATarget() {
executeUpdateAndAssertCallbackResult(new PostUpdateEntityListener());
}
@Test
@Description("Verifies that the pre remove is called after a entity deletion.")
void preRemoveIsCalledWhenDeletingATarget() {
/**
* Verifies that the pre remove is called after a entity deletion.
*/
@Test void preRemoveIsCalledWhenDeletingATarget() {
executeDeleteAndAssertCallbackResult(new PreRemoveEntityListener());
}
@Test
@Description("Verifies that the post remove is called after a entity deletion.")
void postRemoveIsCalledWhenDeletingATarget() {
/**
* Verifies that the post remove is called after a entity deletion.
*/
@Test void postRemoveIsCalledWhenDeletingATarget() {
executeDeleteAndAssertCallbackResult(new PostRemoveEntityListener());
}

View File

@@ -11,20 +11,20 @@ package org.eclipse.hawkbit.repository.jpa.model;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.junit.jupiter.api.Test;
@Feature("Unit Tests - Repository")
@Story("Repository Model")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Repository Model
*/
class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
@Test
@Description("Verifies that different objects even with identical primary key, version and tenant return different hash codes.")
void differentEntitiesReturnDifferentHashCodes() {
/**
* Verifies that different objects even with identical primary key, version and tenant return different hash codes.
*/
@Test void differentEntitiesReturnDifferentHashCodes() {
assertThat(new JpaAction().hashCode()).as("action should have different hashcode than action status")
.isNotEqualTo(new JpaActionStatus().hashCode());
assertThat(new JpaDistributionSet().hashCode())
@@ -38,9 +38,10 @@ class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
.isNotEqualTo(new JpaActionStatus().hashCode());
}
@Test
@Description("Verifies that different object even with identical primary key, version and tenant are not equal.")
void differentEntitiesAreNotEqual() {
/**
* Verifies that different object even with identical primary key, version and tenant are not equal.
*/
@Test void differentEntitiesAreNotEqual() {
assertThat(new JpaAction().equals(new JpaActionStatus())).as("action equals action status").isFalse();
assertThat(new JpaDistributionSet().equals(new JpaSoftwareModule()))
.as("Distribution set equals software module").isFalse();
@@ -50,9 +51,10 @@ class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
.as("Distribution set type equals action status").isFalse();
}
@Test
@Description("Verifies that updated entities are not equal.")
void changedEntitiesAreNotEqual() {
/**
* Verifies that updated entities are not equal.
*/
@Test void changedEntitiesAreNotEqual() {
final SoftwareModuleType type = softwareModuleTypeManagement
.create(entityFactory.softwareModuleType().create().key("test").name("test"));
assertThat(type).as("persited entity is not equal to regular object")
@@ -63,9 +65,10 @@ class ModelEqualsHashcodeTest extends AbstractJpaIntegrationTest {
assertThat(type).as("Changed entity is not equal to the previous version").isNotEqualTo(updated);
}
@Test
@Description("Verify that no proxy of the entity manager has an influence on the equals or hashcode result.")
void managedEntityIsEqualToUnamangedObjectWithSameKey() {
/**
* Verify that no proxy of the entity manager has an influence on the equals or hashcode result.
*/
@Test void managedEntityIsEqualToUnamangedObjectWithSameKey() {
final SoftwareModuleType type = softwareModuleTypeManagement.create(
entityFactory.softwareModuleType().create().key("test").name("test").description("test"));

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.ActionFields;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -30,8 +27,10 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice;
import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter actions")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter actions
*/
class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
private JpaTarget target;
@@ -49,9 +48,10 @@ class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Test filter action by id")
void testFilterByParameterId() {
/**
* Test filter action by id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(ActionFields.ID.name() + "==" + action.getId(), 1);
assertRSQLQuery(ActionFields.ID.name() + "!=" + action.getId(), 10);
assertRSQLQuery(ActionFields.ID.name() + "==" + -1, 0);
@@ -66,9 +66,10 @@ class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(ActionFields.ID.name() + "=out=(" + action.getId() + ",10000000)", 10);
}
@Test
@Description("Test action by status")
void testFilterByParameterStatus() {
/**
* Test action by status
*/
@Test void testFilterByParameterStatus() {
assertRSQLQuery(ActionFields.STATUS.name() + "==pending", 5);
assertRSQLQuery(ActionFields.STATUS.name() + "!=pending", 6);
assertRSQLQuery(ActionFields.STATUS.name() + "=in=(pending)", 5);
@@ -80,9 +81,10 @@ class RSQLActionFieldsTest extends AbstractJpaIntegrationTest {
.isThrownBy(() -> assertRSQLQuery(rsql, 5));
}
@Test
@Description("Test action by status")
void testFilterByParameterExtRef() {
/**
* Test action by status
*/
@Test void testFilterByParameterExtRef() {
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "==extRef", 5);
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "!=extRef", 6);
assertRSQLQuery(ActionFields.EXTERNALREF.name() + "==extRef*", 10);

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.RolloutFields;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -25,8 +22,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter rollout group")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter rollout group
*/
class RSQLRolloutFieldTest extends AbstractJpaIntegrationTest {
private Rollout rollout;
@@ -39,9 +38,10 @@ class RSQLRolloutFieldTest extends AbstractJpaIntegrationTest {
rollout = rolloutManagement.get(rollout.getId()).get();
}
@Test
@Description("Test filter rollout by distrbution set type id")
void testFilterByDsType() {
/**
* Test filter rollout by distrbution set type id
*/
@Test void testFilterByDsType() {
assertRSQLQuery(RolloutFields.DISTRIBUTIONSET.name() + ".type.id" + "==" + rollout.getDistributionSet().getType().getId() + 1, 0);
assertRSQLQuery(RolloutFields.DISTRIBUTIONSET.name() + ".type.id" + "!=" + rollout.getDistributionSet().getType().getId() + 1, 1);
assertRSQLQuery(RolloutFields.DISTRIBUTIONSET.name() + ".type.id" + "==" + rollout.getDistributionSet().getType().getId(), 1);

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.RolloutGroupFields;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -27,8 +24,10 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter rollout group")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter rollout group
*/
class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
private Long rolloutGroupId;
@@ -45,9 +44,10 @@ class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
this.rolloutGroupId = rolloutGroupManagement.findByRollout(rollout.getId(), PAGE).getContent().get(0).getId();
}
@Test
@Description("Test filter rollout group by id")
void testFilterByParameterId() {
/**
* Test filter rollout group by id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(RolloutGroupFields.ID.name() + "==" + rolloutGroupId, 1);
assertRSQLQuery(RolloutGroupFields.ID.name() + "!=" + rolloutGroupId, 3);
assertRSQLQuery(RolloutGroupFields.ID.name() + "==" + -1, 0);
@@ -62,9 +62,10 @@ class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(RolloutGroupFields.ID.name() + "=out=(" + rolloutGroupId + ",10000000)", 3);
}
@Test
@Description("Test filter rollout group by name")
void testFilterByParameterName() {
/**
* Test filter rollout group by name
*/
@Test void testFilterByParameterName() {
assertRSQLQuery(RolloutGroupFields.NAME.name() + "==group-1", 1);
assertRSQLQuery(RolloutGroupFields.NAME.name() + "!=group-1", 3);
assertRSQLQuery(RolloutGroupFields.NAME.name() + "==*", 4);
@@ -73,9 +74,10 @@ class RSQLRolloutGroupFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(RolloutGroupFields.NAME.name() + "=out=(group-1,group-2)", 2);
}
@Test
@Description("Test filter rollout group by description")
void testFilterByParameterDescription() {
/**
* Test filter rollout group by description
*/
@Test void testFilterByParameterDescription() {
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "==group-1", 1);
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "!=group-1", 3);
assertRSQLQuery(RolloutGroupFields.DESCRIPTION.name() + "==group*", 4);

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
import org.eclipse.hawkbit.repository.builder.SoftwareModuleMetadataCreate;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -26,8 +23,10 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter software module")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter software module
*/
class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
private SoftwareModule ah;
@@ -58,9 +57,10 @@ class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
softwareModuleManagement.updateMetadata(softwareModuleMetadata2);
}
@Test
@Description("Test filter software module by id")
void testFilterByParameterId() {
/**
* Test filter software module by id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(SoftwareModuleFields.ID.name() + "==" + ah.getId(), 1);
assertRSQLQuery(SoftwareModuleFields.ID.name() + "!=" + ah.getId(), 5);
assertRSQLQuery(SoftwareModuleFields.ID.name() + "==" + -1, 0);
@@ -75,9 +75,10 @@ class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleFields.ID.name() + "=out=(" + ah.getId() + ",1000000)", 5);
}
@Test
@Description("Test filter software module by name")
void testFilterByParameterName() {
/**
* Test filter software module by name
*/
@Test void testFilterByParameterName() {
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==agent-hub", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "!=agent-hub", 5);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==agent-hub*", 2);
@@ -96,17 +97,19 @@ class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*\\**", 1);
}
@Test
@Description("Test filter software module by name which contain mutated vowels ")
void testFilterByParameterNameWithUmlaut() {
/**
* Test filter software module by name which contain mutated vowels
*/
@Test void testFilterByParameterNameWithUmlaut() {
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ö*", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ä*", 1);
assertRSQLQuery(SoftwareModuleFields.NAME.name() + "==*Ü*", 1);
}
@Test
@Description("Test filter software module by description")
void testFilterByParameterDescription() {
/**
* Test filter software module by description
*/
@Test void testFilterByParameterDescription() {
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "==''", 1);
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "==agent-hub", 1);
@@ -116,18 +119,20 @@ class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleFields.DESCRIPTION.name() + "=out=(agent-hub,notexist)", 5);
}
@Test
@Description("Test filter software module by version")
void testFilterByParameterVersion() {
/**
* Test filter software module by version
*/
@Test void testFilterByParameterVersion() {
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "==1.0.1", 2);
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "!=v1.0", 6);
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "=in=(1.0.1,1.0.2)", 2);
assertRSQLQuery(SoftwareModuleFields.VERSION.name() + "=out=(1.0.1)", 4);
}
@Test
@Description("Test filter software module by type key")
void testFilterByType() {
/**
* Test filter software module by type key
*/
@Test void testFilterByType() {
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==" + TestdataFactory.SM_TYPE_APP, 2);
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "!=" + TestdataFactory.SM_TYPE_APP, 4);
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "==noExist*", 0);
@@ -135,9 +140,10 @@ class RSQLSoftwareModuleFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleFields.TYPE.name() + "=out=(" + TestdataFactory.SM_TYPE_APP + ")", 4);
}
@Test
@Description("Test filter software module by metadata")
void testFilterByMetadata() {
/**
* Test filter software module by metadata
*/
@Test void testFilterByMetadata() {
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey==metaValue", 1);
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey!=metaValue", 1);
assertRSQLQuery(SoftwareModuleFields.METADATA.name() + ".metaKey!=notexist", 2);

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.Constants;
import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -23,13 +20,16 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter software module test type")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter software module test type
*/
class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest {
@Test
@Description("Test filter software module test type by id")
void testFilterByParameterId() {
/**
* Test filter software module test type by id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "==" + osType.getId(), 1);
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "!=" + osType.getId(), 2);
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "==" + -1, 0);
@@ -44,16 +44,18 @@ class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleTypeFields.ID.name() + "=out=(" + osType.getId() + ",1000000)", 2);
}
@Test
@Description("Test filter software module test type by name")
void testFilterByParameterName() {
/**
* Test filter software module test type by name
*/
@Test void testFilterByParameterName() {
assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "==" + Constants.SMT_DEFAULT_OS_NAME, 1);
assertRSQLQuery(SoftwareModuleTypeFields.NAME.name() + "!=" + Constants.SMT_DEFAULT_OS_NAME, 2);
}
@Test
@Description("Test filter software module test type by description")
void testFilterByParameterDescription() {
/**
* Test filter software module test type by description
*/
@Test void testFilterByParameterDescription() {
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "!=''", 3);
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "==Updated*", 3);
@@ -61,18 +63,20 @@ class RSQLSoftwareModuleTypeFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(SoftwareModuleTypeFields.DESCRIPTION.name() + "==noExist*", 0);
}
@Test
@Description("Test filter software module test type by key")
void testFilterByParameterKey() {
/**
* Test filter software module test type by key
*/
@Test void testFilterByParameterKey() {
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "==os", 1);
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "!=os", 2);
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "=in=(os)", 1);
assertRSQLQuery(SoftwareModuleTypeFields.KEY.name() + "=out=(os)", 2);
}
@Test
@Description("Test filter software module test type by max")
void testFilterByMaxAssignment() {
/**
* Test filter software module test type by max
*/
@Test void testFilterByMaxAssignment() {
assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "==1", 2);
assertRSQLQuery(SoftwareModuleTypeFields.MAXASSIGNMENTS.name() + "!=1", 1);
}

View File

@@ -11,9 +11,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.TagFields;
import org.eclipse.hawkbit.repository.builder.TagCreate;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
@@ -24,8 +21,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
@Feature("Component Tests - Repository")
@Story("RSQL filter target and distribution set tags")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter target and distribution set tags
*/
class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
@BeforeEach
@@ -39,9 +38,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
}
}
@Test
@Description("Test filter target tag by name")
void testFilterTargetTagByParameterName() {
/**
* Test filter target tag by name
*/
@Test void testFilterTargetTagByParameterName() {
assertRSQLQueryTarget(TagFields.NAME.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.NAME.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.NAME.name() + "==1", 1);
@@ -52,9 +52,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQueryTarget(TagFields.NAME.name() + "=out=(1,notexist)", 4);
}
@Test
@Description("Test filter target tag by description")
void testFilterTargetTagByParameterDescription() {
/**
* Test filter target tag by description
*/
@Test void testFilterTargetTagByParameterDescription() {
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "==1", 1);
@@ -65,9 +66,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQueryTarget(TagFields.DESCRIPTION.name() + "=out=(1,notexist)", 4);
}
@Test
@Description("Test filter target tag by colour")
void testFilterTargetTagByParameterColour() {
/**
* Test filter target tag by colour
*/
@Test void testFilterTargetTagByParameterColour() {
assertRSQLQueryTarget(TagFields.COLOUR.name() + "==''", 0);
assertRSQLQueryTarget(TagFields.COLOUR.name() + "!=''", 5);
assertRSQLQueryTarget(TagFields.COLOUR.name() + "==red", 3);
@@ -78,9 +80,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQueryTarget(TagFields.COLOUR.name() + "=out=(red,notexist)", 2);
}
@Test
@Description("Test filter distribution set tag by name")
void testFilterDistributionSetTagByParameterName() {
/**
* Test filter distribution set tag by name
*/
@Test void testFilterDistributionSetTagByParameterName() {
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "==1", 1);
@@ -91,9 +94,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQueryDistributionSet(TagFields.NAME.name() + "=out=(1,2)", 3);
}
@Test
@Description("Test filter distribution set by description")
void testFilterDistributionSetTagByParameterDescription() {
/**
* Test filter distribution set by description
*/
@Test void testFilterDistributionSetTagByParameterDescription() {
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "==1", 1);
@@ -104,9 +108,10 @@ class RSQLTagFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQueryDistributionSet(TagFields.DESCRIPTION.name() + "=out=(1,2)", 3);
}
@Test
@Description("Test filter distribution set by colour")
void testFilterDistributionSetTagByParameterColour() {
/**
* Test filter distribution set by colour
*/
@Test void testFilterDistributionSetTagByParameterColour() {
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "==''", 0);
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "!=''", 5);
assertRSQLQueryDistributionSet(TagFields.COLOUR.name() + "==red", 3);

View File

@@ -19,9 +19,6 @@ import java.util.Map;
import jakarta.persistence.EntityManager;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.TargetFields;
import org.eclipse.hawkbit.repository.TargetTypeFields;
import org.eclipse.hawkbit.repository.exception.RSQLParameterUnsupportedFieldException;
@@ -39,8 +36,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Slice;
@Feature("Component Tests - Repository")
@Story("RSQL filter target")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter target
*/
@SuppressWarnings("java:S6813") // constructor injects are not possible for test classes
class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
@@ -107,18 +106,20 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
targetTag3.getId());
}
@Test
@Description("Test filter target by (controller) id")
void testFilterByParameterId() {
/**
* Test filter target by (controller) id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(TargetFields.ID.name() + "==targetId123", 1);
assertRSQLQuery(TargetFields.ID.name() + "!=targetId123", 4);
assertRSQLQuery(TargetFields.ID.name() + "=in=(targetId123,notexist)", 1);
assertRSQLQuery(TargetFields.ID.name() + "=out=(targetId123,notexist)", 4);
}
@Test
@Description("Test filter target by name")
void testFilterByParameterName() {
/**
* Test filter target by name
*/
@Test void testFilterByParameterName() {
assertRSQLQuery(TargetFields.NAME.name() + "==targetName123", 1);
assertRSQLQuery(TargetFields.NAME.name() + "==target*", 5);
assertRSQLQuery(TargetFields.NAME.name() + "==noExist*", 0);
@@ -127,9 +128,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.NAME.name() + "=out=(targetName123,notexist)", 4);
}
@Test
@Description("Test filter target by description")
void testFilterByParameterDescription() {
/**
* Test filter target by description
*/
@Test void testFilterByParameterDescription() {
assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==''", 3);
assertRSQLQuery(TargetFields.DESCRIPTION.name() + "!=''", 2);
assertRSQLQuery(TargetFields.DESCRIPTION.name() + "==targetDesc123", 1);
@@ -140,9 +142,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.DESCRIPTION.name() + "=out=(targetDesc123,notexist)", 4);
}
@Test
@Description("Test filter target by controller id")
void testFilterByParameterControllerId() {
/**
* Test filter target by controller id
*/
@Test void testFilterByParameterControllerId() {
assertRSQLQuery(TargetFields.CONTROLLERID.name() + "==targetId123", 1);
assertRSQLQuery(TargetFields.CONTROLLERID.name() + "==target*", 5);
assertRSQLQuery(TargetFields.CONTROLLERID.name() + "==noExist*", 0);
@@ -151,9 +154,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.CONTROLLERID.name() + "=out=(targetId123,notexist)", 4);
}
@Test
@Description("Test filter target by status")
void testFilterByParameterUpdateStatus() {
/**
* Test filter target by status
*/
@Test void testFilterByParameterUpdateStatus() {
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "==pending", 1);
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "!=pending", 4);
final String rsqlNoExistStar = TargetFields.UPDATESTATUS.name() + "==noExist*";
@@ -164,9 +168,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.UPDATESTATUS.name() + "=out=(pending,error)", 4);
}
@Test
@Description("Test filter target by attribute")
void testFilterByAttribute() {
/**
* Test filter target by attribute
*/
@Test void testFilterByAttribute() {
controllerManagement.updateControllerAttributes(
testdataFactory.createTarget().getControllerId(),
Map.of(
@@ -229,9 +234,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQueryThrowsException(TargetFields.ATTRIBUTE.name() + "==value.dot");
}
@Test
@Description("Test filter target by assigned ds name")
void testFilterByAssignedDsName() {
/**
* Test filter target by assigned ds name
*/
@Test void testFilterByAssignedDsName() {
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".name==AssignedDs", 1);
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".name==A*", 1);
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".name==noExist*", 0);
@@ -239,9 +245,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".name=out=(AssignedDs,notexist)", 4);
}
@Test
@Description("Test filter target by assigned ds version")
void testFilterByAssignedDsVersion() {
/**
* Test filter target by assigned ds version
*/
@Test void testFilterByAssignedDsVersion() {
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==" + TestdataFactory.DEFAULT_VERSION, 1);
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==*1*", 1);
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version==noExist*", 0);
@@ -249,9 +256,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.ASSIGNEDDS.name() + ".version=out=(" + TestdataFactory.DEFAULT_VERSION + ",notexist)", 4);
}
@Test
@Description("Test filter target by tag name")
void testFilterByTag() {
/**
* Test filter target by tag name
*/
@Test void testFilterByTag() {
assertRSQLQuery(TargetFields.TAG.name() + "==Tag1", 2);
assertRSQLQuery(TargetFields.TAG.name() + "!=Tag1", 3);
assertRSQLQuery(TargetFields.TAG.name() + "==T*", 4);
@@ -271,9 +279,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.TAG.name() + "!=Tag2" + OR + TargetFields.TAG.name() + "!=Tag3", 3);
}
@Test
@Description("Test filter target by lastTargetQuery")
void testFilterByLastTargetQuery() {
/**
* Test filter target by lastTargetQuery
*/
@Test void testFilterByLastTargetQuery() {
assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "==" + target.getLastTargetQuery(), 1);
assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "!=" + target.getLastTargetQuery(), 4);
assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=lt=" + target.getLastTargetQuery(), 0);
@@ -284,9 +293,10 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFields.LASTCONTROLLERREQUESTAT.name() + "=gt=${OVERDUE_TS}", 2);
}
@Test
@Description("Test filter target by metadata")
void testFilterByMetadata() {
/**
* Test filter target by metadata
*/
@Test void testFilterByMetadata() {
targetManagement.createMetadata(testdataFactory.createTarget().getControllerId(), Map.of("key.dot", "value.dot"));
assertRSQLQuery(TargetFields.METADATA.name() + ".metaKey==metaValue", 1);
@@ -350,18 +360,20 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
assertRSQLQueryThrowsException(TargetFields.METADATA.name() + "==value.dot");
}
@Test
@Description("Test filter based on more complex RSQL queries")
void testFilterByComplexQueries() {
/**
* Test filter based on more complex RSQL queries
*/
@Test void testFilterByComplexQueries() {
assertRSQLQuery(TargetFields.NAME.name() + "!=targetName123" + AND + TargetFields.METADATA.name() + ".metaKey!=value", 0);
assertRSQLQuery(
"(" + TargetFields.TAG.name() + "!=TAG1" + OR + TargetFields.TAG.name() + "!=TAG2)" +
AND + TargetFields.CONTROLLERID.name() + "!=targetId1235", 4);
}
@Test
@Description("Testing allowed RSQL keys based on TargetFields definition")
void rsqlValidTargetFields() {
/**
* Testing allowed RSQL keys based on TargetFields definition
*/
@Test void rsqlValidTargetFields() {
RSQLUtility.validateRsqlFor(
"ID == '0123' and NAME == abcd and DESCRIPTION == absd and CREATEDAT =lt= 0123 and LASTMODIFIEDAT =gt= 0123" +
" and CONTROLLERID == 0123 and UPDATESTATUS == PENDING and IPADDRESS == 0123 and LASTCONTROLLERREQUESTAT == 0123" +
@@ -386,27 +398,30 @@ class RSQLTargetFieldTest extends AbstractJpaIntegrationTest {
TargetFields.class, JpaTarget.class, virtualPropertyReplacer, entityManager));
}
@Test
@Description("Test filter by target type key")
void shouldFilterTargetsByTypeKey() {
/**
* Test filter by target type key
*/
@Test void shouldFilterTargetsByTypeKey() {
assertRSQLQuery("targettype." + TargetTypeFields.KEY.name() + "==" + targetType1.getKey(), 1);
assertRSQLQuery("targettype." + TargetTypeFields.KEY.name() + "==*1.key", 1);
assertRSQLQuery("targettype." + TargetTypeFields.KEY.name() + "!=" + targetType2.getKey(), 4);
assertRSQLQuery("targettype." + TargetTypeFields.KEY.name() + "==noExist*", 0);
}
@Test
@Description("Test filter by target type name")
void shouldFilterTargetsByTypeName() {
/**
* Test filter by target type name
*/
@Test void shouldFilterTargetsByTypeName() {
assertRSQLQuery("targettype." + TargetTypeFields.NAME.name() + "==" + targetType1.getName(), 1);
assertRSQLQuery("targettype." + TargetTypeFields.NAME.name() + "==*1", 1);
assertRSQLQuery("targettype." + TargetTypeFields.NAME.name() + "!=" + targetType2.getName(), 4);
assertRSQLQuery("targettype." + TargetTypeFields.NAME.name() + "==noExist*", 0);
}
@Test
@Description("Test filter by target type ID and description")
void shouldFilterTargetsByTypeIdAndDescription() {
/**
* Test filter by target type ID and description
*/
@Test void shouldFilterTargetsByTypeIdAndDescription() {
assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)
.isThrownBy(() -> assertRSQLQuery("targettype.ID==1", 0));
assertThatExceptionOfType(RSQLParameterUnsupportedFieldException.class)

View File

@@ -12,9 +12,6 @@ package org.eclipse.hawkbit.repository.jpa.rsql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.TargetFilterQueryFields;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
@@ -26,8 +23,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.orm.jpa.vendor.Database;
@Feature("Component Tests - Repository")
@Story("RSQL filter target filter query")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL filter target filter query
*/
class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
private TargetFilterQuery filter1;
@@ -52,9 +51,10 @@ class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
assertEquals(3L, targetFilterQueryManagement.count());
}
@Test
@Description("Test filter target filter query by id")
void testFilterByParameterId() {
/**
* Test filter target filter query by id
*/
@Test void testFilterByParameterId() {
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "==" + filter1.getId(), 1);
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "!=" + filter1.getId(), 2);
assertRSQLQuery(TargetFilterQueryFields.ID.name() + "==" + -1, 0);
@@ -70,9 +70,10 @@ class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
}
@Test
@Description("Test filter target filter query by name")
void testFilterByParameterName() {
/**
* Test filter target filter query by name
*/
@Test void testFilterByParameterName() {
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==" + filter1.getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==" + filter2.getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "==filter_*", 3);
@@ -81,9 +82,10 @@ class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
assertRSQLQuery(TargetFilterQueryFields.NAME.name() + "=out=(" + filter1.getName() + ",notexist)", 2);
}
@Test
@Description("Test filter target filter query by auto assigned ds name")
void testFilterByAutoAssignedDsName() {
/**
* Test filter target filter query by auto assigned ds name
*/
@Test void testFilterByAutoAssignedDsName() {
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".name=="
+ filter1.getAutoAssignDistributionSet().getName(), 1);
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".name=="
@@ -96,9 +98,10 @@ class RSQLTargetFilterQueryFieldsTest extends AbstractJpaIntegrationTest {
+ filter1.getAutoAssignDistributionSet().getName() + ",notexist)", 2);
}
@Test
@Description("Test filter target filter query by auto assigned ds version")
void testFilterByAutoAssignedDsVersion() {
/**
* Test filter target filter query by auto assigned ds version
*/
@Test void testFilterByAutoAssignedDsVersion() {
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".version=="
+ TestdataFactory.DEFAULT_VERSION, 2);
assertRSQLQuery(TargetFilterQueryFields.AUTOASSIGNDISTRIBUTIONSET.name() + ".version==*1*", 2);

View File

@@ -36,9 +36,6 @@ import jakarta.persistence.metamodel.EntityType;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.Type;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.DistributionSetFields;
import org.eclipse.hawkbit.repository.RsqlQueryField;
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
@@ -69,10 +66,12 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@Feature("Component Tests - Repository")
@Story("RSQL search utility")
/**
* Feature: Component Tests - Repository<br/>
* Story: RSQL search utility
*/
@Disabled
// TODO: fully document tests -> @Description for long text and reasonable
// TODO: fully document tests -> description for long text and reasonable
// method name as short text
class RSQLUtilityTest {
@@ -362,9 +361,10 @@ class RSQLUtilityTest {
.isThrownBy(() -> rsqlSpecification.toPredicate(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock));
}
@Test
@Description("Tests the resolution of overdue_ts placeholder in context of a RSQL expression.")
void correctRsqlWithOverdueMacro() {
/**
* Tests the resolution of overdue_ts placeholder in context of a RSQL expression.
*/
@Test void correctRsqlWithOverdueMacro() {
reset0(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
final String overdueProp = "overdue_ts";
final String overduePropPlaceholder = "${" + overdueProp + "}";
@@ -384,9 +384,10 @@ class RSQLUtilityTest {
verify(criteriaBuilderMock, never()).lessThanOrEqualTo(pathOfString(baseSoftwareModuleRootMock), overduePropPlaceholder);
}
@Test
@Description("Tests RSQL expression with an unknown placeholder.")
void correctRsqlWithUnknownMacro() {
/**
* Tests RSQL expression with an unknown placeholder.
*/
@Test void correctRsqlWithUnknownMacro() {
reset0(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
final String overdueProp = "unknown";
final String overduePropPlaceholder = "${" + overdueProp + "}";

View File

@@ -14,9 +14,6 @@ import static org.mockito.Mockito.when;
import java.util.concurrent.Callable;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.apache.commons.text.StringSubstitutor;
import org.eclipse.hawkbit.repository.TenantConfigurationManagement;
import org.eclipse.hawkbit.repository.model.TenantConfigurationValue;
@@ -37,8 +34,10 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@Feature("Unit Tests - Repository")
@Story("Placeholder resolution for virtual properties")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Placeholder resolution for virtual properties
*/
class VirtualPropertyResolverTest {
private static final TenantConfigurationValue<String> TEST_POLLING_TIME_INTERVAL =
@@ -61,9 +60,10 @@ class VirtualPropertyResolverTest {
.thenReturn(TEST_POLLING_OVERDUE_TIME_INTERVAL);
}
@Test
@Description("Tests VirtualPropertyResolver with a placeholder unknown to VirtualPropertyResolver.")
void handleUnknownPlaceholder() {
/**
* Tests VirtualPropertyResolver with a placeholder unknown to VirtualPropertyResolver.
*/
@Test void handleUnknownPlaceholder() {
final String placeholder = "${unknown}";
final String testString = "lhs=lt=" + placeholder;
@@ -71,9 +71,10 @@ class VirtualPropertyResolverTest {
assertThat(resolvedPlaceholders).as("unknown should not be resolved!").contains(placeholder);
}
@Test
@Description("Tests escape mechanism for placeholders (syntax is $${SOME_PLACEHOLDER}).")
void handleEscapedPlaceholder() {
/**
* Tests escape mechanism for placeholders (syntax is $${SOME_PLACEHOLDER}).
*/
@Test void handleEscapedPlaceholder() {
final String placeholder = "${OVERDUE_TS}";
final String escapedPlaceholder = StringSubstitutor.DEFAULT_ESCAPE + placeholder;
final String testString = "lhs=lt=" + escapedPlaceholder;
@@ -82,9 +83,11 @@ class VirtualPropertyResolverTest {
assertThat(resolvedPlaceholders).as("Escaped OVERDUE_TS should not be resolved!").contains(placeholder);
}
/**
* Tests resolution of NOW_TS by using a StringSubstitutor configured with the VirtualPropertyResolver.
*/
@ParameterizedTest
@ValueSource(strings = { "${NOW_TS}", "${OVERDUE_TS}", "${overdue_ts}" })
@Description("Tests resolution of NOW_TS by using a StringSubstitutor configured with the VirtualPropertyResolver.")
void resolveNowTimestampPlaceholder(final String placeholder) {
when(securityContext.runAsSystem(Mockito.any())).thenAnswer(a -> ((Callable<?>) a.getArgument(0)).call());
final String testString = "lhs=lt=" + placeholder;

View File

@@ -27,26 +27,27 @@ import jakarta.persistence.criteria.Path;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.junit.jupiter.api.Test;
import org.springframework.data.jpa.domain.Specification;
@Feature("Unit Tests - Repository")
@Story("Specifications builder")
/**
* Feature: Unit Tests - Repository<br/>
* Story: Specifications builder
*/
class SpecificationsBuilderTest {
@Test
@Description("Test the combination of specs on an empty list which returns null")
void combineWithAndEmptyList() {
/**
* Test the combination of specs on an empty list which returns null
*/
@Test void combineWithAndEmptyList() {
final List<Specification<Object>> specList = Collections.emptyList();
assertThat(SpecificationsBuilder.combineWithAnd(specList)).isNull();
}
@Test
@Description("Test the combination of specs on an immutable list with one entry")
void combineWithAndSingleImmutableList() {
/**
* Test the combination of specs on an immutable list with one entry
*/
@Test void combineWithAndSingleImmutableList() {
final Specification<Object> spec = (root, query, cb) -> cb.equal(root.get("field1"), "testValue");
final List<Specification<Object>> specList = Collections.singletonList(spec);
final Specification<Object> specifications = SpecificationsBuilder.combineWithAnd(specList);
@@ -68,9 +69,10 @@ class SpecificationsBuilderTest {
}
@Test
@Description("Test the combination of specs on a list with multiple entries")
void combineWithAndList() {
/**
* Test the combination of specs on a list with multiple entries
*/
@Test void combineWithAndList() {
final Specification<Object> spec1 = (root, query, cb) -> cb.equal(root.get("field1"), "testValue1");
final Specification<Object> spec2 = (root, query, cb) -> cb.equal(root.get("field2"), "testValue2");

View File

@@ -16,9 +16,6 @@ import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.eclipse.hawkbit.repository.model.DistributionSet;
@@ -34,15 +31,17 @@ import org.springframework.data.domain.Slice;
* Multi-Tenancy tests which testing the CRUD operations of entities that all
* CRUD-Operations are tenant aware and cannot access or delete entities not
* belonging to the current tenant.
* <p/>
* Feature: Component Tests - Repository<br/>
* Story: Multi Tenancy
*/
@Feature("Component Tests - Repository")
@Story("Multi Tenancy")
@ExtendWith(DisposableSqlTestDatabaseExtension.class)
class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
@Test
@Description(value = "Ensures that multiple targets with same controller-ID can be created for different tenants.")
void createMultipleTargetsWithSameIdForDifferentTenant() throws Exception {
/**
* Ensures that multiple targets with same controller-ID can be created for different tenants.
*/
@Test void createMultipleTargetsWithSameIdForDifferentTenant() throws Exception {
// known controller ID for overall tenants same
final String knownControllerId = "controllerId";
@@ -63,9 +62,10 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
.isEqualTo(anotherTenant.toUpperCase());
}
@Test
@Description(value = "Ensures that targets created by a tenant are not visible by another tenant.")
@WithUser(tenantId = "mytenant", allSpPermissions = true)
/**
* Ensures that targets created by a tenant are not visible by another tenant.
*/
@Test @WithUser(tenantId = "mytenant", allSpPermissions = true)
void queryTargetFromDifferentTenantIsNotVisible() throws Exception {
// create target for another tenant
final String anotherTenant = "anotherTenant";
@@ -83,9 +83,10 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
assertThat(findTargetsForTenant).hasSize(1);
}
@Test
@Description(value = "Ensures that tenant with proper permissions can read and delete other tenants.")
@WithUser(tenantId = "mytenant", allSpPermissions = true)
/**
* Ensures that tenant with proper permissions can read and delete other tenants.
*/
@Test @WithUser(tenantId = "mytenant", allSpPermissions = true)
void deleteAnotherTenantPossible() throws Exception {
// create target for another tenant
final String anotherTenant = "anotherTenant";
@@ -99,9 +100,10 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
assertThat(systemManagement.findTenants(PAGE)).as("Expected number if tenants after deletion is").hasSize(2);
}
@Test
@Description(value = "Ensures that tenant metadata is retrieved for the current tenant.")
@WithUser(tenantId = "mytenant", autoCreateTenant = false, allSpPermissions = true)
/**
* Ensures that tenant metadata is retrieved for the current tenant.
*/
@Test @WithUser(tenantId = "mytenant", autoCreateTenant = false, allSpPermissions = true)
void getTenanatMetdata() throws Exception {
// logged in tenant mytenant - check if tenant default data is
@@ -119,9 +121,10 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
.isEqualTo("bumlux".toUpperCase());
}
@Test
@Description(value = "Ensures that targets created from a different tenant cannot be deleted from other tenants")
@WithUser(tenantId = "mytenant", allSpPermissions = true)
/**
* Ensures that targets created from a different tenant cannot be deleted from other tenants
*/
@Test @WithUser(tenantId = "mytenant", allSpPermissions = true)
void deleteTargetFromOtherTenantIsNotPossible() throws Exception {
// create target for another tenant
final String anotherTenant = "anotherTenant";
@@ -145,9 +148,10 @@ class MultiTenancyEntityTest extends AbstractJpaIntegrationTest {
assertThat(targetsForAnotherTenant).isEmpty();
}
@Test
@Description(value = "Ensures that multiple distribution sets with same name and version can be created for different tenants.")
void createMultipleDistributionSetsWithSameNameForDifferentTenants() throws Exception {
/**
* Ensures that multiple distribution sets with same name and version can be created for different tenants.
*/
@Test void createMultipleDistributionSetsWithSameNameForDifferentTenants() throws Exception {
// known tenant names
final String tenant = "aTenant";