Code format hawkbit-repository-test (#1931)

Signed-off-by: Marinov Avgustin <Avgustin.Marinov@bosch.com>
This commit is contained in:
Avgustin Marinov
2024-11-05 10:11:19 +02:00
committed by GitHub
parent db46a7a372
commit 4987d429c2
18 changed files with 623 additions and 818 deletions

View File

@@ -9,7 +9,7 @@
SPDX-License-Identifier: EPL-2.0 SPDX-License-Identifier: EPL-2.0
--> -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>

View File

@@ -49,7 +49,6 @@ import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cloud.bus.ConditionalOnBusEnabled; import org.springframework.cloud.bus.ConditionalOnBusEnabled;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
@@ -71,8 +70,6 @@ import org.springframework.security.concurrent.DelegatingSecurityContextExecutor
import org.springframework.security.concurrent.DelegatingSecurityContextScheduledExecutorService; import org.springframework.security.concurrent.DelegatingSecurityContextScheduledExecutorService;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import static java.util.Objects.requireNonNull;
/** /**
* Spring context configuration required for Dev.Environment. * Spring context configuration required for Dev.Environment.
*/ */
@@ -86,6 +83,29 @@ import static java.util.Objects.requireNonNull;
@PropertySource("classpath:/hawkbit-test-defaults.properties") @PropertySource("classpath:/hawkbit-test-defaults.properties")
public class TestConfiguration implements AsyncConfigurer { public class TestConfiguration implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
return asyncExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
@Bean
public ScheduledExecutorService scheduledExecutorService() {
final AtomicLong count = new AtomicLong(0);
return new DelegatingSecurityContextScheduledExecutorService(
Executors.newScheduledThreadPool(1, (runnable) -> {
final Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setName(
String.format(
Locale.ROOT, "central-scheduled-executor-pool-%d", count.getAndIncrement()));
return thread;
}));
}
/** /**
* Disables caching during test to avoid concurrency failures during test. * Disables caching during test to avoid concurrency failures during test.
*/ */
@@ -154,6 +174,43 @@ public class TestConfiguration implements AsyncConfigurer {
return simpleApplicationEventMulticaster; return simpleApplicationEventMulticaster;
} }
@Bean
EventPublisherHolder eventBusHolder() {
return EventPublisherHolder.getInstance();
}
@Bean
Executor asyncExecutor() {
return new DelegatingSecurityContextExecutorService(Executors.newSingleThreadExecutor());
}
@Bean
AuditorAware<String> auditorAware() {
return new SpringSecurityAuditorAware();
}
/**
* @return returns a VirtualPropertyReplacer
*/
@Bean
VirtualPropertyReplacer virtualPropertyReplacer() {
return new VirtualPropertyResolver();
}
@Bean
RolloutApprovalStrategy rolloutApprovalStrategy() {
return new RolloutTestApprovalStrategy();
}
/**
* @return the protostuff io message converter
*/
@Bean
@ConditionalOnBusEnabled
MessageConverter busProtoBufConverter() {
return new BusProtoStuffMessageConverter();
}
private static class FilterEnabledApplicationEventPublisher extends SimpleApplicationEventMulticaster { private static class FilterEnabledApplicationEventPublisher extends SimpleApplicationEventMulticaster {
private final ApplicationEventFilter applicationEventFilter; private final ApplicationEventFilter applicationEventFilter;
@@ -171,66 +228,4 @@ public class TestConfiguration implements AsyncConfigurer {
super.multicastEvent(event, eventType); super.multicastEvent(event, eventType);
} }
} }
@Bean
EventPublisherHolder eventBusHolder() {
return EventPublisherHolder.getInstance();
}
@Bean
Executor asyncExecutor() {
return new DelegatingSecurityContextExecutorService(Executors.newSingleThreadExecutor());
}
@Bean
AuditorAware<String> auditorAware() {
return new SpringSecurityAuditorAware();
}
@Override
public Executor getAsyncExecutor() {
return asyncExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
@Bean
public ScheduledExecutorService scheduledExecutorService() {
final AtomicLong count = new AtomicLong(0);
return new DelegatingSecurityContextScheduledExecutorService(
Executors.newScheduledThreadPool(1, (runnable) -> {
final Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setName(
String.format(
Locale.ROOT, "central-scheduled-executor-pool-%d", count.getAndIncrement()));
return thread;
}));
}
/**
*
* @return returns a VirtualPropertyReplacer
*/
@Bean
VirtualPropertyReplacer virtualPropertyReplacer() {
return new VirtualPropertyResolver();
}
@Bean
RolloutApprovalStrategy rolloutApprovalStrategy() {
return new RolloutTestApprovalStrategy();
}
/**
*
* @return the protostuff io message converter
*/
@Bean
@ConditionalOnBusEnabled
MessageConverter busProtoBufConverter() {
return new BusProtoStuffMessageConverter();
}
} }

View File

