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
-->
<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">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@@ -49,7 +49,6 @@ import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.cloud.bus.ConditionalOnBusEnabled;
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.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import static java.util.Objects.requireNonNull;
/**
* Spring context configuration required for Dev.Environment.
*/
@@ -86,6 +83,29 @@ import static java.util.Objects.requireNonNull;
@PropertySource("classpath:/hawkbit-test-defaults.properties")
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.
*/
@@ -154,6 +174,43 @@ public class TestConfiguration implements AsyncConfigurer {
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 final ApplicationEventFilter applicationEventFilter;
@@ -171,66 +228,4 @@ public class TestConfiguration implements AsyncConfigurer {
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
* keep the same.
*
* @param publisher
* the {@link ApplicationEventPublisher} to publish the marker
* @param publisher the {@link ApplicationEventPublisher} to publish the marker
* event to
*/
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 long serialVersionUID = 1L;
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.extension.ExtendWith;
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.cloud.bus.ServiceMatcher;
import org.springframework.cloud.stream.binder.test.TestChannelBinderConfiguration;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Import;
import org.springframework.data.auditing.AuditingHandler;
@@ -93,10 +93,10 @@ import org.springframework.test.context.TestPropertySource;
@Slf4j
@ActiveProfiles({ "test" })
@ExtendWith({ JUnitTestLoggerExtension.class , SharedSqlTestDatabaseExtension.class })
@ExtendWith({ JUnitTestLoggerExtension.class, SharedSqlTestDatabaseExtension.class })
@WithUser(principal = "bumlux", allSpPermissions = true, authorities = { CONTROLLER_ROLE, SYSTEM_ROLE })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ContextConfiguration(classes = { TestConfiguration.class})
@ContextConfiguration(classes = { TestConfiguration.class })
@Import(TestChannelBinderConfiguration.class)
// destroy the context after each test class because otherwise we get problem
// when context is
@@ -216,6 +216,109 @@ public abstract class AbstractIntegrationTest {
@Autowired
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) {
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
* maintenance schedule.
*
* @param dsID
* is the ID for the distribution set being assigned
* @param controllerId
* is the ID for the controller to which the distribution set is
* @param dsID is the ID for the distribution set being assigned
* @param controllerId is the ID for the controller to which the distribution set is
* being assigned
* @param maintenanceWindowSchedule
* is the cron expression to be used for scheduling the
* @param maintenanceWindowSchedule is the cron expression to be used for scheduling the
* maintenance window. Expression has 6 mandatory fields and 1
* last optional field: "second minute hour dayofmonth month
* weekday year"
* @param maintenanceWindowDuration
* in HH:mm:ss format specifying the duration of a maintenance
* @param maintenanceWindowDuration in HH:mm:ss format specifying the duration of a maintenance
* window, for example 00:30:00 for 30 minutes
* @param maintenanceWindowTimeZone
* is the time zone specified as +/-hh:mm offset from UTC, for
* @param maintenanceWindowTimeZone 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
* start time of a maintenance window calculated based on the
* cron expression is relative to this time zone
*
* @return result of the assignment as { @link
* DistributionSetAssignmentResult}.
*/
@@ -355,10 +452,6 @@ public abstract class AbstractIntegrationTest {
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) {
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));
}
@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() {
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)));
}
private static String upperCaseVariant(final String key) {
return key.toUpperCase().replace('.', '_');
}
public String getDatabase() {
return database;
}
@@ -85,4 +81,8 @@ public class DatasourceContext {
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;
import static org.eclipse.hawkbit.repository.test.util.DatasourceContext.SPRING_DATASOURCE_URL_KEY;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.AfterAllCallback;
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.
*/

View File

@@ -34,6 +34,6 @@ public class H2TestDatabase extends AbstractSqlTestDatabase {
@Override
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;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Hash digest utility.
*/
@@ -27,8 +27,7 @@ public final class HashGeneratorUtils {
/**
* Generates a MD5 cryptographic string.
*
* @param message
* the plain message
* @param message the plain message
* @return the cryptographic string
*/
public static String generateMD5(final byte[] message) {
@@ -38,8 +37,7 @@ public final class HashGeneratorUtils {
/**
* Generates a SHA-1 cryptographic string.
*
* @param message
* the plain message
* @param message the plain message
* @return the cryptographic string
*/
public static String generateSHA1(final byte[] message) {
@@ -49,8 +47,7 @@ public final class HashGeneratorUtils {
/**
* Generates a SHA-256 cryptographic string.
*
* @param message
* the plain message
* @param message the plain message
* @return the cryptographic string
*/
public static String generateSHA256(final byte[] message) {

View File

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

View File

@@ -27,14 +27,6 @@ public class RolloutTestApprovalStrategy implements RolloutApprovalStrategy {
return approvalNeeded;
}
public void setApprovalNeeded(boolean approvalNeeded) {
this.approvalNeeded = approvalNeeded;
}
public void setApproveDecidedBy(final String user) {
this.approvalDecidedBy = user;
}
@Override
public void onApprovalRequired(Rollout rollout) {
// do nothing, as no action is needed when testing
@@ -44,4 +36,12 @@ public class RolloutTestApprovalStrategy implements RolloutApprovalStrategy {
public String getApprovalUser(Rollout rollout) {
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 =
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 {
createTenant(DEFAULT_TENANT);
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) {
return withUserAndTenant(principal, DEFAULT_TENANT, true, false, true, authorities);
}
@@ -81,6 +67,20 @@ public class SecurityContextSwitch {
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,
final boolean allSpPermission, final boolean controller, final String... authorities) {
return new WithUser() {
@@ -100,6 +100,16 @@ public class SecurityContextSwitch {
return null;
}
@Override
public String tenantId() {
return tenant;
}
@Override
public boolean autoCreateTenant() {
return autoCreateTenant;
}
@Override
public String[] authorities() {
return authorities;
@@ -115,16 +125,6 @@ public class SecurityContextSwitch {
return new String[0];
}
@Override
public String tenantId() {
return tenant;
}
@Override
public boolean autoCreateTenant() {
return autoCreateTenant;
}
@Override
public boolean controller() {
return controller;
@@ -145,11 +145,6 @@ public class SecurityContextSwitch {
}
}
@Override
public void setAuthentication(final Authentication authentication) {
// nothing to do
}
@Override
public Authentication getAuthentication() {
final String[] authorities;
@@ -166,15 +161,14 @@ public class SecurityContextSwitch {
return testingAuthenticationToken;
}
private String[] getAllAuthorities(final String[] additionalAuthorities, final String[] notInclude) {
final List<String> permissions = SpPermission.getAllAuthorities();
if (notInclude != null) {
permissions.removeAll(Arrays.asList(notInclude));
@Override
public void setAuthentication(final Authentication authentication) {
// nothing to do
}
if (additionalAuthorities != null) {
permissions.addAll(Arrays.asList(additionalAuthorities));
}
return permissions.toArray(new String[0]);
@Override
public int hashCode() {
return annotation.hashCode();
}
@Override
@@ -186,9 +180,15 @@ public class SecurityContextSwitch {
}
}
@Override
public int hashCode() {
return annotation.hashCode();
private String[] getAllAuthorities(final String[] additionalAuthorities, final String[] notInclude) {
final List<String> permissions = SpPermission.getAllAuthorities();
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);
}
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) {
AbstractSqlTestDatabase database;
@@ -79,4 +72,11 @@ public class SharedSqlTestDatabaseExtension implements BeforeAllCallback {
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;
public class TargetTestData {
public static final String ATTRIBUTE_KEY_TOO_LONG;
public static final String ATTRIBUTE_KEY_VALID;
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);
}
private TargetTestData() {
// nothing to do here
}
private static String generateRandomStringWithLength(final int length, final Random rand) {
final StringBuilder randomStringBuilder = new StringBuilder(length);
final int lowercaseACode = 97;
@@ -39,8 +44,4 @@ public class TargetTestData {
}
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 DistributionSet#isRequiredMigrationStep()} <code>false</code>.
*
* @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.
*
* @return {@link DistributionSet} entity.
*/
public DistributionSet createDistributionSet(final String prefix) {
@@ -232,9 +230,7 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
*
* @param modules
* of {@link DistributionSet#getModules()}
*
* @param modules of {@link DistributionSet#getModules()}
* @return {@link DistributionSet} entity.
*/
public DistributionSet createDistributionSet(final Collection<SoftwareModule> modules) {
@@ -247,12 +243,9 @@ public class TestdataFactory {
* {@link #SM_TYPE_APP} with {@link #DEFAULT_VERSION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
*
* @param modules
* of {@link DistributionSet#getModules()}
* @param prefix
* for {@link SoftwareModule}s and {@link DistributionSet}s name,
* @param modules of {@link DistributionSet#getModules()}
* @param prefix for {@link SoftwareModule}s and {@link DistributionSet}s name,
* vendor and description.
*
* @return {@link DistributionSet} entity.
*/
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 #SM_TYPE_APP} with {@link #DEFAULT_VERSION}.
*
* @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.
* @param isRequiredMigrationStep
* for {@link DistributionSet#isRequiredMigrationStep()}
*
* @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* @return {@link DistributionSet} entity.
*/
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 DistributionSet#isRequiredMigrationStep()} <code>false</code>.
*
* @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.
* @param tags
* DistributionSet tags
*
* @param tags DistributionSet tags
* @return {@link DistributionSet} entity.
*/
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 #SM_TYPE_APP}.
*
* @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.
* @param version
* {@link DistributionSet#getVersion()} and
* @param version {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random number.
* @param isRequiredMigrationStep
* for {@link DistributionSet#isRequiredMigrationStep()}
*
* @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* @return {@link DistributionSet} entity.
*/
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 SoftwareModuleMetadata#isTargetVisible()}
*
* @param set
* to add metadata to
* @param set to add metadata to
*/
public void addSoftwareModuleMetadata(final DistributionSet set) {
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.
*
* @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.
* @param version
* {@link DistributionSet#getVersion()} and
* @param version {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random number.
* @param isRequiredMigrationStep
* for {@link DistributionSet#isRequiredMigrationStep()}
* @param modules
* for {@link DistributionSet#getModules()}
*
* @param isRequiredMigrationStep for {@link DistributionSet#isRequiredMigrationStep()}
* @param modules for {@link DistributionSet#getModules()}
* @return {@link DistributionSet} entity.
*/
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 #SM_TYPE_APP}.
*
* @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.
* @param version
* {@link DistributionSet#getVersion()} and
* @param version {@link DistributionSet#getVersion()} and
* {@link SoftwareModule#getVersion()} extended by a random
* number.updat
* @param tags
* DistributionSet tags
*
* @param tags DistributionSet tags
* @return {@link DistributionSet} entity.
*/
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()}
* <code>false</code>.
*
* @param number
* of {@link DistributionSet}s to create
*
* @param number of {@link DistributionSet}s to create
* @return {@link List} of {@link DistributionSet} entities
*/
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.
*
* @param number
* of {@link DistributionSet}s to create
* @param number of {@link DistributionSet}s to create
* @return {@link List} of {@link DistributionSet} entities
*/
public List<DistributionSet> createDistributionSetsWithoutModules(final int number) {
@@ -449,12 +411,9 @@ public class TestdataFactory {
* number and {@link DistributionSet#isRequiredMigrationStep()}
* <code>false</code>.
*
* @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.
* @param number
* of {@link DistributionSet}s to create
*
* @param number of {@link DistributionSet}s to create
* @return {@link List} of {@link DistributionSet} entities
*/
public List<DistributionSet> createDistributionSets(final String prefix, final int number) {
@@ -472,11 +431,8 @@ public class TestdataFactory {
* {@link #DEFAULT_DESCRIPTION} and
* {@link DistributionSet#isRequiredMigrationStep()} <code>false</code>.
*
* @param name
* {@link DistributionSet#getName()}
* @param version
* {@link DistributionSet#getVersion()}
*
* @param name {@link DistributionSet#getName()}
* @param version {@link DistributionSet#getVersion()}
* @return {@link DistributionSet} entity
*/
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
* payload.
*
* @param moduleId
* the {@link Artifact}s belong to.
*
* @param moduleId the {@link Artifact}s belong to.
* @return {@link Artifact} entity.
*/
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
* payload.
*
* @param artifactData
* the {@link Artifact} Inputstream
*
* @param moduleId
* the {@link Artifact} belongs to
*
* @param filename
* that was provided during upload.
*
* @param artifactData the {@link Artifact} Inputstream
* @param moduleId the {@link Artifact} belongs to
* @param filename that was provided during upload.
* @return {@link Artifact} entity.
*/
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
* payload.
*
* @param artifactData
* the {@link Artifact} Inputstream
*
* @param moduleId
* the {@link Artifact} belongs to
*
* @param filename
* that was provided during upload.
*
* @param fileSize
* the file size
*
* @param artifactData the {@link Artifact} Inputstream
* @param moduleId the {@link Artifact} belongs to
* @param filename that was provided during upload.
* @param fileSize the file size
* @return {@link Artifact} entity.
*/
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()}
* in the repository.
*
* @param typeKey
* of the {@link SoftwareModuleType}
*
* @param typeKey of the {@link SoftwareModuleType}
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModule(final String typeKey) {
@@ -568,7 +506,6 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository.
*
*
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModuleApp() {
@@ -580,10 +517,7 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository.
*
* @param prefix
* added to name and version
*
*
* @param prefix added to name and version
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModuleApp(final String prefix) {
@@ -595,7 +529,6 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository.
*
*
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModuleOs() {
@@ -607,10 +540,7 @@ public class TestdataFactory {
* with {@link #DEFAULT_VENDOR} and {@link #DEFAULT_VERSION} and random
* generated {@link Target#getDescription()} in the repository.
*
* @param prefix
* added to name and version
*
*
* @param prefix added to name and version
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModuleOs(final String prefix) {
@@ -622,11 +552,8 @@ public class TestdataFactory {
* {@link #DEFAULT_VERSION} and random generated {@link Target#getDescription()}
* in the repository.
*
* @param typeKey
* of the {@link SoftwareModuleType}
* @param prefix
* added to name and version
*
* @param typeKey of the {@link SoftwareModuleType}
* @param prefix added to name and version
* @return persisted {@link SoftwareModule}.
*/
public SoftwareModule createSoftwareModule(final String typeKey, final String prefix, final boolean encrypted) {
@@ -643,8 +570,7 @@ public class TestdataFactory {
}
/**
* @param controllerId
* of the target
* @param controllerId of the target
* @return persisted {@link Target}
*/
public Target createTarget(final String controllerId) {
@@ -652,10 +578,8 @@ public class TestdataFactory {
}
/**
* @param controllerId
* of the target
* @param targetName
* name of the target
* @param controllerId of the target
* @param targetName name of the target
* @return persisted {@link Target}
*/
public Target createTarget(final String controllerId, final String targetName) {
@@ -673,12 +597,9 @@ public class TestdataFactory {
}
/**
* @param controllerId
* of the target
* @param targetName
* name of the target
* @param targetTypeId
* target type id
* @param controllerId of the target
* @param targetName name of the target
* @param targetTypeId target type id
* @return persisted {@link Target}
*/
public Target createTarget(final String controllerId, final String targetName, final Long targetTypeId) {
@@ -688,15 +609,6 @@ public class TestdataFactory {
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
* {@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.
*
* @param dsTypeKey
* {@link DistributionSetType#getKey()}
* @param dsTypeName
* {@link DistributionSetType#getName()}
*
* @param dsTypeKey {@link DistributionSetType#getKey()}
* @param dsTypeName {@link DistributionSetType#getName()}
* @return persisted {@link DistributionSetType}
*/
public DistributionSetType findOrCreateDistributionSetType(final String dsTypeKey, final String dsTypeName) {
@@ -759,15 +668,10 @@ public class TestdataFactory {
* Finds {@link DistributionSetType} in repository with given
* {@link DistributionSetType#getKey()} or creates if it does not exist yet.
*
* @param dsTypeKey
* {@link DistributionSetType#getKey()}
* @param dsTypeName
* {@link DistributionSetType#getName()}
* @param mandatory
* {@link DistributionSetType#getMandatoryModuleTypes()}
* @param optional
* {@link DistributionSetType#getOptionalModuleTypes()}
*
* @param dsTypeKey {@link DistributionSetType#getKey()}
* @param dsTypeName {@link DistributionSetType#getName()}
* @param mandatory {@link DistributionSetType#getMandatoryModuleTypes()}
* @param optional {@link DistributionSetType#getOptionalModuleTypes()}
* @return persisted {@link DistributionSetType}
*/
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#getMaxAssignments()} = 1.
*
* @param key
* {@link SoftwareModuleType#getKey()}
*
* @param key {@link SoftwareModuleType#getKey()}
* @return persisted {@link SoftwareModuleType}
*/
public SoftwareModuleType findOrCreateSoftwareModuleType(final String key) {
@@ -797,11 +699,8 @@ public class TestdataFactory {
* Finds {@link SoftwareModuleType} in repository with given
* {@link SoftwareModuleType#getKey()} or creates if it does not exist yet.
*
* @param key
* {@link SoftwareModuleType#getKey()}
* @param maxAssignments
* {@link SoftwareModuleType#getMaxAssignments()}
*
* @param key {@link SoftwareModuleType#getKey()}
* @param maxAssignments {@link SoftwareModuleType#getMaxAssignments()}
* @return persisted {@link SoftwareModuleType}
*/
public SoftwareModuleType findOrCreateSoftwareModuleType(final String key, final int maxAssignments) {
@@ -814,15 +713,10 @@ public class TestdataFactory {
/**
* Creates a {@link DistributionSet}.
*
* @param name
* {@link DistributionSet#getName()}
* @param version
* {@link DistributionSet#getVersion()}
* @param type
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
*
* @param name {@link DistributionSet#getName()}
* @param version {@link DistributionSet#getVersion()}
* @param type {@link DistributionSet#getType()}
* @param modules {@link DistributionSet#getModules()}
* @return the created {@link DistributionSet}
*/
public DistributionSet createDistributionSet(final String name, final String version,
@@ -835,17 +729,11 @@ public class TestdataFactory {
/**
* Generates {@link DistributionSet} object without persisting it.
*
* @param name
* {@link DistributionSet#getName()}
* @param version
* {@link DistributionSet#getVersion()}
* @param type
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
* @param requiredMigrationStep
* {@link DistributionSet#isRequiredMigrationStep()}
*
* @param name {@link DistributionSet#getName()}
* @param version {@link DistributionSet#getVersion()}
* @param type {@link DistributionSet#getType()}
* @param modules {@link DistributionSet#getModules()}
* @param requiredMigrationStep {@link DistributionSet#isRequiredMigrationStep()}
* @return the created {@link DistributionSet}
*/
public DistributionSet generateDistributionSet(final String name, final String version,
@@ -860,15 +748,10 @@ public class TestdataFactory {
/**
* Generates {@link DistributionSet} object without persisting it.
*
* @param name
* {@link DistributionSet#getName()}
* @param version
* {@link DistributionSet#getVersion()}
* @param type
* {@link DistributionSet#getType()}
* @param modules
* {@link DistributionSet#getModules()}
*
* @param name {@link DistributionSet#getName()}
* @param version {@link DistributionSet#getVersion()}
* @param type {@link DistributionSet#getType()}
* @param modules {@link DistributionSet#getModules()}
* @return the created {@link DistributionSet}
*/
public DistributionSet generateDistributionSet(final String name, final String version,
@@ -879,9 +762,7 @@ public class TestdataFactory {
/**
* builder method for generating a {@link DistributionSet}.
*
* @param name
* {@link DistributionSet#getName()}
*
* @param name {@link DistributionSet#getName()}
* @return the generated {@link DistributionSet}
*/
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}
* as prefix for {@link Target#getControllerId()}.
*
* @param number
* of {@link Target}s to create
*
* @param number of {@link Target}s to create
* @return {@link List} of {@link Target} entities
*/
public List<Target> createTargets(final int number) {
@@ -918,13 +797,9 @@ public class TestdataFactory {
/**
* Creates {@link Target}s in repository and with {@link TargetType}.
*
* @param number
* of {@link Target}s to create
* @param controllerIdPrefix
* prefix for the controller id
* @param targetType
* targetType of targets to create
*
* @param number of {@link Target}s to create
* @param controllerIdPrefix prefix for the controller id
* @param targetType targetType of targets to create
* @return {@link List} of {@link Target} entities
*/
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.
*
* @param targetIds
* specifies the IDs of the targets
*
* @param targetIds specifies the IDs of the targets
* @return {@link List} of {@link Target} entities
*/
public List<Target> createTargets(final String... targetIds) {
@@ -957,35 +830,12 @@ public class TestdataFactory {
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
* {@link Target#getControllerId()} followed by a number suffix starting with 0.
*
* @param numberOfTargets
* of {@link Target}s to generate
* @param controllerIdPrefix
* for {@link Target#getControllerId()} generation.
* @param numberOfTargets of {@link Target}s to generate
* @param controllerIdPrefix for {@link Target#getControllerId()} generation.
* @return list of {@link Target} objects
*/
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.
*
* @param numberOfTargets
* number of targets to create
* @param prefix
* prefix used for the controller ID and description
* @param numberOfTargets number of targets to create
* @param prefix prefix used for the controller ID and description
* @return set of {@link Target}
*/
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.
*
* @param numberOfTargets
* number of targets to create
* @param controllerIdPrefix
* prefix used for the controller ID
* @param descriptionPrefix
* prefix used for the description
* @param numberOfTargets number of targets to create
* @param controllerIdPrefix prefix used for the controller ID
* @param descriptionPrefix prefix used for the description
* @return set of {@link Target}
*/
public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix,
@@ -1027,25 +872,13 @@ public class TestdataFactory {
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.
*
* @param numberOfTargets
* number of targets to create
* @param controllerIdPrefix
* prefix used for the controller ID
* @param descriptionPrefix
* prefix used for the description
* @param lastTargetQuery
* last time the target polled
* @param numberOfTargets number of targets to create
* @param controllerIdPrefix prefix used for the controller ID
* @param descriptionPrefix prefix used for the description
* @param lastTargetQuery last time the target polled
* @return set of {@link Target}
*/
public List<Target> createTargets(final int numberOfTargets, final String controllerIdPrefix,
@@ -1062,10 +895,8 @@ public class TestdataFactory {
/**
* Create a set of {@link TargetTag}s.
*
* @param number
* number of {@link TargetTag}. to be created
* @param tagPrefix
* prefix for the {@link TargetTag#getName()}
* @param number number of {@link TargetTag}. to be created
* @param tagPrefix prefix for the {@link TargetTag#getName()}
* @return the created set of {@link TargetTag}s
*/
public List<TargetTag> createTargetTags(final int number, final String tagPrefix) {
@@ -1082,9 +913,7 @@ public class TestdataFactory {
/**
* Creates {@link DistributionSetTag}s in repository.
*
* @param number
* of {@link DistributionSetTag}s
*
* @param number of {@link DistributionSetTag}s
* @return the persisted {@link DistributionSetTag}s
*/
public List<DistributionSetTag> createDistributionSetTags(final int number) {
@@ -1098,23 +927,12 @@ public class TestdataFactory {
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.
*
* @param targets
* to add {@link ActionStatus}
* @param status
* to add
* @param message
* to add
*
* @param targets to add {@link ActionStatus}
* @param status to add
* @param message to add
* @return updated {@link Action}.
*/
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.
*
* @param targets
* to add {@link ActionStatus}
* @param status
* to add
* @param msgs
* to add
*
* @param targets to add {@link ActionStatus}
* @param status to add
* @param msgs to add
* @return updated {@link Action}.
*/
public List<Action> sendUpdateActionStatusToTargets(final Collection<Target> targets, final Status status,
@@ -1159,20 +973,13 @@ public class TestdataFactory {
/**
* Creates rollout based on given parameters.
*
* @param rolloutName
* of the {@link Rollout}
* @param rolloutDescription
* of the {@link Rollout}
* @param groupSize
* of the {@link Rollout}
* @param filterQuery
* to identify the {@link Target}s
* @param distributionSet
* to assign
* @param successCondition
* to switch to next group
* @param errorCondition
* to switch to next group
* @param rolloutName of the {@link Rollout}
* @param rolloutDescription of the {@link Rollout}
* @param groupSize of the {@link Rollout}
* @param filterQuery 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}
*/
public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription,
@@ -1204,29 +1011,20 @@ public class TestdataFactory {
return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet,
successCondition, errorCondition, actionType, weight, confirmationRequired, false);
}
/**
* Creates rollout based on given parameters.
*
* @param rolloutName
* of the {@link Rollout}
* @param rolloutDescription
* of the {@link Rollout}
* @param groupSize
* of the {@link Rollout}
* @param filterQuery
* to identify the {@link Target}s
* @param distributionSet
* to assign
* @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
* @param rolloutName of the {@link Rollout}
* @param rolloutDescription of the {@link Rollout}
* @param groupSize of the {@link Rollout}
* @param filterQuery to identify the {@link Target}s
* @param distributionSet to assign
* @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)
* @param dynamic is dynamic
* @return created {@link Rollout}
@@ -1238,6 +1036,7 @@ public class TestdataFactory {
return createRolloutByVariables(rolloutName, rolloutDescription, groupSize, filterQuery, distributionSet,
successCondition, errorCondition, actionType, weight, confirmationRequired, dynamic, null);
}
public Rollout createRolloutByVariables(final String rolloutName, final String rolloutDescription,
final int groupSize, final String filterQuery, final DistributionSet distributionSet,
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
* {@link Target}s.
*
* @param prefix
* for rollouts name, description, {@link Target#getControllerId()}
* @param prefix for rollouts name, description, {@link Target#getControllerId()}
* filter
* @return created {@link Rollout}
*/
@@ -1302,32 +1100,14 @@ public class TestdataFactory {
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
*
* @param amountTargetsForRollout
* the amount of targets used for the rollout
* @param amountOtherTargets
* amount of other targets not included in the rollout
* @param amountGroups
* the size of the rollout group
* @param successCondition
* success condition
* @param errorCondition
* error condition
* @param amountTargetsForRollout the amount of targets used for the rollout
* @param amountOtherTargets amount of other targets not included in the rollout
* @param amountGroups the size of the rollout group
* @param successCondition success condition
* @param errorCondition error condition
* @return the created {@link Rollout}
*/
public Rollout createAndStartRollout(final int amountTargetsForRollout, final int amountOtherTargets,
@@ -1341,16 +1121,11 @@ public class TestdataFactory {
/**
* Create the data for a simple rollout scenario
*
* @param amountTargetsForRollout
* the amount of targets used for the rollout
* @param amountOtherTargets
* amount of other targets not included in the rollout
* @param amountOfGroups
* the size of the rollout group
* @param successCondition
* success condition
* @param errorCondition
* error condition
* @param amountTargetsForRollout the amount of targets used for the rollout
* @param amountOtherTargets amount of other targets not included in the rollout
* @param amountOfGroups the size of the rollout group
* @param successCondition success condition
* @param errorCondition error condition
* @return the created {@link Rollout}
*/
public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout,
@@ -1363,20 +1138,13 @@ public class TestdataFactory {
/**
* Create the data for a simple rollout scenario
*
* @param amountTargetsForRollout
* the amount of targets used for the rollout
* @param amountOtherTargets
* amount of other targets not included in the rollout
* @param amountOfGroups
* the size of the rollout group
* @param successCondition
* success condition
* @param errorCondition
* error condition
* @param actionType
* action Type
* @param weight
* weight
* @param amountTargetsForRollout the amount of targets used for the rollout
* @param amountOtherTargets amount of other targets not included in the rollout
* @param amountOfGroups the size of the rollout group
* @param successCondition success condition
* @param errorCondition error condition
* @param actionType action Type
* @param weight weight
* @return the created {@link Rollout}
*/
public Rollout createSimpleTestRolloutWithTargetsAndDistributionSet(final int amountTargetsForRollout,
@@ -1395,8 +1163,7 @@ public class TestdataFactory {
* Create the soft deleted {@link Rollout} with a new {@link DistributionSet}
* and {@link Target}s.
*
* @param prefix
* for rollouts name, description, {@link Target#getControllerId()}
* @param prefix for rollouts name, description, {@link Target#getControllerId()}
* filter
* @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
* are assigned on creation.
*
* @param targetTypeName
* {@link TargetType#getName()}
*
* @param targetTypeName {@link TargetType#getName()}
* @return persisted {@link TargetType}
*/
public TargetType findOrCreateTargetType(final String targetTypeName) {
@@ -1431,9 +1196,7 @@ public class TestdataFactory {
* {@link TargetType#getName()}. Compatible distribution set types are assigned
* on creation
*
* @param targetTypeName
* {@link TargetType#getName()}
*
* @param targetTypeName {@link TargetType#getName()}
* @return persisted {@link TargetType}
*/
public TargetType createTargetType(final String targetTypeName, final List<DistributionSetType> compatibleDsTypes) {
@@ -1446,9 +1209,7 @@ public class TestdataFactory {
* Creates {@link TargetType} in repository with given
* {@link TargetType#getName()}. No ds types are assigned on creation.
*
* @param targetTypePrefix
* {@link TargetType#getName()}
*
* @param targetTypePrefix {@link TargetType#getName()}
* @return persisted {@link TargetType}
*/
public List<TargetType> createTargetTypes(final String targetTypePrefix, final int count) {
@@ -1498,4 +1259,67 @@ public class TestdataFactory {
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;
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.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
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
* specific permissions.
@@ -81,6 +81,7 @@ public @interface WithUser {
boolean controller() default false;
class WithTenantAwareUserSecurityContextFactory implements WithSecurityContextFactory<WithUser> {
@Override
public SecurityContext createSecurityContext(final WithUser withTenantAwareUser) {
return new SecurityContextSwitch.WithUserSecurityContext(withTenantAwareUser);