@@ -57,8 +57,7 @@ public class EventVerifier extends AbstractTestExecutionListener {
* executor in the ApplicationEventMultiCaster, so the order of the events * executor in the ApplicationEventMultiCaster, so the order of the events
* keep the same. * keep the same.
* *
* @param publisher * @param publisher the {@link ApplicationEventPublisher} to publish the marker
* the {@link ApplicationEventPublisher} to publish the marker
* event to * event to
*/ */
public static void publishResetMarkerEvent(final ApplicationEventPublisher publisher) { public static void publishResetMarkerEvent(final ApplicationEventPublisher publisher) {
@@ -175,6 +174,7 @@ public class EventVerifier extends AbstractTestExecutionListener {
} }
private static final class ResetCounterMarkerEvent extends RemoteApplicationEvent { private static final class ResetCounterMarkerEvent extends RemoteApplicationEvent {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private ResetCounterMarkerEvent() { private ResetCounterMarkerEvent() {

View File

@@ -73,9 +73,9 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.bus.ServiceMatcher; import org.springframework.cloud.bus.ServiceMatcher;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.auditing.AuditingHandler; import org.springframework.data.auditing.AuditingHandler;
@@ -93,10 +93,10 @@ import org.springframework.test.context.TestPropertySource;
@Slf4j @Slf4j
@ActiveProfiles({ "test" }) @ActiveProfiles({ "test" })
@ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class }) @ExtendWith({ JUnitTestLoggerExtension.class, SharedSqlTestDatabaseExtension.class })
@WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE }) @WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ContextConfiguration(classes = { TestConfiguration.class}) @ContextConfiguration(classes = { TestConfiguration.class })
@Import(TestChannelBinderConfiguration.class) @Import(TestChannelBinderConfiguration.class)
// destroy the context after each test class because otherwise we get problem // destroy the context after each test class because otherwise we get problem
// when context is // when context is
@@ -216,6 +216,109 @@ public abstract class AbstractIntegrationTest {
@Autowired @Autowired
protected ApplicationEventPublisher eventPublisher; protected ApplicationEventPublisher eventPublisher;
private static final String ARTIFACT_DIRECTORY = createTempDir();
@BeforeAll
public static void beforeClass() {
System.setProperty("org.eclipse.hawkbit.repository.file.path", ARTIFACT_DIRECTORY);
}
@AfterAll
public static void afterClass() {
if (new File(ARTIFACT_DIRECTORY).exists()) {
try {
FileUtils.deleteDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) {
log.warn("Cannot delete file-directory", e);
}
}
}
@BeforeEach
public void beforeAll() throws Exception {
final String description = "Updated description.";
osType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS));
osType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(osType.getId()).description(description)));
appType = SecurityContextSwitch.runAsPrivileged(
() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE));
appType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(appType.getId()).description(description)));
runtimeType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT));
runtimeType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(runtimeType.getId()).description(description)));
standardDsType = SecurityContextSwitch.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType());
// publish the reset counter market event to reset the counters after
// setup. The setup is transparent by the test and its @ExpectedEvent
// counting so we reset the counter here after the setup. Note that this
// approach is only working when using a single-thread executor in the
// ApplicationEventMultiCaster which the TestConfiguration is doing so
// the order of the events keep the same.
EventVerifier.publishResetMarkerEvent(eventPublisher);
}
@AfterEach
public void cleanUp() {
if (new File(ARTIFACT_DIRECTORY).exists()) {
try {
FileUtils.cleanDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) {
log.warn("Cannot cleanup file-directory", e);
}
}
}
/**
* Gets a valid cron expression describing a schedule with a single
* maintenance window, starting specified number of minutes after current
* time.
*
* @param minutesToAdd is the number of minutes after the current time
* @return {@link String} containing a valid cron expression.
*/
protected static String getTestSchedule(final int minutesToAdd) {
ZonedDateTime currentTime = ZonedDateTime.now();
currentTime = currentTime.plusMinutes(minutesToAdd);
return String.format("%d %d %d %d %d ? %d", currentTime.getSecond(), currentTime.getMinute(),
currentTime.getHour(), currentTime.getDayOfMonth(), currentTime.getMonthValue(), currentTime.getYear());
}
protected static String getTestDuration(final int duration) {
return String.format("%02d:%02d:00", duration / 60, duration % 60);
}
protected static String getTestTimeZone() {
final ZonedDateTime currentTime = ZonedDateTime.now();
return currentTime.getOffset().getId().replace("Z", "+00:00");
}
protected static Action getFirstAssignedAction(
final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return distributionSetAssignmentResult.getAssignedEntity().stream().findFirst()
.orElseThrow(() -> new IllegalStateException("expected one assigned action, found none"));
}
protected static Long getFirstAssignedActionId(
final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return getFirstAssignedAction(distributionSetAssignmentResult).getId();
}
protected static Target getFirstAssignedTarget(final DistributionSetAssignmentResult assignment) {
return getFirstAssignedAction(assignment).getTarget();
}
protected static Comparator<Target> controllerIdComparator() {
return (o1, o2) -> o1.getControllerId().equals(o2.getControllerId()) ? 0 : 1;
}
protected DistributionSetAssignmentResult assignDistributionSet(final long dsID, final String controllerId) { protected DistributionSetAssignmentResult assignDistributionSet(final long dsID, final String controllerId) {
return assignDistributionSet(dsID, controllerId, ActionType.FORCED); return assignDistributionSet(dsID, controllerId, ActionType.FORCED);
@@ -286,25 +389,19 @@ public abstract class AbstractIntegrationTest {
* Test helper method to assign distribution set to a target with a * Test helper method to assign distribution set to a target with a
* maintenance schedule. * maintenance schedule.
* *
* @param dsID * @param dsID is the ID for the distribution set being assigned
* is the ID for the distribution set being assigned * @param controllerId is the ID for the controller to which the distribution set is
* @param controllerId
* is the ID for the controller to which the distribution set is
* being assigned * being assigned
* @param maintenanceWindowSchedule * @param maintenanceWindowSchedule is the cron expression to be used for scheduling the
* is the cron expression to be used for scheduling the
* maintenance window. Expression has 6 mandatory fields and 1 * maintenance window. Expression has 6 mandatory fields and 1
* last optional field: "second minute hour dayofmonth month * last optional field: "second minute hour dayofmonth month
* weekday year" * weekday year"
* @param maintenanceWindowDuration * @param maintenanceWindowDuration in HH:mm:ss format specifying the duration of a maintenance
* in HH:mm:ss format specifying the duration of a maintenance
* window, for example 00:30:00 for 30 minutes * window, for example 00:30:00 for 30 minutes
* @param maintenanceWindowTimeZone * @param maintenanceWindowTimeZone is the time zone specified as +/-hh:mm offset from UTC, for
* is the time zone specified as +/-hh:mm offset from UTC, for
* example +02:00 for CET summer time and +00:00 for UTC. The * example +02:00 for CET summer time and +00:00 for UTC. The
* start time of a maintenance window calculated based on the * start time of a maintenance window calculated based on the
* cron expression is relative to this time zone * cron expression is relative to this time zone
*
* @return result of the assignment as { @link * @return result of the assignment as { @link
* DistributionSetAssignmentResult}. * DistributionSetAssignmentResult}.
*/ */
@@ -355,10 +452,6 @@ public abstract class AbstractIntegrationTest {
createTargetMetadata(controllerId, Collections.singletonList(md)); createTargetMetadata(controllerId, Collections.singletonList(md));
} }
private void createTargetMetadata(final String controllerId, final List<MetaData> md) {
targetManagement.createMetaData(controllerId, md);
}
protected Long getOsModule(final DistributionSet ds) { protected Long getOsModule(final DistributionSet ds) {
return ds.findFirstModuleByType(osType).orElseThrow(NoSuchElementException::new).getId(); return ds.findFirstModuleByType(osType).orElseThrow(NoSuchElementException::new).getId();
} }
@@ -387,120 +480,6 @@ public abstract class AbstractIntegrationTest {
entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED));
} }
@BeforeEach
public void beforeAll() throws Exception {
final String description = "Updated description.";
osType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_OS));
osType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(osType.getId()).description(description)));
appType = SecurityContextSwitch.runAsPrivileged(
() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_APP, Integer.MAX_VALUE));
appType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(appType.getId()).description(description)));
runtimeType = SecurityContextSwitch
.runAsPrivileged(() -> testdataFactory.findOrCreateSoftwareModuleType(TestdataFactory.SM_TYPE_RT));
runtimeType = SecurityContextSwitch.runAsPrivileged(() -> softwareModuleTypeManagement
.update(entityFactory.softwareModuleType().update(runtimeType.getId()).description(description)));
standardDsType = SecurityContextSwitch.runAsPrivileged(() -> testdataFactory.findOrCreateDefaultTestDsType());
// publish the reset counter market event to reset the counters after
// setup. The setup is transparent by the test and its @ExpectedEvent
// counting so we reset the counter here after the setup. Note that this
// approach is only working when using a single-thread executor in the
// ApplicationEventMultiCaster which the TestConfiguration is doing so
// the order of the events keep the same.
EventVerifier.publishResetMarkerEvent(eventPublisher);
}
private static final String ARTIFACT_DIRECTORY = createTempDir();
private static String createTempDir() {
try {
return Files.createTempDirectory(null).toString() + "/" + RandomStringUtils.randomAlphanumeric(20);
} catch (final IOException e) {
throw new IllegalStateException("Failed to create temp directory");
}
}
@AfterEach
public void cleanUp() {
if (new File(ARTIFACT_DIRECTORY).exists()) {
try {
FileUtils.cleanDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) {
log.warn("Cannot cleanup file-directory", e);
}
}
}
@BeforeAll
public static void beforeClass() {
System.setProperty("org.eclipse.hawkbit.repository.file.path", ARTIFACT_DIRECTORY);
}
@AfterAll
public static void afterClass() {
if (new File(ARTIFACT_DIRECTORY).exists()) {
try {
FileUtils.deleteDirectory(new File(ARTIFACT_DIRECTORY));
} catch (final IOException | IllegalArgumentException e) {
log.warn("Cannot delete file-directory", e);
}
}
}
/**
* Gets a valid cron expression describing a schedule with a single
* maintenance window, starting specified number of minutes after current
* time.
*
* @param minutesToAdd
* is the number of minutes after the current time
*
* @return {@link String} containing a valid cron expression.
*/
protected static String getTestSchedule(final int minutesToAdd) {
ZonedDateTime currentTime = ZonedDateTime.now();
currentTime = currentTime.plusMinutes(minutesToAdd);
return String.format("%d %d %d %d %d ? %d", currentTime.getSecond(), currentTime.getMinute(),
currentTime.getHour(), currentTime.getDayOfMonth(), currentTime.getMonthValue(), currentTime.getYear());
}
protected static String getTestDuration(final int duration) {
return String.format("%02d:%02d:00", duration / 60, duration % 60);
}
protected static String getTestTimeZone() {
final ZonedDateTime currentTime = ZonedDateTime.now();
return currentTime.getOffset().getId().replace("Z", "+00:00");
}
protected static Action getFirstAssignedAction(
final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return distributionSetAssignmentResult.getAssignedEntity().stream().findFirst()
.orElseThrow(() -> new IllegalStateException("expected one assigned action, found none"));
}
protected static Long getFirstAssignedActionId(
final DistributionSetAssignmentResult distributionSetAssignmentResult) {
return getFirstAssignedAction(distributionSetAssignmentResult).getId();
}
protected static Target getFirstAssignedTarget(final DistributionSetAssignmentResult assignment) {
return getFirstAssignedAction(assignment).getTarget();
}
protected static Comparator<Target> controllerIdComparator() {
return (o1, o2) -> o1.getControllerId().equals(o2.getControllerId()) ? 0 : 1;
}
protected void enableBatchAssignments() { protected void enableBatchAssignments() {
tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.BATCH_ASSIGNMENTS_ENABLED, true); tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.BATCH_ASSIGNMENTS_ENABLED, true);
} }
@@ -525,4 +504,16 @@ public abstract class AbstractIntegrationTest {
} }
} }
} }
private static String createTempDir() {
try {
return Files.createTempDirectory(null).toString() + "/" + RandomStringUtils.randomAlphanumeric(20);
} catch (final IOException e) {
throw new IllegalStateException("Failed to create temp directory");
}
}
private void createTargetMetadata(final String controllerId, final List<MetaData> md) {
targetManagement.createMetaData(controllerId, md);
}
} }

View File

@@ -55,10 +55,6 @@ public class DatasourceContext {
System.getProperty(upperCaseVariant(SPRING_DATABASE_PASSWORD_KEY))); System.getProperty(upperCaseVariant(SPRING_DATABASE_PASSWORD_KEY)));
} }
private static String upperCaseVariant(final String key) {
return key.toUpperCase().replace('.', '_');
}
public String getDatabase() { public String getDatabase() {
return database; return database;
} }
@@ -85,4 +81,8 @@ public class DatasourceContext {
return database == null || datasourceUrl == null || username == null || password == null; return database == null || datasourceUrl == null || username == null || password == null;
} }
private static String upperCaseVariant(final String key) {
return key.toUpperCase().replace('.', '_');
}
} }

View File

@@ -9,13 +9,12 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_DATASOURCE_URL_KEY;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ExtensionContext;
import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_DATASOURCE_URL_KEY;
/** /**
* Provides a convenient way to generate a test database that can be used, and disposed of after the test is executed. * Provides a convenient way to generate a test database that can be used, and disposed of after the test is executed.
*/ */

View File

@@ -34,6 +34,6 @@ public class H2TestDatabase extends AbstractSqlTestDatabase {
@Override @Override
protected String getRandomSchemaUri() { protected String getRandomSchemaUri() {
return "jdbc:h2:mem:" + context.getRandomSchemaName() +";MODE=MySQL;"; return "jdbc:h2:mem:" + context.getRandomSchemaName() + ";MODE=MySQL;";
} }
} }

View File

@@ -9,14 +9,14 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.HexFormat; import java.util.HexFormat;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/** /**
* Hash digest utility. * Hash digest utility.
*/ */
@@ -27,8 +27,7 @@ public final class HashGeneratorUtils {
/** /**
* Generates a MD5 cryptographic string. * Generates a MD5 cryptographic string.
* *
* @param message * @param message the plain message
* the plain message
* @return the cryptographic string * @return the cryptographic string
*/ */
public static String generateMD5(final byte[] message) { public static String generateMD5(final byte[] message) {
@@ -38,8 +37,7 @@ public final class HashGeneratorUtils {
/** /**
* Generates a SHA-1 cryptographic string. * Generates a SHA-1 cryptographic string.
* *
* @param message * @param message the plain message
* the plain message
* @return the cryptographic string * @return the cryptographic string
*/ */
public static String generateSHA1(final byte[] message) { public static String generateSHA1(final byte[] message) {
@@ -49,8 +47,7 @@ public final class HashGeneratorUtils {
/** /**
* Generates a SHA-256 cryptographic string. * Generates a SHA-256 cryptographic string.
* *
* @param message * @param message the plain message
* the plain message
* @return the cryptographic string * @return the cryptographic string
*/ */
public static String generateSHA256(final byte[] message) { public static String generateSHA256(final byte[] message) {

View File

@@ -34,12 +34,9 @@ public class JpaTestRepositoryManagement {
/** /**
* Constructor. * Constructor.
* *
* @param cacheManager * @param cacheManager the cachemanager
* the cachemanager * @param systemSecurityContext the systemSecurityContext
* @param systemSecurityContext * @param systemManagement the systemManagement
* the systemSecurityContext
* @param systemManagement
* the systemManagement
*/ */
public JpaTestRepositoryManagement(final TenantAwareCacheManager cacheManager, public JpaTestRepositoryManagement(final TenantAwareCacheManager cacheManager,
final SystemSecurityContext systemSecurityContext, final SystemManagement systemManagement) { final SystemSecurityContext systemSecurityContext, final SystemManagement systemManagement) {

View File

@@ -27,14 +27,6 @@ public class RolloutTestApprovalStrategy implements RolloutApprovalStrategy {
return approvalNeeded; return approvalNeeded;
} }
public void setApprovalNeeded(boolean approvalNeeded) {
this.approvalNeeded = approvalNeeded;
}
public void setApproveDecidedBy(final String user) {
this.approvalDecidedBy = user;
}
@Override @Override
public void onApprovalRequired(Rollout rollout) { public void onApprovalRequired(Rollout rollout) {
// do nothing, as no action is needed when testing // do nothing, as no action is needed when testing
@@ -44,4 +36,12 @@ public class RolloutTestApprovalStrategy implements RolloutApprovalStrategy {
public String getApprovalUser(Rollout rollout) { public String getApprovalUser(Rollout rollout) {
return approvalDecidedBy; return approvalDecidedBy;
} }
public void setApprovalNeeded(boolean approvalNeeded) {
this.approvalNeeded = approvalNeeded;
}
public void setApproveDecidedBy(final String user) {
this.approvalDecidedBy = user;
}
} }

View File

@@ -31,10 +31,6 @@ public class SecurityContextSwitch {
private static final WithUser PRIVILEDGED_USER = private static final WithUser PRIVILEDGED_USER =
createWithUser("bumlux", DEFAULT_TENANT, false, true, false, "ROLE_CONTROLLER", "ROLE_SYSTEM_CODE"); createWithUser("bumlux", DEFAULT_TENANT, false, true, false, "ROLE_CONTROLLER", "ROLE_SYSTEM_CODE");
private static void setSecurityContext(final WithUser annotation) {
SecurityContextHolder.setContext(new WithUserSecurityContext(annotation));
}
public static <T> T runAsPrivileged(final Callable<T> callable) throws Exception { public static <T> T runAsPrivileged(final Callable<T> callable) throws Exception {
createTenant(DEFAULT_TENANT); createTenant(DEFAULT_TENANT);
return runAs(PRIVILEDGED_USER, callable); return runAs(PRIVILEDGED_USER, callable);
@@ -53,16 +49,6 @@ public class SecurityContextSwitch {
} }
} }
private static void createTenant(final String tenantId) {
final SecurityContext oldContext = SecurityContextHolder.getContext();
setSecurityContext(PRIVILEDGED_USER);
try {
SystemManagementHolder.getInstance().getSystemManagement().createTenantMetadata(tenantId);
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
public static WithUser withController(final String principal, final String... authorities) { public static WithUser withController(final String principal, final String... authorities) {
return withUserAndTenant(principal, DEFAULT_TENANT, true, false, true, authorities); return withUserAndTenant(principal, DEFAULT_TENANT, true, false, true, authorities);
} }
@@ -81,6 +67,20 @@ public class SecurityContextSwitch {
return createWithUser(principal, tenant, autoCreateTenant, allSpPermission, controller, authorities); return createWithUser(principal, tenant, autoCreateTenant, allSpPermission, controller, authorities);
} }
private static void setSecurityContext(final WithUser annotation) {
SecurityContextHolder.setContext(new WithUserSecurityContext(annotation));
}
private static void createTenant(final String tenantId) {
final SecurityContext oldContext = SecurityContextHolder.getContext();
setSecurityContext(PRIVILEDGED_USER);
try {
SystemManagementHolder.getInstance().getSystemManagement().createTenantMetadata(tenantId);
} finally {
SecurityContextHolder.setContext(oldContext);
}
}
private static WithUser createWithUser(final String principal, final String tenant, final boolean autoCreateTenant, private static WithUser createWithUser(final String principal, final String tenant, final boolean autoCreateTenant,
final boolean allSpPermission, final boolean controller, final String... authorities) { final boolean allSpPermission, final boolean controller, final String... authorities) {
return new WithUser() { return new WithUser() {
@@ -100,6 +100,16 @@ public class SecurityContextSwitch {
return null; return null;
} }
@Override
public String tenantId() {
return tenant;
}
@Override
public boolean autoCreateTenant() {
return autoCreateTenant;
}
@Override @Override
public String[] authorities() { public String[] authorities() {
return authorities; return authorities;
@@ -115,16 +125,6 @@ public class SecurityContextSwitch {
return new String[0]; return new String[0];
} }
@Override
public String tenantId() {
return tenant;
}
@Override
public boolean autoCreateTenant() {
return autoCreateTenant;
}
@Override @Override
public boolean controller() { public boolean controller() {
return controller; return controller;
@@ -145,11 +145,6 @@ public class SecurityContextSwitch {
} }
} }
@Override
public void setAuthentication(final Authentication authentication) {
// nothing to do
}
@Override @Override
public Authentication getAuthentication() { public Authentication getAuthentication() {
final String[] authorities; final String[] authorities;
@@ -166,15 +161,14 @@ public class SecurityContextSwitch {
return testingAuthenticationToken; return testingAuthenticationToken;
} }
private String[] getAllAuthorities(final String[] additionalAuthorities, final String[] notInclude) { @Override
final List<String> permissions = SpPermission.getAllAuthorities(); public void setAuthentication(final Authentication authentication) {
if (notInclude != null) { // nothing to do
permissions.removeAll(Arrays.asList(notInclude));
} }
if (additionalAuthorities != null) {
permissions.addAll(Arrays.asList(additionalAuthorities)); @Override
} public int hashCode() {
return permissions.toArray(new String[0]); return annotation.hashCode();
} }
@Override @Override
@@ -186,9 +180,15 @@ public class SecurityContextSwitch {
} }
} }
@Override private String[] getAllAuthorities(final String[] additionalAuthorities, final String[] notInclude) {
public int hashCode() { final List<String> permissions = SpPermission.getAllAuthorities();
return annotation.hashCode(); if (notInclude != null) {
permissions.removeAll(Arrays.asList(notInclude));
}
if (additionalAuthorities != null) {
permissions.addAll(Arrays.asList(additionalAuthorities));
}
return permissions.toArray(new String[0]);
} }
} }
} }

View File

@@ -49,13 +49,6 @@ public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
registerDropSchemaOnSystemShutdownHook(database, randomSchemaUri); registerDropSchemaOnSystemShutdownHook(database, randomSchemaUri);
} }
private void registerDropSchemaOnSystemShutdownHook(final AbstractSqlTestDatabase database, final String schemaUri) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
log.warn("\033[0;33mDropping schema at url {} \033[0m", schemaUri);
database.dropRandomSchema();
}));
}
protected AbstractSqlTestDatabase matchingDatabase(final DatasourceContext context) { protected AbstractSqlTestDatabase matchingDatabase(final DatasourceContext context) {
AbstractSqlTestDatabase database; AbstractSqlTestDatabase database;
@@ -79,4 +72,11 @@ public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
return database; return database;
} }
private void registerDropSchemaOnSystemShutdownHook(final AbstractSqlTestDatabase database, final String schemaUri) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
log.warn("\033[0;33mDropping schema at url {} \033[0m", schemaUri);
database.dropRandomSchema();
}));
}
} }

View File

@@ -15,6 +15,7 @@ import java.util.Random;
import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.Target;
public class TargetTestData { public class TargetTestData {
public static final String ATTRIBUTE_KEY_TOO_LONG; public static final String ATTRIBUTE_KEY_TOO_LONG;
public static final String ATTRIBUTE_KEY_VALID; public static final String ATTRIBUTE_KEY_VALID;
public static final String ATTRIBUTE_VALUE_TOO_LONG; public static final String ATTRIBUTE_VALUE_TOO_LONG;
@@ -28,6 +29,10 @@ public class TargetTestData {
ATTRIBUTE_VALUE_VALID = generateRandomStringWithLength(Target.CONTROLLER_ATTRIBUTE_VALUE_SIZE, rand); ATTRIBUTE_VALUE_VALID = generateRandomStringWithLength(Target.CONTROLLER_ATTRIBUTE_VALUE_SIZE, rand);
} }
private TargetTestData() {
// nothing to do here
}
private static String generateRandomStringWithLength(final int length, final Random rand) { private static String generateRandomStringWithLength(final int length, final Random rand) {
final StringBuilder randomStringBuilder = new StringBuilder(length); final StringBuilder randomStringBuilder = new StringBuilder(length);
final int lowercaseACode = 97; final int lowercaseACode = 97;
@@ -39,8 +44,4 @@ public class TargetTestData {
} }
return randomStringBuilder.toString(); return randomStringBuilder.toString();
} }
private TargetTestData() {
// nothing to do here
}
} }

View File

@@ -204,10 +204,8 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and * {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>. * {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix) { public DistributionSet createDistributionSet(final String prefix) {
@@ -232,9 +230,7 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and * {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>. * {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
* *
* @param modules * @param modules of {@link DistributionSet#getModules()}
* of {@link DistributionSet#getModules()}
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final Collection<SoftwareModule> modules) { public DistributionSet createDistributionSet(final Collection<SoftwareModule> modules) {
@@ -247,12 +243,9 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and * {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>. * {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
* *
* @param modules * @param modules of {@link DistributionSet#getModules()}
* of {@link DistributionSet#getModules()} * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* @param prefix
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final Collection<SoftwareModule> modules, final String prefix) { public DistributionSet createDistributionSet(final Collection<SoftwareModule> modules, final String prefix) {
@@ -264,12 +257,9 @@ public class TestdataFactory {
* {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} , * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} ,
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION}. * {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION}.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param isRequiredMigrationStep * @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* for {@link DistributionSet#isRequiredMigrationStep()}
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix, final boolean isRequiredMigrationStep) { public DistributionSet createDistributionSet(final String prefix, final boolean isRequiredMigrationStep) {
@@ -282,12 +272,9 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and * {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>. * {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param tags * @param tags DistributionSet tags
* DistributionSet tags
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix, final Collection<DistributionSetTag> tags) { public DistributionSet createDistributionSet(final String prefix, final Collection<DistributionSetTag> tags) {
@@ -299,15 +286,11 @@ public class TestdataFactory {
* {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} , * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} ,
* {@link #SM_TYPE_APP}. * {@link #SM_TYPE_APP}.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param version * @param version {@link DistributionSet#getVersion()} and
* {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random number. * {@link SoftwareModule#getVersion()} extended by a random number.
* @param isRequiredMigrationStep * @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* for {@link DistributionSet#isRequiredMigrationStep()}
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix, final String version, public DistributionSet createDistributionSet(final String prefix, final String version,
@@ -342,35 +325,21 @@ public class TestdataFactory {
* {@link #INVISIBLE_SM_MD_KEY}, {@link #INVISIBLE_SM_MD_VALUE} without * {@link #INVISIBLE_SM_MD_KEY}, {@link #INVISIBLE_SM_MD_VALUE} without
* {@link SoftwareModuleMetadata#isTargetVisible()} * {@link SoftwareModuleMetadata#isTargetVisible()}
* *
* @param set * @param set to add metadata to
* to add metadata to
*/ */
public void addSoftwareModuleMetadata(final DistributionSet set) { public void addSoftwareModuleMetadata(final DistributionSet set) {
set.getModules().forEach(this::addTestModuleMetadata); set.getModules().forEach(this::addTestModuleMetadata);
} }
private void addTestModuleMetadata(final SoftwareModule module) {
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata().create(module.getId())
.key(VISIBLE_SM_MD_KEY).value(VISIBLE_SM_MD_VALUE).targetVisible(true));
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata().create(module.getId())
.key(INVISIBLE_SM_MD_KEY).value(INVISIBLE_SM_MD_VALUE).targetVisible(false));
}
/** /**
* Creates {@link DistributionSet} in repository. * Creates {@link DistributionSet} in repository.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param version * @param version {@link DistributionSet#getVersion()} and
* {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random number. * {@link SoftwareModule#getVersion()} extended by a random number.
* @param isRequiredMigrationStep * @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* for {@link DistributionSet#isRequiredMigrationStep()} * @param modules for {@link DistributionSet#getModules()}
* @param modules
* for {@link DistributionSet#getModules()}
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix, final String version, public DistributionSet createDistributionSet(final String prefix, final String version,
@@ -388,16 +357,12 @@ public class TestdataFactory {
* {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} , * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} ,
* {@link #SM_TYPE_APP}. * {@link #SM_TYPE_APP}.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param version * @param version {@link DistributionSet#getVersion()} and
* {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random * {@link SoftwareModule#getVersion()} extended by a random
* number.updat * number.updat
* @param tags * @param tags DistributionSet tags
* DistributionSet tags
*
* @return {@link DistributionSet} entity. * @return {@link DistributionSet} entity.
*/ */
public DistributionSet createDistributionSet(final String prefix, final String version, final Collection<DistributionSetTag> tags) { public DistributionSet createDistributionSet(final String prefix, final String version, final Collection<DistributionSetTag> tags) {
@@ -413,9 +378,7 @@ public class TestdataFactory {
* number and {@link DistributionSet#isRequiredMigrationStep()} * number and {@link DistributionSet#isRequiredMigrationStep()}
* <code>false</code>. * <code>false</code>.
* *
* @param number * @param number of {@link DistributionSet}s to create
* of {@link DistributionSet}s to create
*
* @return {@link List} of {@link DistributionSet} entities * @return {@link List} of {@link DistributionSet} entities
*/ */
public List<DistributionSet> createDistributionSets(final int number) { public List<DistributionSet> createDistributionSets(final int number) {
@@ -426,8 +389,7 @@ public class TestdataFactory {
/** /**
* Create a list of {@link DistributionSet}s without modules, i.e. incomplete. * Create a list of {@link DistributionSet}s without modules, i.e. incomplete.
* *
* @param number * @param number of {@link DistributionSet}s to create
* of {@link DistributionSet}s to create
* @return {@link List} of {@link DistributionSet} entities * @return {@link List} of {@link DistributionSet} entities
*/ */
public List<DistributionSet> createDistributionSetsWithoutModules(final int number) { public List<DistributionSet> createDistributionSetsWithoutModules(final int number) {
@@ -449,12 +411,9 @@ public class TestdataFactory {
* number and {@link DistributionSet#isRequiredMigrationStep()} * number and {@link DistributionSet#isRequiredMigrationStep()}
* <code>false</code>. * <code>false</code>.
* *
* @param prefix * @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description. * vendor and description.
* @param number * @param number of {@link DistributionSet}s to create
* of {@link DistributionSet}s to create
*
* @return {@link List} of {@link DistributionSet} entities * @return {@link List} of {@link DistributionSet} entities
*/ */
public List<DistributionSet> createDistributionSets(final String prefix, final int number) { public List<DistributionSet> createDistributionSets(final String prefix, final int number) {
@@ -472,11 +431,8 @@ public class TestdataFactory {
* {@link #DEFAULT_DESCRIPTION} and * {@link #DEFAULT_DESCRIPTION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>. * {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
* *
* @param name * @param name {@link DistributionSet#getName()}
* {@link DistributionSet#getName()} * @param version {@link DistributionSet#getVersion()}
* @param version
* {@link DistributionSet#getVersion()}
*
* @return {@link DistributionSet} entity * @return {@link DistributionSet} entity
*/ */
public DistributionSet createDistributionSetWithNoSoftwareModules(final String name, final String version) { public DistributionSet createDistributionSetWithNoSoftwareModules(final String name, final String version) {
@@ -489,9 +445,7 @@ public class TestdataFactory {
* Creates {@link Artifact}s for given {@link SoftwareModule} with a small text * Creates {@link Artifact}s for given {@link SoftwareModule} with a small text
* payload. * payload.
* *
* @param moduleId * @param moduleId the {@link Artifact}s belong to.
* the {@link Artifact}s belong to.
*
* @return {@link Artifact} entity. * @return {@link Artifact} entity.
*/ */
public List<Artifact> createArtifacts(final Long moduleId) { public List<Artifact> createArtifacts(final Long moduleId) {
@@ -508,15 +462,9 @@ public class TestdataFactory {
* Create an {@link Artifact} for given {@link SoftwareModule} with a small text * Create an {@link Artifact} for given {@link SoftwareModule} with a small text
* payload. * payload.
* *
* @param artifactData * @param artifactData the {@link Artifact} Inputstream
* the {@link Artifact} Inputstream * @param moduleId the {@link Artifact} belongs to
* * @param filename that was provided during upload.
* @param moduleId
* the {@link Artifact} belongs to
*
* @param filename
* that was provided during upload.
*
* @return {@link Artifact} entity. * @return {@link Artifact} entity.
*/ */
public Artifact createArtifact(final String artifactData, final Long moduleId, final String filename) { public Artifact createArtifact(final String artifactData, final Long moduleId, final String filename) {
@@ -529,18 +477,10 @@ public class TestdataFactory {
* Create an {@link Artifact} for given {@link SoftwareModule} with a small text * Create an {@link Artifact} for given {@link SoftwareModule} with a small text
* payload. * payload.
* *
* @param artifactData * @param artifactData the {@link Artifact} Inputstream
* the {@link Artifact} Inputstream * @param moduleId the {@link Artifact} belongs to
* * @param filename that was provided during upload.
* @param moduleId * @param fileSize the file size
* the {@link Artifact} belongs to
*
* @param filename
* that was provided during upload.
*
* @param fileSize
* the file size
*
* @return {@link Artifact} entity. * @return {@link Artifact} entity.
*/ */
public Artifact createArtifact(final byte[] artifactData, final Long moduleId, final String filename, public Artifact createArtifact(final byte[] artifactData, final Long moduleId, final String filename,
@@ -554,9 +494,7 @@ public class TestdataFactory {
* {@link #DEFAULT_VERSION} and random generated {@link Target#getDescription()} * {@link #DEFAULT_VERSION} and random generated {@link Target#getDescription()}
* in the repository. * in the repository.
* *
* @param typeKey * @param typeKey of the {@link SoftwareModuleType}
* of the {@link SoftwareModuleType}
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModule(final String typeKey) { public SoftwareModule createSoftwareModule(final String typeKey) {
@@ -568,7 +506,6 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random * with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository. * generated {@link Target#getDescription()} in the repository.
* *
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModuleApp() { public SoftwareModule createSoftwareModuleApp() {
@@ -580,10 +517,7 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random * with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository. * generated {@link Target#getDescription()} in the repository.
* *
* @param prefix * @param prefix added to name and version
* added to name and version
*
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModuleApp(final String prefix) { public SoftwareModule createSoftwareModuleApp(final String prefix) {
@@ -595,7 +529,6 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random * with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository. * generated {@link Target#getDescription()} in the repository.
* *
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModuleOs() { public SoftwareModule createSoftwareModuleOs() {
@@ -607,10 +540,7 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random * with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository. * generated {@link Target#getDescription()} in the repository.
* *
* @param prefix * @param prefix added to name and version
* added to name and version
*
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModuleOs(final String prefix) { public SoftwareModule createSoftwareModuleOs(final String prefix) {
@@ -622,11 +552,8 @@ public class TestdataFactory {
* {@link #DEFAULT_VERSION} and random generated {@link Target#getDescription()} * {@link #DEFAULT_VERSION} and random generated {@link Target#getDescription()}
* in the repository. * in the repository.
* *
* @param typeKey * @param typeKey of the {@link SoftwareModuleType}
* of the {@link SoftwareModuleType} * @param prefix added to name and version
* @param prefix
* added to name and version
*
* @return persisted {@link SoftwareModule}. * @return persisted {@link SoftwareModule}.
*/ */
public SoftwareModule createSoftwareModule(final String typeKey, final String prefix, final boolean encrypted) { public SoftwareModule createSoftwareModule(final String typeKey, final String prefix, final boolean encrypted) {
@@ -643,8 +570,7 @@ public class TestdataFactory {
} }
/** /**
* @param controllerId * @param controllerId of the target
* of the target
* @return persisted {@link Target} * @return persisted {@link Target}
*/ */
public Target createTarget(final String controllerId) { public Target createTarget(final String controllerId) {
@@ -652,10 +578,8 @@ public class TestdataFactory {
} }
/** /**
* @param controllerId * @param controllerId of the target
* of the target * @param targetName name of the target
* @param targetName
* name of the target
* @return persisted {@link Target} * @return persisted {@link Target}
*/ */
public Target createTarget(final String controllerId, final String targetName) { public Target createTarget(final String controllerId, final String targetName) {
@@ -673,12 +597,9 @@ public class TestdataFactory {
} }
/** /**
* @param controllerId * @param controllerId of the target
* of the target * @param targetName name of the target
* @param targetName * @param targetTypeId target type id
* name of the target
* @param targetTypeId
* target type id
* @return persisted {@link Target} * @return persisted {@link Target}
*/ */
public Target createTarget(final String controllerId, final String targetName, final Long targetTypeId) { public Target createTarget(final String controllerId, final String targetName, final Long targetTypeId) {
@@ -688,15 +609,6 @@ public class TestdataFactory {
return target; return target;
} }
private void assertTargetProperlyCreated(final Target target) {
assertThat(target.getCreatedBy()).isNotNull();
assertThat(target.getCreatedAt()).isNotNull();
assertThat(target.getLastModifiedBy()).isNotNull();
assertThat(target.getLastModifiedAt()).isNotNull();
assertThat(target.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
}
/** /**
* Creates {@link DistributionSet}s in repository including three * Creates {@link DistributionSet}s in repository including three
* {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} , * {@link SoftwareModule}s of types {@link #SM_TYPE_OS}, {@link #SM_TYPE_RT} ,
@@ -742,11 +654,8 @@ public class TestdataFactory {
/** /**
* Creates {@link DistributionSetType} in repository. * Creates {@link DistributionSetType} in repository.
* *
* @param dsTypeKey * @param dsTypeKey {@link DistributionSetType#getKey()}
* {@link DistributionSetType#getKey()} * @param dsTypeName {@link DistributionSetType#getName()}
* @param dsTypeName
* {@link DistributionSetType#getName()}
*
* @return persisted {@link DistributionSetType} * @return persisted {@link DistributionSetType}
*/ */
public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName) { public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName) {
@@ -759,15 +668,10 @@ public class TestdataFactory {
* Finds {@link DistributionSetType} in repository with given * Finds {@link DistributionSetType} in repository with given
* {@link DistributionSetType#getKey()} or creates if it does not exist yet. * {@link DistributionSetType#getKey()} or creates if it does not exist yet.
* *
* @param dsTypeKey * @param dsTypeKey {@link DistributionSetType#getKey()}
* {@link DistributionSetType#getKey()} * @param dsTypeName {@link DistributionSetType#getName()}
* @param dsTypeName * @param mandatory {@link DistributionSetType#getMandatoryModuleTypes()}
* {@link DistributionSetType#getName()} * @param optional {@link DistributionSetType#getOptionalModuleTypes()}
* @param mandatory
* {@link DistributionSetType#getMandatoryModuleTypes()}
* @param optional
* {@link DistributionSetType#getOptionalModuleTypes()}
*
* @return persisted {@link DistributionSetType} * @return persisted {@link DistributionSetType}
*/ */
public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName, public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName,
@@ -784,9 +688,7 @@ public class TestdataFactory {
* {@link SoftwareModuleType#getKey()} or creates if it does not exist yet with * {@link SoftwareModuleType#getKey()} or creates if it does not exist yet with
* {@link SoftwareModuleType#getMaxAssignments()} = 1. * {@link SoftwareModuleType#getMaxAssignments()} = 1.
* *
* @param key * @param key {@link SoftwareModuleType#getKey()}
* {@link SoftwareModuleType#getKey()}
*
* @return persisted {@link SoftwareModuleType} * @return persisted {@link SoftwareModuleType}
*/ */
public SoftwareModuleType findOrCreateSoftwareModuleType(final String key) { public SoftwareModuleType findOrCreateSoftwareModuleType(final String key) {
@@ -797,11 +699,8 @@ public class TestdataFactory {
* Finds {@link SoftwareModuleType} in repository with given * Finds {@link SoftwareModuleType} in repository with given
* {@link SoftwareModuleType#getKey()} or creates if it does not exist yet. * {@link SoftwareModuleType#getKey()} or creates if it does not exist yet.
* *
* @param key * @param key {@link SoftwareModuleType#getKey()}
* {@link SoftwareModuleType#getKey()} * @param maxAssignments {@link SoftwareModuleType#getMaxAssignments()}
* @param maxAssignments
* {@link SoftwareModuleType#getMaxAssignments()}
*
* @return persisted {@link SoftwareModuleType} * @return persisted {@link SoftwareModuleType}
*/ */
public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final int maxAssignments) { public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final int maxAssignments) {
@@ -814,15 +713,10 @@ public class TestdataFactory {
/** /**
* Creates a {@link DistributionSet}. * Creates a {@link DistributionSet}.
* *
* @param name * @param name {@link DistributionSet#getName()}
* {@link DistributionSet#getName()} * @param version {@link DistributionSet#getVersion()}
* @param version * @param type {@link DistributionSet#getType()}
* {@link DistributionSet#getVersion()} * @param modules {@link DistributionSet#getModules()}
* @param type
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
*
* @return the created {@link DistributionSet} * @return the created {@link DistributionSet}
*/ */
public DistributionSet createDistributionSet(final String name, final String version, public DistributionSet createDistributionSet(final String name, final String version,
@@ -835,17 +729,11 @@ public class TestdataFactory {
/** /**
* Generates {@link DistributionSet} object without persisting it. * Generates {@link DistributionSet} object without persisting it.
* *
* @param name * @param name {@link DistributionSet#getName()}
* {@link DistributionSet#getName()} * @param version {@link DistributionSet#getVersion()}
* @param version * @param type {@link DistributionSet#getType()}
* {@link DistributionSet#getVersion()} * @param modules {@link DistributionSet#getModules()}
* @param type * @param requiredMigrationStep {@link DistributionSet#isRequiredMigrationStep()}
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
* @param requiredMigrationStep
* {@link DistributionSet#isRequiredMigrationStep()}
*
* @return the created {@link DistributionSet} * @return the created {@link DistributionSet}
*/ */
public DistributionSet generateDistributionSet(final String name, final String version, public DistributionSet generateDistributionSet(final String name, final String version,
@@ -860,15 +748,10 @@ public class TestdataFactory {
/** /**
* Generates {@link DistributionSet} object without persisting it. * Generates {@link DistributionSet} object without persisting it.
* *
* @param name * @param name {@link DistributionSet#getName()}
* {@link DistributionSet#getName()} * @param version {@link DistributionSet#getVersion()}
* @param version * @param type {@link DistributionSet#getType()}
* {@link DistributionSet#getVersion()} * @param modules {@link DistributionSet#getModules()}
* @param type
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
*
* @return the created {@link DistributionSet} * @return the created {@link DistributionSet}
*/ */
public DistributionSet generateDistributionSet(final String name, final String version, public DistributionSet generateDistributionSet(final String name, final String version,
@@ -879,9 +762,7 @@ public class TestdataFactory {
/** /**
* builder method for generating a {@link DistributionSet}. * builder method for generating a {@link DistributionSet}.
* *
* @param name * @param name {@link DistributionSet#getName()}
* {@link DistributionSet#getName()}
*
* @return the generated {@link DistributionSet} * @return the generated {@link DistributionSet}
*/ */
public DistributionSet generateDistributionSet(final String name) { public DistributionSet generateDistributionSet(final String name) {
@@ -893,9 +774,7 @@ public class TestdataFactory {
* Creates {@link Target}s in repository and with {@link #DEFAULT_CONTROLLER_ID} * Creates {@link Target}s in repository and with {@link #DEFAULT_CONTROLLER_ID}
* as prefix for {@link Target#getControllerId()}. * as prefix for {@link Target#getControllerId()}.
* *
* @param number * @param number of {@link Target}s to create
* of {@link Target}s to create
*
* @return {@link List} of {@link Target} entities * @return {@link List} of {@link Target} entities
*/ */
public List<Target> createTargets(final int number) { public List<Target> createTargets(final int number) {
@@ -918,13 +797,9 @@ public class TestdataFactory {
/** /**
* Creates {@link Target}s in repository and with {@link TargetType}. * Creates {@link Target}s in repository and with {@link TargetType}.
* *
* @param number * @param number of {@link Target}s to create
* of {@link Target}s to create * @param controllerIdPrefix prefix for the controller id
* @param controllerIdPrefix * @param targetType targetType of targets to create
* prefix for the controller id
* @param targetType
* targetType of targets to create
*
* @return {@link List} of {@link Target} entities * @return {@link List} of {@link Target} entities
*/ */
public List<Target> createTargetsWithType(final int number, final String controllerIdPrefix, public List<Target> createTargetsWithType(final int number, final String controllerIdPrefix,
@@ -942,9 +817,7 @@ public class TestdataFactory {
/** /**
* Creates {@link Target}s in repository and with given targetIds. * Creates {@link Target}s in repository and with given targetIds.
* *
* @param targetIds * @param targetIds specifies the IDs of the targets
* specifies the IDs of the targets
*
* @return {@link List} of {@link Target} entities * @return {@link List} of {@link Target} entities
*/ */
public List<Target> createTargets(final String... targetIds) { public List<Target> createTargets(final String... targetIds) {
@@ -957,35 +830,12 @@ public class TestdataFactory {
return createTargets(targets); return createTargets(targets);
} }
/**
* Builds {@link Target} objects with given prefix for
* {@link Target#getControllerId()} followed by a number suffix.
*
* @param start
* value for the controllerId suffix
* @param numberOfTargets
* of {@link Target}s to generate
* @param controllerIdPrefix
* for {@link Target#getControllerId()} generation.
* @return list of {@link Target} objects
*/
private List<Target> generateTargets(final int start, final int numberOfTargets, final String controllerIdPrefix) {
final List<Target> targets = new ArrayList<>(numberOfTargets);
for (int i = start; i < start + numberOfTargets; i++) {
targets.add(entityFactory.target().create().controllerId(controllerIdPrefix + i).build());
}
return targets;
}
/** /**
* Builds {@link Target} objects with given prefix for * Builds {@link Target} objects with given prefix for
* {@link Target#getControllerId()} followed by a number suffix starting with 0. * {@link Target#getControllerId()} followed by a number suffix starting with 0.
* *
* @param numberOfTargets * @param numberOfTargets of {@link Target}s to generate
* of {@link Target}s to generate * @param controllerIdPrefix for {@link Target#getControllerId()} generation.
* @param controllerIdPrefix
* for {@link Target#getControllerId()} generation.
* @return list of {@link Target} objects * @return list of {@link Target} objects
*/ */
public List<Target> generateTargets(final int numberOfTargets, final String controllerIdPrefix) { public List<Target> generateTargets(final int numberOfTargets, final String controllerIdPrefix) {
@@ -995,10 +845,8 @@ public class TestdataFactory {
/** /**
* builds a set of {@link Target} fixtures from the given parameters. * builds a set of {@link Target} fixtures from the given parameters.
* *
* @param numberOfTargets * @param numberOfTargets number of targets to create
* number of targets to create * @param prefix prefix used for the controller ID and description
* @param prefix
* prefix used for the controller ID and description
* @return set of {@link Target} * @return set of {@link Target}
*/ */
public List<Target> createTargets(final int numberOfTargets, final String prefix) { public List<Target> createTargets(final int numberOfTargets, final String prefix) {
@@ -1008,12 +856,9 @@ public class TestdataFactory {
/** /**
* builds a set of {@link Target} fixtures from the given parameters. * builds a set of {@link Target} fixtures from the given parameters.
* *
* @param numberOfTargets * @param numberOfTargets number of targets to create
* number of targets to create * @param controllerIdPrefix prefix used for the controller ID
* @param controllerIdPrefix * @param descriptionPrefix prefix used for the description
* prefix used for the controller ID
* @param descriptionPrefix
* prefix used for the description
* @return set of {@link Target} * @return set of {@link Target}
*/ */
public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix, public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix,
@@ -1027,25 +872,13 @@ public class TestdataFactory {
return createTargets(targets); return createTargets(targets);
} }
private List<Target> createTargets(final Collection<TargetCreate> targetCreates) {
// init new instance of array list since the TargetManagement#create
// will
// provide a unmodifiable list
final List<Target> createdTargets = targetManagement.create(targetCreates);
return new ArrayList<>(createdTargets);
}
/** /**
* builds a set of {@link Target} fixtures from the given parameters. * builds a set of {@link Target} fixtures from the given parameters.
* *
* @param numberOfTargets * @param numberOfTargets number of targets to create
* number of targets to create * @param controllerIdPrefix prefix used for the controller ID
* @param controllerIdPrefix * @param descriptionPrefix prefix used for the description
* prefix used for the controller ID * @param lastTargetQuery last time the target polled
* @param descriptionPrefix
* prefix used for the description
* @param lastTargetQuery
* last time the target polled
* @return set of {@link Target} * @return set of {@link Target}
*/ */
public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix, public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix,
@@ -1062,10 +895,8 @@ public class TestdataFactory {
/** /**
* Create a set of {@link TargetTag}s. * Create a set of {@link TargetTag}s.
* *
* @param number * @param number number of {@link TargetTag}. to be created
* number of {@link TargetTag}. to be created * @param tagPrefix prefix for the {@link TargetTag#getName()}
* @param tagPrefix
* prefix for the {@link TargetTag#getName()}
* @return the created set of {@link TargetTag}s * @return the created set of {@link TargetTag}s
*/ */
public List<TargetTag> createTargetTags(final int number, final String tagPrefix) { public List<TargetTag> createTargetTags(final int number, final String tagPrefix) {
@@ -1082,9 +913,7 @@ public class TestdataFactory {
/** /**
* Creates {@link DistributionSetTag}s in repository. * Creates {@link DistributionSetTag}s in repository.
* *
* @param number * @param number of {@link DistributionSetTag}s
* of {@link DistributionSetTag}s
*
* @return the persisted {@link DistributionSetTag}s * @return the persisted {@link DistributionSetTag}s
*/ */
public List<DistributionSetTag> createDistributionSetTags(final int number) { public List<DistributionSetTag> createDistributionSetTags(final int number) {
@@ -1098,23 +927,12 @@ public class TestdataFactory {
return distributionSetTagManagement.create(result); return distributionSetTagManagement.create(result);
} }
private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA,
final Collection<String> msgs) {
return controllerManagament.addUpdateActionStatus(
entityFactory.actionStatus().create(updActA.getId()).status(status).messages(msgs));
}
/** /**
* Append {@link ActionStatus} to all {@link Action}s of given {@link Target}s. * Append {@link ActionStatus} to all {@link Action}s of given {@link Target}s.
* *
* @param targets * @param targets to add {@link ActionStatus}
* to add {@link ActionStatus} * @param status to add
* @param status * @param message to add
* to add
* @param message
* to add
*
* @return updated {@link Action}. * @return updated {@link Action}.
*/ */
public List<Action> sendUpdateActionStatusToTargets(final Collection<Target> targets, final Status status, public List<Action> sendUpdateActionStatusToTargets(final Collection<Target> targets, final Status status,
@@ -1125,13 +943,9 @@ public class TestdataFactory {
/** /**
* Append {@link ActionStatus} to all {@link Action}s of given {@link Target}s. * Append {@link ActionStatus} to all {@link Action}s of given {@link Target}s.
* *
* @param targets * @param targets to add {@link ActionStatus}
* to add {@link ActionStatus} * @param status to add
* @param status * @param msgs to add
* to add
* @param msgs
* to add
*
* @return updated {@link Action}. * @return updated {@link Action}.
*/ */
public List<Action> sendUpdateActionStatusToTargets(final Collection<Target> targets, final Status status, public List<Action> sendUpdateActionStatusToTargets(final Collection<Target> targets, final Status status,
@@ -1159,20 +973,13 @@ public class TestdataFactory {
/** /**
* Creates rollout based on given parameters. * Creates rollout based on given parameters.
* *
* @param rolloutName * @param rolloutName of the {@link Rollout}
* of the {@link Rollout} * @param rolloutDescription of the {@link Rollout}
* @param rolloutDescription * @param groupSize of the {@link Rollout}
* of the {@link Rollout} * @param filterQuery to identify the {@link Target}s
* @param groupSize * @param distributionSet to assign
* of the {@link Rollout} * @param successCondition to switch to next group
* @param filterQuery * @param errorCondition to switch to next group
* to identify the {@link Target}s
* @param distributionSet
* to assign
* @param successCondition
* to switch to next group
* @param errorCondition
* to switch to next group
* @return created {@link Rollout} * @return created {@link Rollout}
*/ */
public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription, public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription,
@@ -1204,29 +1011,20 @@ public class TestdataFactory {
return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet, return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet,
successCondition, errorCondition, actionType, weight, confirmationRequired, false); successCondition, errorCondition, actionType, weight, confirmationRequired, false);
} }
/** /**
* Creates rollout based on given parameters. * Creates rollout based on given parameters.
* *
* @param rolloutName * @param rolloutName of the {@link Rollout}
* of the {@link Rollout} * @param rolloutDescription of the {@link Rollout}
* @param rolloutDescription * @param groupSize of the {@link Rollout}
* of the {@link Rollout} * @param filterQuery to identify the {@link Target}s
* @param groupSize * @param distributionSet to assign
* of the {@link Rollout} * @param successCondition to switch to next group
* @param filterQuery * @param errorCondition to switch to next group
* to identify the {@link Target}s * @param actionType the type of the Rollout
* @param distributionSet * @param weight weight of the Rollout
* to assign * @param confirmationRequired if the confirmation is required (considered with confirmation flow
* @param successCondition
* to switch to next group
* @param errorCondition
* to switch to next group
* @param actionType
* the type of the Rollout
* @param weight
* weight of the Rollout
* @param confirmationRequired
* if the confirmation is required (considered with confirmation flow
* active) * active)
* @param dynamic is dynamic * @param dynamic is dynamic
* @return created {@link Rollout} * @return created {@link Rollout}
@@ -1238,6 +1036,7 @@ public class TestdataFactory {
return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet, return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet,
successCondition, errorCondition, actionType, weight, confirmationRequired, dynamic, null); successCondition, errorCondition, actionType, weight, confirmationRequired, dynamic, null);
} }
public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription, public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription,
final int groupSize, final String filterQuery, final DistributionSet distributionSet, final int groupSize, final String filterQuery, final DistributionSet distributionSet,
final String successCondition, final String errorCondition, final Action.ActionType actionType, final String successCondition, final String errorCondition, final Action.ActionType actionType,
@@ -1264,8 +1063,7 @@ public class TestdataFactory {
* Create {@link Rollout} with a new {@link DistributionSet} and * Create {@link Rollout} with a new {@link DistributionSet} and
* {@link Target}s. * {@link Target}s.
* *
* @param prefix * @param prefix for rollouts name, description, {@link Target#getControllerId()}
* for rollouts name, description, {@link Target#getControllerId()}
* filter * filter
* @return created {@link Rollout} * @return created {@link Rollout}
*/ */
@@ -1302,32 +1100,14 @@ public class TestdataFactory {
return startAndReloadRollout(createRollout()); return startAndReloadRollout(createRollout());
} }
private Rollout startAndReloadRollout(final Rollout rollout) {
rolloutManagement.start(rollout.getId());
// Run here, because scheduler is disabled during tests
rolloutHandler.handleAll();
return reloadRollout(rollout);
}
private Rollout reloadRollout(final Rollout rollout) {
return rolloutManagement.get(rollout.getId()).orElseThrow(NoSuchElementException::new);
}
/** /**
* Create the data for a simple rollout scenario * Create the data for a simple rollout scenario
* *
* @param amountTargetsForRollout * @param amountTargetsForRollout the amount of targets used for the rollout
* the amount of targets used for the rollout * @param amountOtherTargets amount of other targets not included in the rollout
* @param amountOtherTargets * @param amountGroups the size of the rollout group
* amount of other targets not included in the rollout * @param successCondition success condition
* @param amountGroups * @param errorCondition error condition
* the size of the rollout group
* @param successCondition
* success condition
* @param errorCondition
* error condition
* @return the created {@link Rollout} * @return the created {@link Rollout}
*/ */
public Rollout createAndStartRollout(final int amountTargetsForRollout, final int amountOtherTargets, public Rollout createAndStartRollout(final int amountTargetsForRollout, final int amountOtherTargets,
@@ -1341,16 +1121,11 @@ public class TestdataFactory {
/** /**
* Create the data for a simple rollout scenario * Create the data for a simple rollout scenario
* *
* @param amountTargetsForRollout * @param amountTargetsForRollout the amount of targets used for the rollout
* the amount of targets used for the rollout * @param amountOtherTargets amount of other targets not included in the rollout
* @param amountOtherTargets * @param amountOfGroups the size of the rollout group
* amount of other targets not included in the rollout * @param successCondition success condition
* @param amountOfGroups * @param errorCondition error condition
* the size of the rollout group
* @param successCondition
* success condition
* @param errorCondition
* error condition
* @return the created {@link Rollout} * @return the created {@link Rollout}
*/ */
public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout, public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout,
@@ -1363,20 +1138,13 @@ public class TestdataFactory {
/** /**
* Create the data for a simple rollout scenario * Create the data for a simple rollout scenario
* *
* @param amountTargetsForRollout * @param amountTargetsForRollout the amount of targets used for the rollout
* the amount of targets used for the rollout * @param amountOtherTargets amount of other targets not included in the rollout
* @param amountOtherTargets * @param amountOfGroups the size of the rollout group
* amount of other targets not included in the rollout * @param successCondition success condition
* @param amountOfGroups * @param errorCondition error condition
* the size of the rollout group * @param actionType action Type
* @param successCondition * @param weight weight
* success condition
* @param errorCondition
* error condition
* @param actionType
* action Type
* @param weight
* weight
* @return the created {@link Rollout} * @return the created {@link Rollout}
*/ */
public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout, public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout,
@@ -1395,8 +1163,7 @@ public class TestdataFactory {
* Create the soft deleted {@link Rollout} with a new {@link DistributionSet} * Create the soft deleted {@link Rollout} with a new {@link DistributionSet}
* and {@link Target}s. * and {@link Target}s.
* *
* @param prefix * @param prefix for rollouts name, description, {@link Target#getControllerId()}
* for rollouts name, description, {@link Target#getControllerId()}
* filter * filter
* @return created {@link Rollout} * @return created {@link Rollout}
*/ */
@@ -1414,9 +1181,7 @@ public class TestdataFactory {
* {@link TargetType#getName()} or creates if it does not exist yet. No ds types * {@link TargetType#getName()} or creates if it does not exist yet. No ds types
* are assigned on creation. * are assigned on creation.
* *
* @param targetTypeName * @param targetTypeName {@link TargetType#getName()}
* {@link TargetType#getName()}
*
* @return persisted {@link TargetType} * @return persisted {@link TargetType}
*/ */
public TargetType findOrCreateTargetType(final String targetTypeName) { public TargetType findOrCreateTargetType(final String targetTypeName) {
@@ -1431,9 +1196,7 @@ public class TestdataFactory {
* {@link TargetType#getName()}. Compatible distribution set types are assigned * {@link TargetType#getName()}. Compatible distribution set types are assigned
* on creation * on creation
* *
* @param targetTypeName * @param targetTypeName {@link TargetType#getName()}
* {@link TargetType#getName()}
*
* @return persisted {@link TargetType} * @return persisted {@link TargetType}
*/ */
public TargetType createTargetType(final String targetTypeName, final List<DistributionSetType> compatibleDsTypes) { public TargetType createTargetType(final String targetTypeName, final List<DistributionSetType> compatibleDsTypes) {
@@ -1446,9 +1209,7 @@ public class TestdataFactory {
* Creates {@link TargetType} in repository with given * Creates {@link TargetType} in repository with given
* {@link TargetType#getName()}. No ds types are assigned on creation. * {@link TargetType#getName()}. No ds types are assigned on creation.
* *
* @param targetTypePrefix * @param targetTypePrefix {@link TargetType#getName()}
* {@link TargetType#getName()}
*
* @return persisted {@link TargetType} * @return persisted {@link TargetType}
*/ */
public List<TargetType> createTargetTypes(final String targetTypePrefix, final int count) { public List<TargetType> createTargetTypes(final String targetTypePrefix, final int count) {
@@ -1498,4 +1259,67 @@ public class TestdataFactory {
return RandomStringUtils.randomAlphanumeric(len); return RandomStringUtils.randomAlphanumeric(len);
} }
private void addTestModuleMetadata(final SoftwareModule module) {
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata().create(module.getId())
.key(VISIBLE_SM_MD_KEY).value(VISIBLE_SM_MD_VALUE).targetVisible(true));
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata().create(module.getId())
.key(INVISIBLE_SM_MD_KEY).value(INVISIBLE_SM_MD_VALUE).targetVisible(false));
}
private void assertTargetProperlyCreated(final Target target) {
assertThat(target.getCreatedBy()).isNotNull();
assertThat(target.getCreatedAt()).isNotNull();
assertThat(target.getLastModifiedBy()).isNotNull();
assertThat(target.getLastModifiedAt()).isNotNull();
assertThat(target.getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
}
/**
* Builds {@link Target} objects with given prefix for
* {@link Target#getControllerId()} followed by a number suffix.
*
* @param start value for the controllerId suffix
* @param numberOfTargets of {@link Target}s to generate
* @param controllerIdPrefix for {@link Target#getControllerId()} generation.
* @return list of {@link Target} objects
*/
private List<Target> generateTargets(final int start, final int numberOfTargets, final String controllerIdPrefix) {
final List<Target> targets = new ArrayList<>(numberOfTargets);
for (int i = start; i < start + numberOfTargets; i++) {
targets.add(entityFactory.target().create().controllerId(controllerIdPrefix + i).build());
}
return targets;
}
private List<Target> createTargets(final Collection<TargetCreate> targetCreates) {
// init new instance of array list since the TargetManagement#create
// will
// provide a unmodifiable list
final List<Target> createdTargets = targetManagement.create(targetCreates);
return new ArrayList<>(createdTargets);
}
private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA,
final Collection<String> msgs) {
return controllerManagament.addUpdateActionStatus(
entityFactory.actionStatus().create(updActA.getId()).status(status).messages(msgs));
}
private Rollout startAndReloadRollout(final Rollout rollout) {
rolloutManagement.start(rollout.getId());
// Run here, because scheduler is disabled during tests
rolloutHandler.handleAll();
return reloadRollout(rollout);
}
private Rollout reloadRollout(final Rollout rollout) {
return rolloutManagement.get(rollout.getId()).orElseThrow(NoSuchElementException::new);
}
} }

View File

@@ -9,16 +9,16 @@
*/ */
package org.eclipse.hawkbit.repository.test.util; package org.eclipse.hawkbit.repository.test.util;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited; import java.lang.annotation.Inherited;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
/** /**
* Annotation to run test classes or test methods with a specific user with * Annotation to run test classes or test methods with a specific user with
* specific permissions. * specific permissions.
@@ -81,6 +81,7 @@ public @interface WithUser {
boolean controller() default false; boolean controller() default false;
class WithTenantAwareUserSecurityContextFactory implements WithSecurityContextFactory<WithUser> { class WithTenantAwareUserSecurityContextFactory implements WithSecurityContextFactory<WithUser> {
@Override @Override
public SecurityContext createSecurityContext(final WithUser withTenantAwareUser) { public SecurityContext createSecurityContext(final WithUser withTenantAwareUser) {
return new SecurityContextSwitch.WithUserSecurityContext(withTenantAwareUser); return new SecurityContextSwitch.WithUserSecurityContext(withTenantAwareUser);