Initial check in accordance with Parallel IP
This commit is contained in:
@@ -0,0 +1,344 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
|
||||
import org.eclipse.hawkbit.cache.TenantAwareCacheManager;
|
||||
import org.eclipse.hawkbit.repository.ActionRepository;
|
||||
import org.eclipse.hawkbit.repository.ActionStatusRepository;
|
||||
import org.eclipse.hawkbit.repository.ArtifactManagement;
|
||||
import org.eclipse.hawkbit.repository.ControllerManagement;
|
||||
import org.eclipse.hawkbit.repository.DeploymentManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetRepository;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetTagRepository;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetTypeRepository;
|
||||
import org.eclipse.hawkbit.repository.ExternalArtifactRepository;
|
||||
import org.eclipse.hawkbit.repository.LocalArtifactRepository;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleMetadataRepository;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleRepository;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleTypeRepository;
|
||||
import org.eclipse.hawkbit.repository.SystemManagement;
|
||||
import org.eclipse.hawkbit.repository.TagManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetInfoRepository;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetRepository;
|
||||
import org.eclipse.hawkbit.repository.TargetTagRepository;
|
||||
import org.eclipse.hawkbit.repository.TenantMetaDataRepository;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil;
|
||||
import org.eclipse.hawkbit.security.DosFilter;
|
||||
import org.eclipse.hawkbit.tenancy.TenantAware;
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.MethodRule;
|
||||
import org.junit.rules.TestWatchman;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.model.FrameworkMethod;
|
||||
import org.slf4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.SpringApplicationConfiguration;
|
||||
import org.springframework.context.EnvironmentAware;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.data.auditing.AuditingHandler;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.mongodb.gridfs.GridFsOperations;
|
||||
import org.springframework.test.annotation.DirtiesContext;
|
||||
import org.springframework.test.annotation.DirtiesContext.ClassMode;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@SpringApplicationConfiguration(classes = { RepositoryApplicationConfiguration.class, TestConfiguration.class })
|
||||
@ActiveProfiles({ "test" })
|
||||
@WithUser(principal = "bumlux", allSpPermissions = true, authorities = "ROLE_CONTROLLER")
|
||||
// destroy the context after each test class because otherwise we get problem
|
||||
// when context is
|
||||
// refreshed we e.g. get two instances of CacheManager which leads to very
|
||||
// strange test failures.
|
||||
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
|
||||
public abstract class AbstractIntegrationTest implements EnvironmentAware {
|
||||
protected static Logger LOG = null;
|
||||
|
||||
protected final Pageable pageReq = new PageRequest(0, 400);
|
||||
|
||||
@PersistenceContext
|
||||
protected EntityManager entityManager;
|
||||
|
||||
@Autowired
|
||||
protected TargetRepository targetRepository;
|
||||
|
||||
@Autowired
|
||||
protected ActionRepository actionRepository;
|
||||
|
||||
@Autowired
|
||||
protected DistributionSetRepository distributionSetRepository;
|
||||
|
||||
@Autowired
|
||||
protected SoftwareModuleRepository softwareModuleRepository;
|
||||
|
||||
@Autowired
|
||||
protected TenantMetaDataRepository tenantMetaDataRepository;
|
||||
|
||||
@Autowired
|
||||
protected DistributionSetTypeRepository distributionSetTypeRepository;
|
||||
|
||||
@Autowired
|
||||
protected SoftwareModuleTypeRepository softwareModuleTypeRepository;
|
||||
|
||||
@Autowired
|
||||
protected TargetTagRepository targetTagRepository;
|
||||
|
||||
@Autowired
|
||||
protected DistributionSetTagRepository distributionSetTagRepository;
|
||||
|
||||
@Autowired
|
||||
protected SoftwareModuleMetadataRepository softwareModuleMetadataRepository;
|
||||
|
||||
@Autowired
|
||||
protected ActionStatusRepository actionStatusRepository;
|
||||
|
||||
@Autowired
|
||||
protected ExternalArtifactRepository externalArtifactRepository;
|
||||
|
||||
@Autowired
|
||||
protected SoftwareManagement softwareManagement;
|
||||
|
||||
@Autowired
|
||||
protected DistributionSetManagement distributionSetManagement;
|
||||
|
||||
@Autowired
|
||||
protected ControllerManagement controllerManagement;
|
||||
|
||||
@Autowired
|
||||
protected TargetManagement targetManagement;
|
||||
|
||||
@Autowired
|
||||
protected TargetFilterQueryManagement targetFilterQueryManagement;
|
||||
|
||||
@Autowired
|
||||
protected TagManagement tagManagement;
|
||||
|
||||
@Autowired
|
||||
protected DeploymentManagement deploymentManagement;
|
||||
|
||||
@Autowired
|
||||
protected ArtifactManagement artifactManagement;
|
||||
|
||||
@Autowired
|
||||
protected LocalArtifactRepository artifactRepository;
|
||||
|
||||
@Autowired
|
||||
protected TargetInfoRepository targetInfoRepository;
|
||||
|
||||
@Autowired
|
||||
protected GridFsOperations operations;
|
||||
|
||||
@Autowired
|
||||
protected WebApplicationContext context;
|
||||
|
||||
@Autowired
|
||||
protected ControllerManagement controllerManagament;
|
||||
|
||||
@Autowired
|
||||
protected AuditingHandler auditingHandler;
|
||||
|
||||
@Autowired
|
||||
protected TenantAware tenantAware;
|
||||
|
||||
@Autowired
|
||||
protected SystemManagement systemManagement;
|
||||
|
||||
@Autowired
|
||||
protected TenantAwareCacheManager cacheManager;
|
||||
|
||||
protected MockMvc mvc;
|
||||
|
||||
@Autowired
|
||||
protected DatabaseCleanupUtil dbCleanupUtil;
|
||||
|
||||
protected SoftwareModuleType osType;
|
||||
protected SoftwareModuleType appType;
|
||||
protected SoftwareModuleType runtimeType;
|
||||
|
||||
protected DistributionSetType standardDsType;
|
||||
|
||||
@Rule
|
||||
public final WithSpringAuthorityRule securityRule = new WithSpringAuthorityRule();
|
||||
|
||||
protected Environment environment = null;
|
||||
|
||||
private static CIMySqlTestDatabase tesdatabase;
|
||||
|
||||
static {
|
||||
final Properties props = System.getProperties();
|
||||
|
||||
// if( props.getProperty( SuiteEmbeddedConfiguration.IM_HOME ) == null )
|
||||
// {
|
||||
// props.setProperty( SuiteEmbeddedConfiguration.IM_HOME,
|
||||
// "./src/test/resources/im" );
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.context.EnvironmentAware#setEnvironment(org.
|
||||
* springframework.core.env. Environment)
|
||||
*/
|
||||
@Override
|
||||
public void setEnvironment(final Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
mvc = MockMvcBuilders
|
||||
.webAppContextSetup(context)
|
||||
.addFilter(
|
||||
new DosFilter(100, 10, "127\\.0\\.0\\.1|\\[0:0:0:0:0:0:0:1\\]", "(^192\\.168\\.)",
|
||||
"X-Forwarded-For"))
|
||||
.addFilter(
|
||||
new ExcludePathAwareShallowETagFilter(
|
||||
"/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download",
|
||||
"/*/controller/artifacts/**")).build();
|
||||
|
||||
standardDsType = securityRule.runAsPrivileged(new Callable<DistributionSetType>() {
|
||||
@Override
|
||||
public DistributionSetType call() throws Exception {
|
||||
return systemManagement.getTenantMetadata().getDefaultDsType();
|
||||
}
|
||||
});
|
||||
|
||||
osType = securityRule.runAsPrivileged(new Callable<SoftwareModuleType>() {
|
||||
@Override
|
||||
public SoftwareModuleType call() throws Exception {
|
||||
return softwareManagement.findSoftwareModuleTypeByKey("os");
|
||||
}
|
||||
});
|
||||
|
||||
appType = securityRule.runAsPrivileged(new Callable<SoftwareModuleType>() {
|
||||
@Override
|
||||
public SoftwareModuleType call() throws Exception {
|
||||
return softwareManagement.findSoftwareModuleTypeByKey("application");
|
||||
}
|
||||
});
|
||||
runtimeType = securityRule.runAsPrivileged(new Callable<SoftwareModuleType>() {
|
||||
@Override
|
||||
public SoftwareModuleType call() throws Exception {
|
||||
return softwareManagement.findSoftwareModuleTypeByKey("runtime");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
public static void beforeClass() {
|
||||
createTestdatabaseAndStart();
|
||||
}
|
||||
|
||||
private static void createTestdatabaseAndStart() {
|
||||
if ("MYSQL".equals(System.getProperty("spring.jpa.database"))) {
|
||||
tesdatabase = new CIMySqlTestDatabase();
|
||||
tesdatabase.before();
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void afterClass() {
|
||||
if (tesdatabase != null) {
|
||||
tesdatabase.after();
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
deleteAllRepos();
|
||||
cacheManager.getDirectCacheNames().forEach(name -> cacheManager.getDirectCache(name).clear());
|
||||
assertThat(actionStatusRepository.findAll()).isEmpty();
|
||||
assertThat(targetRepository.findAll()).isEmpty();
|
||||
assertThat(actionRepository.findAll()).isEmpty();
|
||||
assertThat(distributionSetRepository.findAll()).isEmpty();
|
||||
assertThat(targetTagRepository.findAll()).isEmpty();
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
assertThat(softwareModuleRepository.findAll()).isEmpty();
|
||||
assertThat(softwareModuleTypeRepository.findAll()).isEmpty();
|
||||
assertThat(distributionSetTypeRepository.findAll()).isEmpty();
|
||||
assertThat(tenantMetaDataRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
protected void deleteAllRepos() throws Exception {
|
||||
final List<String> tenants = securityRule.runAs(WithSpringAuthorityRule.withUser(false),
|
||||
new Callable<List<String>>() {
|
||||
@Override
|
||||
public List<String> call() throws Exception {
|
||||
return systemManagement.findTenants();
|
||||
}
|
||||
});
|
||||
tenants.forEach(tenant -> {
|
||||
try {
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUser(false), new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
systemManagement.deleteTenant(tenant);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Rule
|
||||
public MethodRule watchman = new TestWatchman() {
|
||||
@Override
|
||||
public void starting(final FrameworkMethod method) {
|
||||
if (LOG != null) {
|
||||
LOG.info("Starting Test {}...", method.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void succeeded(final FrameworkMethod method) {
|
||||
if (LOG != null) {
|
||||
LOG.info("Test {} succeeded.", method.getName());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(final Throwable e, final FrameworkMethod method) {
|
||||
if (LOG != null) {
|
||||
LOG.error("Test {} failed with {}.", method.getName(), e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
||||
import de.flapdoodle.embed.mongo.Command;
|
||||
import de.flapdoodle.embed.mongo.MongodExecutable;
|
||||
import de.flapdoodle.embed.mongo.MongodStarter;
|
||||
import de.flapdoodle.embed.mongo.config.ArtifactStoreBuilder;
|
||||
import de.flapdoodle.embed.mongo.config.DownloadConfigBuilder;
|
||||
import de.flapdoodle.embed.mongo.config.IMongodConfig;
|
||||
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
|
||||
import de.flapdoodle.embed.mongo.config.Net;
|
||||
import de.flapdoodle.embed.mongo.config.RuntimeConfigBuilder;
|
||||
import de.flapdoodle.embed.mongo.distribution.Version;
|
||||
import de.flapdoodle.embed.process.config.store.HttpProxyFactory;
|
||||
import de.flapdoodle.embed.process.runtime.Network;
|
||||
|
||||
/**
|
||||
* Test class that contains MonfoDb start and stop for the test
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public abstract class AbstractIntegrationTestWithMongoDB extends AbstractIntegrationTest {
|
||||
protected static volatile MongodExecutable mongodExecutable = null;
|
||||
private static final AtomicInteger mongoLease = new AtomicInteger(0);
|
||||
private static volatile Integer port;
|
||||
|
||||
@BeforeClass
|
||||
public static void setupMongo() throws UnknownHostException, IOException {
|
||||
mongoLease.incrementAndGet();
|
||||
if (mongodExecutable == null) {
|
||||
final Command command = Command.MongoD;
|
||||
|
||||
final RuntimeConfigBuilder runtimeConfig = new RuntimeConfigBuilder().defaults(command);
|
||||
|
||||
if (port == null) {
|
||||
port = new FreePortFileWriter(28017, 28090, "./target/freeports").getPort();
|
||||
System.setProperty("spring.data.mongodb.port", String.valueOf(port));
|
||||
}
|
||||
|
||||
Version version = Version.V3_0_5;
|
||||
if (System.getProperty("inf.mongodb.version") != null) {
|
||||
version = Version
|
||||
.valueOf("V" + System.getProperty("inf.mongodb.version").trim().replaceAll("\\.", "_"));
|
||||
}
|
||||
|
||||
if (System.getProperty("http.proxyHost") != null) {
|
||||
runtimeConfig
|
||||
.artifactStore(
|
||||
new ArtifactStoreBuilder().defaults(command)
|
||||
.download(new DownloadConfigBuilder().defaultsForCommand(command)
|
||||
.proxyFactory(new HttpProxyFactory(
|
||||
System.getProperty("http.proxyHost").trim(),
|
||||
Integer.valueOf(System.getProperty("http.proxyPort"))))));
|
||||
}
|
||||
|
||||
final IMongodConfig mongodConfig = new MongodConfigBuilder().version(version)
|
||||
.net(new Net("127.0.0.1", port, Network.localhostIsIPv6())).build();
|
||||
|
||||
final MongodStarter starter = MongodStarter.getInstance(runtimeConfig.build());
|
||||
mongodExecutable = starter.prepare(mongodConfig);
|
||||
mongodExecutable.start();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanCurrentCollection() {
|
||||
operations.delete(new Query());
|
||||
}
|
||||
|
||||
public void internalShutDownMongo() {
|
||||
if (mongodExecutable != null && mongoLease.decrementAndGet() <= 0) {
|
||||
mongodExecutable.stop();
|
||||
mongodExecutable = null;
|
||||
}
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void shutdownMongo() throws UnknownHostException, IOException {
|
||||
if (mongodExecutable != null && mongoLease.decrementAndGet() <= 0) {
|
||||
mongodExecutable.stop();
|
||||
mongodExecutable = null;
|
||||
}
|
||||
port = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class CIMySqlTestDatabase implements Testdatabase {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(CIMySqlTestDatabase.class);
|
||||
private String schemaName;
|
||||
private String uri;
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
public CIMySqlTestDatabase() {
|
||||
this.username = System.getProperty("spring.datasource.username");
|
||||
this.password = System.getProperty("spring.datasource.password");
|
||||
this.uri = System.getProperty("spring.datasource.url");
|
||||
createSchemaUri();
|
||||
initSystemProperties();
|
||||
}
|
||||
|
||||
private final void initSystemProperties() {
|
||||
System.setProperty("spring.datasource.driverClassName", getDriverClassName());
|
||||
System.setProperty("spring.jpa.database", "MYSQL");
|
||||
}
|
||||
|
||||
private void createSchemaUri() {
|
||||
schemaName = "SP" + RandomStringUtils.randomAlphanumeric(10);
|
||||
this.uri = this.uri.substring(0, uri.lastIndexOf("/") + 1);
|
||||
|
||||
System.setProperty("spring.datasource.url", uri + schemaName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void before() {
|
||||
createSchema();
|
||||
}
|
||||
|
||||
private void createSchema() {
|
||||
try (Connection connection = DriverManager.getConnection(uri, username, password)) {
|
||||
connection.prepareStatement("CREATE SCHEMA " + schemaName + ";").execute();
|
||||
LOG.info("Schema {} created on uri {}", schemaName, uri);
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void after() {
|
||||
dropSchema();
|
||||
}
|
||||
|
||||
private void dropSchema() {
|
||||
try (Connection connection = DriverManager.getConnection(uri, username, password)) {
|
||||
connection.prepareStatement("DROP SCHEMA " + schemaName + ";").execute();
|
||||
LOG.info("Schema {} dropped on uri {}", schemaName, uri);
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDriverClassName() {
|
||||
return "org.mariadb.jdbc.Driver";
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
75
hawkbit-repository/src/test/java/org/eclipse/hawkbit/FreePortFileWriter.java
Executable file
75
hawkbit-repository/src/test/java/org/eclipse/hawkbit/FreePortFileWriter.java
Executable file
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class FreePortFileWriter {
|
||||
|
||||
private final String filePortPath;
|
||||
private final int from;
|
||||
private final int to;
|
||||
|
||||
/**
|
||||
* @param from
|
||||
* @param to
|
||||
*/
|
||||
public FreePortFileWriter(final int from, final int to, final String filePortPath) {
|
||||
this.from = from;
|
||||
this.to = to;
|
||||
this.filePortPath = filePortPath;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return findFree();
|
||||
}
|
||||
|
||||
protected int findFree() {
|
||||
for (int i = from; i <= to; i++) {
|
||||
if (isFree(i)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("No free port in range " + from + ":" + to);
|
||||
}
|
||||
|
||||
boolean isFree(final int port) {
|
||||
try {
|
||||
final File portFile = new File(filePortPath + File.separator + port + ".port");
|
||||
portFile.getParentFile().mkdirs();
|
||||
if (portFile.exists()) {
|
||||
return false;
|
||||
} else {
|
||||
boolean isFree = false;
|
||||
final ServerSocket sock = new ServerSocket();
|
||||
sock.setReuseAddress(true);
|
||||
sock.bind(new InetSocketAddress(port));
|
||||
if (portFile.createNewFile()) {
|
||||
portFile.deleteOnExit();
|
||||
isFree = true;
|
||||
}
|
||||
sock.close();
|
||||
// is free:
|
||||
return isFree;
|
||||
// We rely on an exception thrown to determine availability or
|
||||
// not availability.
|
||||
}
|
||||
} catch (final Exception e) {
|
||||
// not free.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
85
hawkbit-repository/src/test/java/org/eclipse/hawkbit/HashGeneratorUtils.java
Executable file
85
hawkbit-repository/src/test/java/org/eclipse/hawkbit/HashGeneratorUtils.java
Executable file
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Hash utility calls copied from
|
||||
* http://www.codejava.net/coding/how-to-calculate-md5-and-sha-hash-values-in-
|
||||
* java.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public final class HashGeneratorUtils {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(HashGeneratorUtils.class);
|
||||
|
||||
private HashGeneratorUtils() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a MD5 cryptographic string.
|
||||
*
|
||||
* @param message
|
||||
* the plain message
|
||||
* @return the cryptographic string
|
||||
*/
|
||||
public static String generateMD5(final byte[] message) {
|
||||
return hashString(message, "MD5");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a SHA-1 cryptographic string.
|
||||
*
|
||||
* @param message
|
||||
* the plain message
|
||||
* @return the cryptographic string
|
||||
*/
|
||||
public static String generateSHA1(final byte[] message) {
|
||||
return hashString(message, "SHA-1");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a SHA-256 cryptographic string.
|
||||
*
|
||||
* @param message
|
||||
* the plain message
|
||||
* @return the cryptographic string
|
||||
*/
|
||||
public static String generateSHA256(final byte[] message) {
|
||||
return hashString(message, "SHA-256");
|
||||
}
|
||||
|
||||
private static String hashString(final byte[] message, final String algorithm) {
|
||||
|
||||
try {
|
||||
final MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
final byte[] hashedBytes = digest.digest(message);
|
||||
return convertByteArrayToHexString(hashedBytes);
|
||||
} catch (final NoSuchAlgorithmException e) {
|
||||
LOG.error("Algorithm could not be find", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String convertByteArrayToHexString(final byte[] arrayBytes) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
for (int i = 0; i < arrayBytes.length; i++) {
|
||||
builder.append(Integer.toString((arrayBytes[i] & 0xff) + 0x100, 16).substring(1));
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
118
hawkbit-repository/src/test/java/org/eclipse/hawkbit/LocalH2TestDatabase.java
Executable file
118
hawkbit-repository/src/test/java/org/eclipse/hawkbit/LocalH2TestDatabase.java
Executable file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.h2.tools.Server;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class LocalH2TestDatabase implements Testdatabase {
|
||||
|
||||
private final static Logger LOG = LoggerFactory.getLogger(LocalH2TestDatabase.class);
|
||||
private final int port;
|
||||
private Server h2server;
|
||||
private boolean dbStarted;
|
||||
private String uri;
|
||||
|
||||
public LocalH2TestDatabase(final int port) {
|
||||
super();
|
||||
this.port = port;
|
||||
createUri();
|
||||
initSystemProperties();
|
||||
}
|
||||
|
||||
private final void initSystemProperties() {
|
||||
System.setProperty("spring.datasource.driverClassName", getDriverClassName());
|
||||
System.setProperty("spring.datasource.username", "");
|
||||
System.setProperty("spring.datasource.password", "");
|
||||
System.setProperty("hawkbit.server.database", "H2");
|
||||
}
|
||||
|
||||
private void dropAllObjects() {
|
||||
try (Connection connection = DriverManager.getConnection(uri)) {
|
||||
connection.prepareCall("DROP ALL OBJECTS;").execute();
|
||||
} catch (final SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void before() {
|
||||
try {
|
||||
startDatabase();
|
||||
} catch (ClassNotFoundException | SQLException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void after() {
|
||||
try {
|
||||
stopDatabase();
|
||||
} catch (ClassNotFoundException | SQLException | IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private void startDatabase() throws SQLException, ClassNotFoundException, IOException {
|
||||
if (dbStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Start H2 database for OpenFire
|
||||
h2server = Server
|
||||
.createTcpServer(
|
||||
new String[] { "-tcpPort", String.valueOf(port), "-tcpAllowOthers", "-tcpShutdownForce" })
|
||||
.start();
|
||||
dbStarted = true;
|
||||
LOG.info("H2 Database started on port {} and uri {}", port, uri);
|
||||
dropAllObjects();
|
||||
}
|
||||
|
||||
private final void createUri() {
|
||||
this.uri = "jdbc:h2:tcp://localhost:" + port + "/mem:SP" + UUID.randomUUID().toString() + ";MVCC=TRUE;"
|
||||
+ "DB_CLOSE_DELAY=-1";
|
||||
System.setProperty("spring.datasource.url", uri);
|
||||
}
|
||||
|
||||
private void stopDatabase() throws SQLException, ClassNotFoundException, IOException {
|
||||
if (!dbStarted) {
|
||||
return;
|
||||
}
|
||||
|
||||
h2server.stop();
|
||||
h2server = null;
|
||||
dbStarted = false;
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (final InterruptedException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDriverClassName() {
|
||||
return "org.h2.Driver";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
}
|
||||
63
hawkbit-repository/src/test/java/org/eclipse/hawkbit/MethodSecurityUtil.java
Executable file
63
hawkbit-repository/src/test/java/org/eclipse/hawkbit/MethodSecurityUtil.java
Executable file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
|
||||
public class MethodSecurityUtil {
|
||||
|
||||
private static final Set<String> METHOD_SECURITY_EXCLUSION = new HashSet<>();
|
||||
|
||||
static {
|
||||
METHOD_SECURITY_EXCLUSION.add("equals");
|
||||
METHOD_SECURITY_EXCLUSION.add("toString");
|
||||
METHOD_SECURITY_EXCLUSION.add("hashCode");
|
||||
METHOD_SECURITY_EXCLUSION.add("clone");
|
||||
METHOD_SECURITY_EXCLUSION.add("setEnvironment");
|
||||
// this method shouldn't be public on the DeploymentManagemeht but it is
|
||||
METHOD_SECURITY_EXCLUSION.add("setOverrideObsoleteUpdateActions");
|
||||
METHOD_SECURITY_EXCLUSION.add("isOverrideObsoleteUpdateActions");
|
||||
// this method must be public accessible without security because it's
|
||||
// necessary to acccess
|
||||
// the security-token of a target without being authenticated because
|
||||
// the security-token is
|
||||
// the authentication process
|
||||
// ControllerManagement#getSecurityTokenByControllerId()
|
||||
METHOD_SECURITY_EXCLUSION.add("getSecurityTokenByControllerId");
|
||||
}
|
||||
|
||||
/**
|
||||
* asserts that the given methods are annotated with the
|
||||
* {@link PreAuthorize} annotation for security. Inherited methods are not
|
||||
* checked. The following methods are excluded due inherited from
|
||||
* {@link Object}, like equals() or toString().
|
||||
*
|
||||
* @param clazz
|
||||
* the class to retrieve the public declared methods
|
||||
*/
|
||||
public static void assertDeclaredMethodsContainsPreAuthorizeAnnotaions(final Class<?> clazz) {
|
||||
final Method[] declaredMethods = clazz.getDeclaredMethods();
|
||||
for (final Method method : declaredMethods) {
|
||||
if (!METHOD_SECURITY_EXCLUSION.contains(method.getName()) && !method.isSynthetic()
|
||||
&& Modifier.isPublic(method.getModifiers())) {
|
||||
final PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
|
||||
assertThat(annotation).describedAs(
|
||||
"The public method " + method.getName() + " is not annoated with @PreAuthorize, security leak?")
|
||||
.isNotNull();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class RandomGeneratedInputStream extends InputStream {
|
||||
|
||||
private final Random random = new SecureRandom();
|
||||
|
||||
/** Target size of the stream. */
|
||||
private final long size;
|
||||
|
||||
/** Internal counter. */
|
||||
private long index;
|
||||
|
||||
/**
|
||||
* @param size
|
||||
* target size of the stream [byte]
|
||||
*/
|
||||
public RandomGeneratedInputStream(final long size) {
|
||||
super();
|
||||
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
if (index == size) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
index++;
|
||||
|
||||
return random.nextInt(255);
|
||||
}
|
||||
|
||||
}
|
||||
114
hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java
Executable file
114
hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java
Executable file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import org.eclipse.hawkbit.cache.CacheConstants;
|
||||
import org.eclipse.hawkbit.cache.TenancyCacheManager;
|
||||
import org.eclipse.hawkbit.cache.TenantAwareCacheManager;
|
||||
import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator;
|
||||
import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil;
|
||||
import org.eclipse.hawkbit.security.SecurityContextTenantAware;
|
||||
import org.eclipse.hawkbit.security.SecurityProperties;
|
||||
import org.eclipse.hawkbit.security.SpringSecurityAuditorAware;
|
||||
import org.eclipse.hawkbit.tenancy.TenantAware;
|
||||
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
|
||||
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.guava.GuavaCacheManager;
|
||||
import org.springframework.context.annotation.AdviceMode;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.data.domain.AuditorAware;
|
||||
import org.springframework.scheduling.annotation.AsyncConfigurer;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
|
||||
|
||||
import com.google.common.eventbus.AsyncEventBus;
|
||||
import com.google.common.eventbus.EventBus;
|
||||
import com.mongodb.MongoClientOptions;
|
||||
|
||||
/**
|
||||
* Spring context configuration required for Dev.Environment.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Configuration
|
||||
@EnableGlobalMethodSecurity(prePostEnabled = true, mode = AdviceMode.ASPECTJ, proxyTargetClass = true, securedEnabled = true)
|
||||
@EnableConfigurationProperties({ SecurityProperties.class, ControllerPollProperties.class })
|
||||
@Profile("test")
|
||||
public class TestConfiguration implements AsyncConfigurer {
|
||||
|
||||
/**
|
||||
* DB cleanup utility bean is created.
|
||||
*
|
||||
* @return the {@link DatabaseCleanupUtil} bean
|
||||
*/
|
||||
@Bean
|
||||
public DatabaseCleanupUtil createDatabaseCleanupUtil() {
|
||||
return new RepositoryDataGenerator.DatabaseCleanupUtil();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public MongoClientOptions options() {
|
||||
return MongoClientOptions.builder().connectTimeout(500).maxWaitTime(500).connectionsPerHost(2)
|
||||
.serverSelectionTimeout(500).build();
|
||||
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TenantAware tenantAware() {
|
||||
return new SecurityContextTenantAware();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TenancyCacheManager cacheManager() {
|
||||
return new TenantAwareCacheManager(new GuavaCacheManager(), tenantAware());
|
||||
}
|
||||
|
||||
/**
|
||||
* Bean for the downlod id cache.
|
||||
*
|
||||
* @return the cache
|
||||
*/
|
||||
@Bean(name = CacheConstants.DOWNLOAD_ID_CACHE)
|
||||
public Cache downloadIdCache() {
|
||||
return cacheManager().getDirectCache(CacheConstants.DOWNLOAD_ID_CACHE);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public EventBus eventBus() {
|
||||
return new AsyncEventBus(asyncExecutor());
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Executor asyncExecutor() {
|
||||
return new ThreadPoolTaskExecutor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuditorAware<String> auditorAware() {
|
||||
return new SpringSecurityAuditorAware();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Executor getAsyncExecutor() {
|
||||
return asyncExecutor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
|
||||
return new SimpleAsyncUncaughtExceptionHandler();
|
||||
}
|
||||
|
||||
}
|
||||
366
hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java
Executable file
366
hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java
Executable file
@@ -0,0 +1,366 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.eclipse.hawkbit.repository.ArtifactManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import net._01001111.text.LoremIpsum;
|
||||
|
||||
/**
|
||||
* Data generator utility for tests.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class TestDataUtil {
|
||||
private static final LoremIpsum LOREM = new LoremIpsum();
|
||||
|
||||
public static List<DistributionSet> generateDistributionSets(final String suffix, final int number,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<DistributionSet>();
|
||||
for (int i = 0; i < number; i++) {
|
||||
sets.add(generateDistributionSet(suffix, "v1." + i, softwareManagement, distributionSetManagement, false));
|
||||
}
|
||||
|
||||
return sets;
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSetWithNoSoftwareModules(final String name, final String version,
|
||||
final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
final DistributionSet dis = new DistributionSet();
|
||||
dis.setName(name);
|
||||
dis.setVersion(version);
|
||||
dis.setDescription("Test describtion for " + name);
|
||||
return distributionSetManagement.createDistributionSet(dis);
|
||||
}
|
||||
|
||||
public static List<DistributionSet> generateDistributionSets(final int number,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
|
||||
|
||||
return generateDistributionSets("", number, softwareManagement, distributionSetManagement);
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSet(final String suffix, final String version,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
|
||||
final boolean isRequiredMigrationStep) {
|
||||
|
||||
final SoftwareModule ah = softwareManagement.createSoftwareModule(new SoftwareModule(
|
||||
findOrCreateSoftwareModuleType(softwareManagement, "application"), suffix + "application",
|
||||
version + "." + new Random().nextInt(100), LOREM.words(20), suffix + " vendor Limited, California"));
|
||||
final SoftwareModule jvm = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(findOrCreateSoftwareModuleType(softwareManagement, "runtime"),
|
||||
suffix + "app runtime", version + "." + new Random().nextInt(100), LOREM.words(20),
|
||||
suffix + " vendor GmbH, Stuttgart, Germany"));
|
||||
final SoftwareModule os = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(findOrCreateSoftwareModuleType(softwareManagement, "os"),
|
||||
suffix + " Firmware", version + "." + new Random().nextInt(100), LOREM.words(20),
|
||||
suffix + " vendor Limited Inc, California"));
|
||||
|
||||
final List<SoftwareModuleType> mand = new ArrayList<>();
|
||||
mand.add(findOrCreateSoftwareModuleType(softwareManagement, "os"));
|
||||
|
||||
final List<SoftwareModuleType> opt = new ArrayList<>();
|
||||
opt.add(findOrCreateSoftwareModuleType(softwareManagement, "application"));
|
||||
opt.add(findOrCreateSoftwareModuleType(softwareManagement, "runtime"));
|
||||
|
||||
return distributionSetManagement.createDistributionSet(
|
||||
buildDistributionSet(suffix != null && suffix.length() > 0 ? suffix : "DS", version,
|
||||
findOrCreateDistributionSetType(distributionSetManagement, "ecl_os_app_jvm",
|
||||
"OC mandatory App/JVM optional", mand, opt),
|
||||
os, jvm, ah).setRequiredMigrationStep(isRequiredMigrationStep));
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSet(final String suffix, final String version,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
|
||||
final Collection<DistributionSetTag> tags) {
|
||||
|
||||
final DistributionSet set = generateDistributionSet(suffix, version, softwareManagement,
|
||||
distributionSetManagement, false);
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<DistributionSet>();
|
||||
sets.add(set);
|
||||
|
||||
tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(sets, tag));
|
||||
|
||||
return distributionSetManagement.findDistributionSetById(set.getId());
|
||||
|
||||
}
|
||||
|
||||
public static List<Target> generateTargets(final int number) {
|
||||
return generateTargets(0, number, "Test target ");
|
||||
}
|
||||
|
||||
public static List<Target> generateTargets(final int number, final String prefix) {
|
||||
return generateTargets(0, number, prefix);
|
||||
}
|
||||
|
||||
public static List<Target> generateTargets(final int start, final int number, final String prefix) {
|
||||
final List<Target> targets = new ArrayList<>();
|
||||
for (int i = start; i < start + number; i++) {
|
||||
targets.add(new Target(prefix + i));
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
public static List<TargetTag> generateTargetTags(final int number) {
|
||||
final List<TargetTag> result = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < number; i++) {
|
||||
result.add(new TargetTag("tag" + i, "tagdesc" + i, "" + i));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static List<DistributionSetTag> generateDistributionSetTags(final int number) {
|
||||
final List<DistributionSetTag> result = new ArrayList<DistributionSetTag>();
|
||||
|
||||
for (int i = 0; i < number; i++) {
|
||||
result.add(new DistributionSetTag("tag" + i, "tagdesc" + i, "" + i));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSet(final String suffix,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
|
||||
final boolean isRequiredMigrationStep) {
|
||||
return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement,
|
||||
isRequiredMigrationStep);
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSet(final String suffix,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) {
|
||||
return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement, false);
|
||||
}
|
||||
|
||||
public static List<org.eclipse.hawkbit.repository.model.Artifact> generateArtifacts(
|
||||
final ArtifactManagement artifactManagement, final Long moduleId) {
|
||||
final List<org.eclipse.hawkbit.repository.model.Artifact> artifacts = new ArrayList<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
final InputStream stubInputStream = IOUtils.toInputStream("some test data" + i);
|
||||
artifacts.add(artifactManagement.createLocalArtifact(stubInputStream, moduleId, "filename" + i, false));
|
||||
|
||||
}
|
||||
|
||||
return artifacts;
|
||||
}
|
||||
|
||||
public static Target createTarget(final TargetManagement targetManagement) {
|
||||
final String targetExist = "targetExist";
|
||||
final Target target = new Target(targetExist);
|
||||
targetManagement.createTarget(target);
|
||||
return target;
|
||||
}
|
||||
|
||||
public static DistributionSet generateDistributionSet(final String suffix,
|
||||
final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement,
|
||||
final Collection<DistributionSetTag> tags) {
|
||||
return generateDistributionSet(suffix, "v1.0", softwareManagement, distributionSetManagement, tags);
|
||||
}
|
||||
|
||||
public static SoftwareModuleType findOrCreateSoftwareModuleType(final SoftwareManagement softwareManagement,
|
||||
final String softwareModuleType) {
|
||||
final SoftwareModuleType findSoftwareModuleTypeByKey = softwareManagement
|
||||
.findSoftwareModuleTypeByKey(softwareModuleType);
|
||||
if (findSoftwareModuleTypeByKey != null) {
|
||||
return findSoftwareModuleTypeByKey;
|
||||
}
|
||||
return softwareManagement.createSoftwareModuleType(new SoftwareModuleType(softwareModuleType,
|
||||
softwareModuleType, "Standard type " + softwareManagement, 1));
|
||||
}
|
||||
|
||||
public static DistributionSetType findOrCreateDistributionSetType(
|
||||
final DistributionSetManagement distributionSetManagement, final String dsTypeKey, final String dsTypeName,
|
||||
final Collection<SoftwareModuleType> mandatory, final Collection<SoftwareModuleType> optional) {
|
||||
final DistributionSetType findDistributionSetTypeByname = distributionSetManagement
|
||||
.findDistributionSetTypeByKey(dsTypeKey);
|
||||
|
||||
if (findDistributionSetTypeByname != null) {
|
||||
return findDistributionSetTypeByname;
|
||||
}
|
||||
|
||||
final DistributionSetType type = new DistributionSetType(dsTypeKey, dsTypeName, "Standard type" + dsTypeName);
|
||||
mandatory.forEach(entry -> type.addMandatoryModuleType(entry));
|
||||
optional.forEach(entry -> type.addOptionalModuleType(entry));
|
||||
|
||||
return distributionSetManagement.createDistributionSetType(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a set of {@link Target} fixtures from the given parameters.
|
||||
*
|
||||
* @param noOfTgts
|
||||
* number of targets to create
|
||||
* @param ctlrIDPrefix
|
||||
* prefix used for the controller ID
|
||||
* @param descriptionPrefix
|
||||
* prefix used for the description
|
||||
* @return set of {@link Target}
|
||||
*/
|
||||
public static List<Target> buildTargetFixtures(final int noOfTgts, final String ctlrIDPrefix,
|
||||
final String descriptionPrefix) {
|
||||
return buildTargetFixtures(noOfTgts, ctlrIDPrefix, descriptionPrefix, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* method creates set of targets by by generating the controller ID and the
|
||||
* description like: prefix + no of target.
|
||||
*
|
||||
* @param noOfTgts
|
||||
* number of targets which should be created
|
||||
* @param ctlrIDPrefix
|
||||
* prefix of the controllerID which is concatenated with the
|
||||
* number of the target
|
||||
* @param descriptionPrefix
|
||||
* prefix of the target description which is concatenated with
|
||||
* the number of the target
|
||||
* @param tags
|
||||
* tags which should be added to the created {@link Target}s
|
||||
* @return set of created targets
|
||||
*/
|
||||
public static List<Target> buildTargetFixtures(final int noOfTgts, final String ctlrIDPrefix,
|
||||
final String descriptionPrefix, final TargetTag[] tags) {
|
||||
final List<Target> list = new ArrayList<Target>();
|
||||
for (int i = 0; i < noOfTgts; i++) {
|
||||
String ctrlID = ctlrIDPrefix;
|
||||
if (Strings.isNullOrEmpty(ctrlID)) {
|
||||
ctrlID = UUID.randomUUID().toString();
|
||||
}
|
||||
ctrlID = String.format("%s-%05d", ctrlID, i);
|
||||
|
||||
final String description = String.format("the description of ProvisioningTarget: [%s]", ctrlID);
|
||||
|
||||
final Target target = buildTargetFixture(ctrlID, description, tags);
|
||||
list.add(target);
|
||||
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a single {@link Target} fixture from the given parameters.
|
||||
*
|
||||
* @param ctrlID
|
||||
* controllerID
|
||||
* @param description
|
||||
* the description of the target
|
||||
* @param tags
|
||||
* assigned {@link TargetTag}s
|
||||
* @return the created {@link Target}
|
||||
*/
|
||||
public static Target buildTargetFixture(final String ctrlID, final String description, final TargetTag[] tags) {
|
||||
final Target target = new Target(ctrlID);
|
||||
target.setName("Prov.Target ".concat(ctrlID));
|
||||
target.setDescription(description);
|
||||
if (tags != null && tags.length > 0) {
|
||||
for (final TargetTag t : tags) {
|
||||
target.getTags().add(t);
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* builder method for creating a single target object.
|
||||
*
|
||||
* @param ctrlID
|
||||
* the ID of the target
|
||||
* @param description
|
||||
* of the target
|
||||
* @return the created target object
|
||||
*/
|
||||
public static Target buildTargetFixture(final String ctrlID, final String description) {
|
||||
return buildTargetFixture(ctrlID, description, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* builder method for creating a {@link DistributionSet}.
|
||||
*
|
||||
* @param name
|
||||
* of the DS
|
||||
* @param version
|
||||
* of the DS
|
||||
* @param os
|
||||
* operating system of the DS
|
||||
* @param jvm
|
||||
* java virtual machine of the DS
|
||||
* @param agentHub
|
||||
* of the DS
|
||||
* @return the created {@link DistributionSet}
|
||||
*/
|
||||
public static DistributionSet buildDistributionSet(final String name, final String version,
|
||||
final DistributionSetType type, final SoftwareModule os, final SoftwareModule jvm,
|
||||
final SoftwareModule agentHub) {
|
||||
final DistributionSet distributionSet = new DistributionSet(name, version, null, type,
|
||||
Lists.newArrayList(os, jvm, agentHub));
|
||||
distributionSet.setDescription(
|
||||
String.format("description of DistributionSet; name = '%s', version = '%s'", name, version));
|
||||
return distributionSet;
|
||||
}
|
||||
|
||||
/**
|
||||
* builder method for creating a set of {@link TargetTag}.
|
||||
*
|
||||
* @param noOfTags
|
||||
* number of {@link TargetTag}. to be created
|
||||
* @param tagPrefix
|
||||
* prefix for the {@link TargetTag.getName()}
|
||||
* @return the created set of {@link TargetTag}s
|
||||
*/
|
||||
public static List<TargetTag> buildTargetTagFixtures(final int noOfTags, final String tagPrefix) {
|
||||
final List<TargetTag> list = new ArrayList<>();
|
||||
for (int i = 0; i < noOfTags; i++) {
|
||||
String tagName = "myTag";
|
||||
if (!Strings.isNullOrEmpty(tagPrefix)) {
|
||||
tagName = tagPrefix;
|
||||
}
|
||||
tagName = String.format("%s-%05d", tagName, i);
|
||||
|
||||
final TargetTag targetTag = buildTargetTagFixture(tagName);
|
||||
list.add(targetTag);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* builder method for creating a simple {@link TargetTag}.
|
||||
*
|
||||
* @param tagName
|
||||
* name of the Tag
|
||||
* @return the {@link TargetTag}
|
||||
*/
|
||||
public static TargetTag buildTargetTagFixture(final String tagName) {
|
||||
return new TargetTag(tagName);
|
||||
}
|
||||
}
|
||||
25
hawkbit-repository/src/test/java/org/eclipse/hawkbit/Testdatabase.java
Executable file
25
hawkbit-repository/src/test/java/org/eclipse/hawkbit/Testdatabase.java
Executable file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
public interface Testdatabase {
|
||||
|
||||
void before();
|
||||
|
||||
void after();
|
||||
|
||||
public String getUri();
|
||||
|
||||
String getDriverClassName();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails;
|
||||
import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder;
|
||||
import org.junit.rules.TestRule;
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runners.model.Statement;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
|
||||
public class WithSpringAuthorityRule implements TestRule {
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
|
||||
* org.junit.runner.Description)
|
||||
*/
|
||||
@Override
|
||||
public Statement apply(final Statement base, final Description description) {
|
||||
return new Statement() {
|
||||
@Override
|
||||
public void evaluate() throws Throwable {
|
||||
final SecurityContext oldContext = before(description);
|
||||
try {
|
||||
base.evaluate();
|
||||
} finally {
|
||||
after(oldContext);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private SecurityContext before(final Description description) throws Throwable {
|
||||
final SecurityContext oldContext = SecurityContextHolder.getContext();
|
||||
WithUser annotation = description.getAnnotation(WithUser.class);
|
||||
if (annotation == null) {
|
||||
annotation = description.getTestClass().getAnnotation(WithUser.class);
|
||||
}
|
||||
if (annotation != null) {
|
||||
setSecurityContext(annotation);
|
||||
if (annotation.autoCreateTenant()) {
|
||||
SystemManagementHolder.getInstance().getSystemManagement().getTenantMetadata(annotation.tenantId());
|
||||
}
|
||||
}
|
||||
return oldContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param annotation
|
||||
*/
|
||||
private void setSecurityContext(final WithUser annotation) {
|
||||
SecurityContextHolder.setContext(new SecurityContext() {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Override
|
||||
public void setAuthentication(final Authentication authentication) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication getAuthentication() {
|
||||
final String[] authorities;
|
||||
if (annotation.allSpPermissions()) {
|
||||
authorities = getAllAuthorities(annotation.authorities(), annotation.removeFromAllPermission());
|
||||
} else {
|
||||
authorities = annotation.authorities();
|
||||
}
|
||||
final TestingAuthenticationToken testingAuthenticationToken = new TestingAuthenticationToken(
|
||||
annotation.principal(), annotation.credentials(), authorities);
|
||||
testingAuthenticationToken
|
||||
.setDetails(new TenantAwareAuthenticationDetails(annotation.tenantId(), false));
|
||||
return testingAuthenticationToken;
|
||||
}
|
||||
|
||||
private String[] getAllAuthorities(final String[] additionalAuthorities, final String[] notInclude) {
|
||||
final List<String> allPermissions = new ArrayList<>();
|
||||
final Field[] declaredFields = SpPermission.class.getDeclaredFields();
|
||||
for (final Field field : declaredFields) {
|
||||
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
boolean addPermission = true;
|
||||
final String permissionName = (String) field.get(null);
|
||||
if (notInclude != null) {
|
||||
for (final String notInlcudePerm : notInclude) {
|
||||
if (permissionName.equals(notInlcudePerm)) {
|
||||
addPermission = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (addPermission) {
|
||||
allPermissions.add(permissionName);
|
||||
}
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
// nope
|
||||
}
|
||||
}
|
||||
}
|
||||
for (final String authority : additionalAuthorities) {
|
||||
allPermissions.add(authority);
|
||||
}
|
||||
return allPermissions.toArray(new String[allPermissions.size()]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void after(final SecurityContext oldContext) {
|
||||
SecurityContextHolder.setContext(oldContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public <T> T runAsPrivileged(final Callable<T> callable) throws Exception {
|
||||
return runAs(privilegedUser(), callable);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param withUser
|
||||
* @param callable
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public <T> T runAs(final WithUser withUser, final Callable<T> callable) throws Exception {
|
||||
final SecurityContext oldContext = SecurityContextHolder.getContext();
|
||||
setSecurityContext(withUser);
|
||||
if (withUser.autoCreateTenant()) {
|
||||
SystemManagementHolder.getInstance().getSystemManagement().getTenantMetadata(withUser.tenantId());
|
||||
}
|
||||
try {
|
||||
return callable.call();
|
||||
} finally {
|
||||
after(oldContext);
|
||||
}
|
||||
}
|
||||
|
||||
public static WithUser withUser(final String principal, final String... authorities) {
|
||||
return withUserAndTenant(principal, "default", true, authorities);
|
||||
}
|
||||
|
||||
public static WithUser withUser(final boolean autoCreateTenant) {
|
||||
return withUserAndTenant("bumlux", "default", autoCreateTenant, new String[] {});
|
||||
}
|
||||
|
||||
public static WithUser withUserAndTenant(final String principal, final String tenant, final String... authorities) {
|
||||
return withUserAndTenant(principal, tenant, true, new String[] {});
|
||||
}
|
||||
|
||||
public static WithUser withUserAndTenant(final String principal, final String tenant,
|
||||
final boolean autoCreateTenant, final String... authorities) {
|
||||
return new WithUser() {
|
||||
|
||||
@Override
|
||||
public Class<? extends Annotation> annotationType() {
|
||||
return WithUser.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String principal() {
|
||||
return principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String credentials() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] authorities() {
|
||||
return authorities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allSpPermissions() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] removeFromAllPermission() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tenantId() {
|
||||
return tenant;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.hawkbit.WithUser#autoCreateTenant()
|
||||
*/
|
||||
@Override
|
||||
public boolean autoCreateTenant() {
|
||||
return autoCreateTenant;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static WithUser privilegedUser() {
|
||||
return new WithUser() {
|
||||
|
||||
@Override
|
||||
public Class<? extends Annotation> annotationType() {
|
||||
return WithUser.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String principal() {
|
||||
return "bumlux";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String credentials() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] authorities() {
|
||||
return new String[] { "ROLE_CONTROLLER" };
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean allSpPermissions() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] removeFromAllPermission() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String tenantId() {
|
||||
return "default";
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.eclipse.hawkbit.WithUser#autoCreateTenant()
|
||||
*/
|
||||
@Override
|
||||
public boolean autoCreateTenant() {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
77
hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithUser.java
Executable file
77
hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithUser.java
Executable file
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Annotation to run test classes or test methods with a specific user with
|
||||
* specific permissions.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Inherited
|
||||
public @interface WithUser {
|
||||
|
||||
/**
|
||||
* Gets the test principal.
|
||||
*
|
||||
* @return test principal
|
||||
*/
|
||||
String principal() default "TestPrincipal";
|
||||
|
||||
/**
|
||||
* Gets the test credentials.
|
||||
*
|
||||
* @return test credentials
|
||||
*/
|
||||
String credentials() default "TestCredentials";
|
||||
|
||||
/**
|
||||
* Gets the test tenant id.
|
||||
*
|
||||
* @return test tenant id
|
||||
*/
|
||||
String tenantId() default "default";
|
||||
|
||||
/**
|
||||
* Should tenant auto created.
|
||||
*
|
||||
* @return <true> = auto create <false> not create
|
||||
*/
|
||||
boolean autoCreateTenant() default true;
|
||||
|
||||
/**
|
||||
* Gets the test authorities.
|
||||
*
|
||||
* @return authorities
|
||||
*/
|
||||
String[] authorities() default {};
|
||||
|
||||
/**
|
||||
* Gets the test all permissions.
|
||||
*
|
||||
* @return permissions
|
||||
*/
|
||||
boolean allSpPermissions() default false;
|
||||
|
||||
/**
|
||||
* Gets the test removeFromAllPermission.
|
||||
*
|
||||
* @return removeFromAllPermission
|
||||
*/
|
||||
String[] removeFromAllPermission() default {};
|
||||
}
|
||||
25
hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java
vendored
Executable file
25
hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheKeysTest.java
vendored
Executable file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.cache;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CacheKeysTest {
|
||||
|
||||
@Test
|
||||
public void entitySpecificCacheKeyPattern() {
|
||||
final String knownEntityId = "123";
|
||||
final String knownCacheKey = "someField";
|
||||
final String entitySpecificCacheKey = CacheKeys.entitySpecificCacheKey(knownEntityId, knownCacheKey);
|
||||
assertThat(entitySpecificCacheKey).isEqualTo(knownEntityId + "." + knownCacheKey);
|
||||
}
|
||||
|
||||
}
|
||||
69
hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java
vendored
Executable file
69
hawkbit-repository/src/test/java/org/eclipse/hawkbit/cache/CacheWriteNotifyTest.java
vendored
Executable file
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.cache;
|
||||
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.tenancy.TenantAware;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
|
||||
import com.google.common.eventbus.EventBus;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CacheWriteNotifyTest {
|
||||
|
||||
@Mock
|
||||
private EventBus eventBusMock;
|
||||
|
||||
@Mock
|
||||
private CacheManager cacheManagerMock;
|
||||
|
||||
@Mock
|
||||
private Cache cacheMock;
|
||||
|
||||
@Mock
|
||||
private TenantAware tenantAwareMock;
|
||||
|
||||
private CacheWriteNotify underTest;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
underTest = new CacheWriteNotify();
|
||||
underTest.setEventBus(eventBusMock);
|
||||
underTest.setCacheManager(cacheManagerMock);
|
||||
underTest.setTenantAware(tenantAwareMock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void downloadgProgressIsCachedAndEventSent() {
|
||||
final long knownStatusId = 1;
|
||||
final int knownPercentage = 23;
|
||||
|
||||
when(cacheManagerMock.getCache(Action.class.getName())).thenReturn(cacheMock);
|
||||
when(tenantAwareMock.getCurrentTenant()).thenReturn("default");
|
||||
|
||||
underTest.downloadProgressPercent(knownStatusId, knownPercentage);
|
||||
|
||||
verify(cacheManagerMock).getCache(eq(Action.class.getName()));
|
||||
verify(cacheMock).put(knownStatusId + "." + CacheKeys.DOWNLOAD_PROGRESS_PERCENT, knownPercentage);
|
||||
verify(eventBusMock).post(any(DownloadProgressEvent.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.eventbus;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.eclipse.hawkbit.cache.CacheField;
|
||||
import org.eclipse.hawkbit.cache.CacheKeys;
|
||||
import org.eclipse.hawkbit.repository.model.helper.CacheManagerHolder;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.support.SimpleValueWrapper;
|
||||
import org.springframework.hateoas.Identifiable;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CacheFieldEntityListenerTest {
|
||||
|
||||
private static final String TEST_CACHE_FIELD = "testCacheField";
|
||||
|
||||
@Mock
|
||||
private CacheManager cacheManagerMock;
|
||||
|
||||
@Mock
|
||||
private Cache cacheMock;
|
||||
|
||||
private CacheFieldEntityListener underTest;
|
||||
|
||||
@Before
|
||||
public void before() {
|
||||
// mock
|
||||
when(cacheManagerMock.getCache(anyString())).thenReturn(cacheMock);
|
||||
|
||||
underTest = new CacheFieldEntityListener();
|
||||
CacheManagerHolder.getInstance().setCacheManager(cacheManagerMock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postLoadSetsCacheFields() {
|
||||
final String entityId = "123";
|
||||
final String normalFieldValue = "bumlux";
|
||||
final TestEntity testObject = new TestEntity(entityId, normalFieldValue);
|
||||
final int expectedTestValue = -1;
|
||||
|
||||
when(cacheMock.get(CacheKeys.entitySpecificCacheKey(entityId, TEST_CACHE_FIELD)))
|
||||
.thenReturn(new SimpleValueWrapper(expectedTestValue));
|
||||
|
||||
// pre verify everything is ok
|
||||
assertThat(testObject.getCacheField()).isNotEqualTo(expectedTestValue);
|
||||
assertThat(testObject.getNormalField()).isEqualTo(normalFieldValue);
|
||||
|
||||
// test
|
||||
underTest.postLoad(testObject);
|
||||
|
||||
assertThat(testObject.getNormalField()).isEqualTo(normalFieldValue);
|
||||
// now cache value should be like the value in the mock of the cache
|
||||
assertThat(testObject.getCacheField()).isEqualTo(expectedTestValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void postRemoveEvictsCacheField() {
|
||||
final String entityId = "123";
|
||||
final String normalFieldValue = "bumlux";
|
||||
final TestEntity testObject = new TestEntity(entityId, normalFieldValue);
|
||||
// test
|
||||
underTest.postDelete(testObject);
|
||||
|
||||
verify(cacheMock).evict(eq(CacheKeys.entitySpecificCacheKey(entityId, TEST_CACHE_FIELD)));
|
||||
}
|
||||
|
||||
private final class TestEntity implements Identifiable<String> {
|
||||
|
||||
private final String id;
|
||||
|
||||
private final String normalField;
|
||||
|
||||
@CacheField(key = TEST_CACHE_FIELD)
|
||||
private int cacheField;
|
||||
|
||||
private TestEntity(final String id, final String normalFieldValue) {
|
||||
this.id = id;
|
||||
this.normalField = normalFieldValue;
|
||||
}
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.hateoas.Identifiable#getId()
|
||||
*/
|
||||
@Override
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the normalField
|
||||
*/
|
||||
String getNormalField() {
|
||||
return normalField;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the cacheField
|
||||
*/
|
||||
int getCacheField() {
|
||||
return cacheField;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.ActionType;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ActionTest {
|
||||
|
||||
// issue MECS-670 timeforced update and eTAG calculation
|
||||
@Test
|
||||
public void timeforcedHitNewHasCodeIsGenerated() throws InterruptedException {
|
||||
|
||||
final boolean active = true;
|
||||
// current time + 1 seconds
|
||||
final long sleepTime = 1000;
|
||||
final long timeForceTimeAt = System.currentTimeMillis() + sleepTime;
|
||||
final Action timeforcedAction = new Action();
|
||||
timeforcedAction.setActionType(ActionType.TIMEFORCED);
|
||||
timeforcedAction.setForcedTime(timeForceTimeAt);
|
||||
final int knownHashCode = timeforcedAction.hashCode();
|
||||
assertThat(timeforcedAction.isForce()).isFalse();
|
||||
|
||||
// wait until timeforce time is hit
|
||||
Thread.sleep(sleepTime + 100);
|
||||
assertThat(timeforcedAction.isForce()).isTrue();
|
||||
assertThat(timeforcedAction.hashCode()).isNotEqualTo(knownHashCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.repository.exception.ArtifactUploadFailedException;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Addition tests next to {@link ArtifactManagementTest} with no running MongoDB
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Artifact Management")
|
||||
public class ArtifactManagementNoMongoDbTest extends AbstractIntegrationTest {
|
||||
|
||||
@BeforeClass
|
||||
public static void initialize() {
|
||||
// set property to mongoPort which does not start any mongoDB of
|
||||
// parallel test execution
|
||||
System.setProperty("spring.data.mongodb.port", "1020");
|
||||
}
|
||||
|
||||
@Test(expected = ArtifactUploadFailedException.class)
|
||||
@Description("Checks if the expected ArtifactUploadFailedException is thrown in case of MongoDB down")
|
||||
public void createLocalArtifactWithMongoDbDown() throws IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.HashGeneratorUtils;
|
||||
import org.eclipse.hawkbit.RandomGeneratedInputStream;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.repository.exception.ArtifactDeleteFailedException;
|
||||
import org.eclipse.hawkbit.repository.exception.InsufficientPermissionException;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.ExternalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider;
|
||||
import org.eclipse.hawkbit.repository.model.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test class for {@link ArtifactManagement} with running MongoDB instance..
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Artifact Management")
|
||||
public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB {
|
||||
public ArtifactManagementTest() {
|
||||
LOG = LoggerFactory.getLogger(ArtifactManagementTest.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#createLocalArtifact(java.io.InputStream)}
|
||||
* .
|
||||
*
|
||||
* @throws IOException
|
||||
* @throws NoSuchAlgorithmException
|
||||
*/
|
||||
@Test
|
||||
@Description("Test if a local artifact can be created by API including metadata.")
|
||||
public void createLocalArtifact() throws NoSuchAlgorithmException, IOException {
|
||||
// checkbaseline
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2",
|
||||
"version 2", null, null);
|
||||
sm2 = softwareModuleRepository.save(sm2);
|
||||
|
||||
SoftwareModule sm3 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 3",
|
||||
"version 3", null, null);
|
||||
sm3 = softwareModuleRepository.save(sm3);
|
||||
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(),
|
||||
"file1", false);
|
||||
final Artifact result11 = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(),
|
||||
"file11", false);
|
||||
final Artifact result12 = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(),
|
||||
"file12", false);
|
||||
final Artifact result2 = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm2.getId(),
|
||||
"file2", false);
|
||||
|
||||
assertThat(result).isInstanceOf(LocalArtifact.class);
|
||||
assertThat(result.getSoftwareModule().getId()).isEqualTo(sm.getId());
|
||||
assertThat(result2.getSoftwareModule().getId()).isEqualTo(sm2.getId());
|
||||
assertThat(((LocalArtifact) result).getFilename()).isEqualTo("file1");
|
||||
assertThat(((LocalArtifact) result).getGridFsFileName()).isNotNull();
|
||||
assertThat(result).isNotEqualTo(result2);
|
||||
assertThat(((LocalArtifact) result).getGridFsFileName())
|
||||
.isEqualTo(((LocalArtifact) result2).getGridFsFileName());
|
||||
|
||||
assertThat(artifactManagement.findLocalArtifactByFilename("file1").get(0).getSha1Hash())
|
||||
.isEqualTo(HashGeneratorUtils.generateSHA1(random));
|
||||
assertThat(artifactManagement.findLocalArtifactByFilename("file1").get(0).getMd5Hash())
|
||||
.isEqualTo(HashGeneratorUtils.generateMD5(random));
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(4);
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(3);
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts()).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests hard delete directly on repository.")
|
||||
public void hardDeleteSoftwareModule() throws NoSuchAlgorithmException, IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false);
|
||||
assertThat(artifactRepository.findAll()).hasSize(1);
|
||||
|
||||
softwareModuleRepository.deleteAll();
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#createExternalArtifact(org.eclipse.hawkbit.repository.model.ExternalArtifactProvider, java.lang.String)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
@Description("Tests the creation of an external artifact metadata element.")
|
||||
public void createExternalArtifact() {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2",
|
||||
"version 2", null, null);
|
||||
sm2 = softwareModuleRepository.save(sm2);
|
||||
|
||||
final ExternalArtifactProvider provider = artifactManagement.createExternalArtifactProvider("provider X", null,
|
||||
"https://fhghdfjgh", "/{version}/");
|
||||
|
||||
ExternalArtifact result = artifactManagement.createExternalArtifact(provider, null, sm.getId());
|
||||
|
||||
assertNotNull(result);
|
||||
assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(1);
|
||||
assertThat(result.getSoftwareModule().getId()).isEqualTo(sm.getId());
|
||||
assertThat(result.getUrl()).isEqualTo("https://fhghdfjgh/{version}/");
|
||||
assertThat(result.getExternalArtifactProvider()).isEqualTo(provider);
|
||||
|
||||
result = artifactManagement.createExternalArtifact(provider, "/test", sm2.getId());
|
||||
assertNotNull(result);
|
||||
assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(2);
|
||||
assertThat(result.getUrl()).isEqualTo("https://fhghdfjgh/test");
|
||||
assertThat(result.getExternalArtifactProvider()).isEqualTo(provider);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests deletio of an external artifact metadata element.")
|
||||
public void deleteExternalArtifact() {
|
||||
assertThat(artifactRepository.findAll()).isEmpty();
|
||||
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
final ExternalArtifactProvider provider = artifactManagement.createExternalArtifactProvider("provider X", null,
|
||||
"https://fhghdfjgh", "/{version}/");
|
||||
|
||||
final ExternalArtifact result = artifactManagement.createExternalArtifact(provider, null, sm.getId());
|
||||
assertNotNull(result);
|
||||
assertThat(externalArtifactRepository.findAll()).contains(result).hasSize(1);
|
||||
|
||||
artifactManagement.deleteExternalArtifact(result.getId());
|
||||
assertThat(externalArtifactRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#deleteLocalArtifact(java.lang.Long)}
|
||||
* .
|
||||
*
|
||||
* @throws IOException
|
||||
* @throws NoSuchAlgorithmException
|
||||
*/
|
||||
@Test
|
||||
@Description("Tests the deletion of a local artifact including metadata.")
|
||||
public void deleteLocalArtifact() throws NoSuchAlgorithmException, IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2",
|
||||
"version 2", null, null);
|
||||
sm2 = softwareModuleRepository.save(sm2);
|
||||
|
||||
assertThat(artifactRepository.findAll()).isEmpty();
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024),
|
||||
sm.getId(), "file1", false);
|
||||
final Artifact result2 = artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024),
|
||||
sm2.getId(), "file2", false);
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(2);
|
||||
|
||||
assertThat(result.getId()).isNotNull();
|
||||
assertThat(result2.getId()).isNotNull();
|
||||
assertThat(((LocalArtifact) result).getGridFsFileName())
|
||||
.isNotEqualTo(((LocalArtifact) result2).getGridFsFileName());
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
|
||||
artifactManagement.deleteLocalArtifact(result.getId());
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNull();
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
|
||||
artifactManagement.deleteLocalArtifact(result2.getId());
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result2).getGridFsFileName()))))
|
||||
.isNull();
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Trys and fails to delete local artifact with a down mongodb and checks if expected ArtifactDeleteFailedException is thrown.")
|
||||
public void deleteArtifactsWithNoMongoDb() throws UnknownHostException, IOException {
|
||||
// ensure baseline
|
||||
assertThat(artifactRepository.findAll()).isEmpty();
|
||||
|
||||
// prepare test
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024),
|
||||
sm.getId(), "file1", false);
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(1);
|
||||
|
||||
internalShutDownMongo();
|
||||
try {
|
||||
artifactManagement.deleteLocalArtifact(result.getId());
|
||||
fail("deletion should have failed");
|
||||
} catch (final ArtifactDeleteFailedException e) {
|
||||
|
||||
}
|
||||
setupMongo();
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(1);
|
||||
assertThat(artifactManagement.findArtifact(result.getId())).isEqualTo(result);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test the deletion of an artifact metadata where the binary is still linked to another "
|
||||
+ "metadata element. The expected result is that the metadata is deleted but the binary kept.")
|
||||
public void deleteDuplicateArtifacts() throws NoSuchAlgorithmException, IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareModuleRepository.save(sm);
|
||||
|
||||
SoftwareModule sm2 = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 2",
|
||||
"version 2", null, null);
|
||||
sm2 = softwareModuleRepository.save(sm2);
|
||||
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(),
|
||||
"file1", false);
|
||||
final Artifact result2 = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm2.getId(),
|
||||
"file2", false);
|
||||
|
||||
assertThat(artifactRepository.findAll()).hasSize(2);
|
||||
assertThat(result.getId()).isNotNull();
|
||||
assertThat(result2.getId()).isNotNull();
|
||||
assertThat(((LocalArtifact) result).getGridFsFileName())
|
||||
.isEqualTo(((LocalArtifact) result2).getGridFsFileName());
|
||||
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
artifactManagement.deleteLocalArtifact(result.getId());
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
|
||||
artifactManagement.deleteLocalArtifact(result2.getId());
|
||||
assertThat(operations.findOne(
|
||||
new Query().addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#findArtifact(java.lang.Long)}
|
||||
* .
|
||||
*
|
||||
* @throws IOException
|
||||
* @throws NoSuchAlgorithmException
|
||||
*/
|
||||
@Test
|
||||
@Description("Loads an artifact based on given ID.")
|
||||
public void findArtifact() throws NoSuchAlgorithmException, IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024),
|
||||
sm.getId(), "file1", false);
|
||||
|
||||
assertThat(artifactManagement.findArtifact(result.getId())).isEqualTo(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.ArtifactManagement#loadLocalArtifactBinary(java.lang.Long)}
|
||||
* .
|
||||
*
|
||||
* @throws IOException
|
||||
* @throws NoSuchAlgorithmException
|
||||
*/
|
||||
@Test
|
||||
@Description("Loads an artifact binary based on given ID.")
|
||||
public void loadStreamOfLocalArtifact() throws NoSuchAlgorithmException, IOException {
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
|
||||
final LocalArtifact result = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
sm.getId(), "file1", false);
|
||||
|
||||
assertTrue(IOUtils.contentEquals(new ByteArrayInputStream(random),
|
||||
artifactManagement.loadLocalArtifactBinary(result).getFileInputStream()));
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientPermissionException.class)
|
||||
@WithUser(allSpPermissions = true, removeFromAllPermission = { SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT })
|
||||
@Description("Trys and fails to load an artifact without required permission. Checks if expected InsufficientPermissionException is thrown.")
|
||||
public void loadLocalArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() {
|
||||
artifactManagement.loadLocalArtifactBinary(new LocalArtifact());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Searches an artifact through the relations of a software module.")
|
||||
public void findLocalArtifactBySoftwareModule() {
|
||||
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
|
||||
SoftwareModule sm2 = new SoftwareModule(osType, "name 2", "version 2", null, null);
|
||||
sm2 = softwareManagement.createSoftwareModule(sm2);
|
||||
|
||||
assertThat(artifactManagement.findLocalArtifactBySoftwareModule(pageReq, sm.getId())).isEmpty();
|
||||
|
||||
final Artifact result = artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024),
|
||||
sm.getId(), "file1", false);
|
||||
|
||||
assertThat(artifactManagement.findLocalArtifactBySoftwareModule(pageReq, sm.getId())).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Searches an artifact through the relations of a software module and the filename.")
|
||||
public void findByFilenameAndSoftwareModule() {
|
||||
SoftwareModule sm = new SoftwareModule(osType, "name 1", "version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
|
||||
assertThat(artifactManagement.findByFilenameAndSoftwareModule("file1", sm.getId())).isEmpty();
|
||||
|
||||
artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024), sm.getId(), "file1", false);
|
||||
artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024), sm.getId(), "file2", false);
|
||||
|
||||
assertThat(artifactManagement.findByFilenameAndSoftwareModule("file1", sm.getId())).hasSize(1);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.junit.Test;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Controller Management")
|
||||
public class ControllerManagementTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Controller adds a new action status.")
|
||||
public void controllerAddsActionStatus() {
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
|
||||
assertThat(savedTarget.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
|
||||
|
||||
savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedTargets().iterator().next();
|
||||
final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
|
||||
assertThat(targetManagement.findTargetByControllerID(savedTarget.getControllerId()).getTargetInfo()
|
||||
.getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
|
||||
ActionStatus actionStatusMessage = new ActionStatus(savedAction, Action.Status.RUNNING,
|
||||
System.currentTimeMillis());
|
||||
actionStatusMessage.addMessage("foobar");
|
||||
savedAction.setStatus(Status.RUNNING);
|
||||
controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.PENDING);
|
||||
|
||||
actionStatusMessage = new ActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis());
|
||||
actionStatusMessage.addMessage(RandomStringUtils.randomAscii(512));
|
||||
savedAction.setStatus(Status.FINISHED);
|
||||
controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.IN_SYNC);
|
||||
|
||||
assertThat(actionStatusRepository.findAll(pageReq).getNumberOfElements()).isEqualTo(3);
|
||||
assertThat(deploymentManagement.findActionStatusMessagesByActionInDescOrder(pageReq, savedAction, false)
|
||||
.getNumberOfElements()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Controller trys to finish an update process after it has been finished by an error action status.")
|
||||
public void tryToFinishUpdateProcessMoreThenOnce() {
|
||||
|
||||
// mock
|
||||
final Target target = new Target("Rabbit");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
Target savedTarget = targetManagement.createTarget(target);
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedTargets().iterator().next();
|
||||
Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
|
||||
// test and verify
|
||||
final ActionStatus actionStatusMessage = new ActionStatus(savedAction, Action.Status.RUNNING,
|
||||
System.currentTimeMillis());
|
||||
actionStatusMessage.addMessage("running");
|
||||
savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage, savedAction);
|
||||
assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.PENDING);
|
||||
|
||||
final ActionStatus actionStatusMessage2 = new ActionStatus(savedAction, Action.Status.ERROR,
|
||||
System.currentTimeMillis());
|
||||
actionStatusMessage2.addMessage("error");
|
||||
savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage2, savedAction);
|
||||
assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.ERROR);
|
||||
|
||||
final ActionStatus actionStatusMessage3 = new ActionStatus(savedAction, Action.Status.FINISHED,
|
||||
System.currentTimeMillis());
|
||||
actionStatusMessage3.addMessage("finish");
|
||||
savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage3, savedAction);
|
||||
|
||||
targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus();
|
||||
|
||||
// test
|
||||
assertThat(targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.ERROR);
|
||||
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,583 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
import static org.fest.assertions.api.Assertions.fail;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithSpringAuthorityRule;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.report.model.DataReportSeries;
|
||||
import org.eclipse.hawkbit.report.model.DataReportSeriesItem;
|
||||
import org.eclipse.hawkbit.report.model.InnerOuterDataReportSeries;
|
||||
import org.eclipse.hawkbit.report.model.SeriesTime;
|
||||
import org.eclipse.hawkbit.repository.ReportManagement.DateTypes;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetInfo;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.auditing.AuditingHandler;
|
||||
import org.springframework.data.auditing.CurrentDateTimeProvider;
|
||||
import org.springframework.data.auditing.DateTimeProvider;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Slice;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Report Management")
|
||||
public class ReportManagementTest extends AbstractIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private ReportManagement reportManagement;
|
||||
|
||||
@Autowired
|
||||
private AuditingHandler auditingHandler;
|
||||
|
||||
@After
|
||||
public void afterTest() {
|
||||
auditingHandler.setDateTimeProvider(CurrentDateTimeProvider.INSTANCE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void targetsCreatedOverPeriod() {
|
||||
|
||||
// the maximum months going back from now
|
||||
// create more targets than asking the report so we can check if the
|
||||
// report is returning the
|
||||
// correct timeframe
|
||||
final int maxMonthBackAmountCreateTargets = 10;
|
||||
final int maxMonthBackAmountReportTargets = 4;
|
||||
|
||||
final DynamicDateTimeProvider dynamicDateTimeProvider = new DynamicDateTimeProvider();
|
||||
auditingHandler.setDateTimeProvider(dynamicDateTimeProvider);
|
||||
|
||||
for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) {
|
||||
dynamicDateTimeProvider.nowMinusMonths(month);
|
||||
targetManagement.createTarget(new Target("t" + month));
|
||||
}
|
||||
|
||||
final LocalDateTime to = LocalDateTime.now();
|
||||
final LocalDateTime from = to.minusMonths(maxMonthBackAmountReportTargets);
|
||||
|
||||
DataReportSeries<LocalDate> targetsCreatedOverPeriod = reportManagement
|
||||
.targetsCreatedOverPeriod(DateTypes.perMonth(), from, to);
|
||||
|
||||
// +1 because we go back #maxMonthBackAmountReportTargets but in the
|
||||
// report the current month
|
||||
// is included for sure, so from this month we go back
|
||||
assertThat(targetsCreatedOverPeriod.getData()).hasSize(maxMonthBackAmountReportTargets + 1);
|
||||
for (final DataReportSeriesItem<LocalDate> reportItem : targetsCreatedOverPeriod.getData()) {
|
||||
// only one target is created for each month
|
||||
assertThat(reportItem.getData().intValue()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// check cache evict
|
||||
for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) {
|
||||
dynamicDateTimeProvider.nowMinusMonths(month);
|
||||
targetManagement.createTarget(new Target("t2" + month));
|
||||
}
|
||||
targetsCreatedOverPeriod = reportManagement.targetsCreatedOverPeriod(DateTypes.perMonth(), from, to);
|
||||
for (final DataReportSeriesItem<LocalDate> reportItem : targetsCreatedOverPeriod.getData()) {
|
||||
assertThat(reportItem.getData().intValue()).isEqualTo(2);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void targetsFeedbackOverPeriod() {
|
||||
|
||||
// the maximum months going back from now
|
||||
// create more targets than asking the report so we can check if the
|
||||
// report is returning the
|
||||
// correct timeframe
|
||||
final int maxMonthBackAmountCreateTargets = 10;
|
||||
final int maxMonthBackAmountReportTargets = 4;
|
||||
|
||||
final LocalDateTime to = LocalDateTime.now();
|
||||
final LocalDateTime from = to.minusMonths(maxMonthBackAmountReportTargets);
|
||||
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("ds", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final DynamicDateTimeProvider dynamicDateTimeProvider = new DynamicDateTimeProvider();
|
||||
auditingHandler.setDateTimeProvider(dynamicDateTimeProvider);
|
||||
|
||||
for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) {
|
||||
dynamicDateTimeProvider.nowMinusMonths(month);
|
||||
final Target createTarget = targetManagement.createTarget(new Target("t" + month));
|
||||
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet,
|
||||
Lists.newArrayList(createTarget));
|
||||
controllerManagament.registerRetrieved(result.getActions().get(0),
|
||||
"Controller retrieved update action and should start now the download.");
|
||||
}
|
||||
DataReportSeries<LocalDate> feedbackReceivedOverTime = reportManagement
|
||||
.feedbackReceivedOverTime(DateTypes.perMonth(), from, to);
|
||||
// +1 because we go back #maxMonthBackAmountReportTargets but in the
|
||||
// report the current month
|
||||
// is included for sure, so from this month we go back
|
||||
assertThat(feedbackReceivedOverTime.getData()).hasSize(maxMonthBackAmountReportTargets + 1);
|
||||
for (final DataReportSeriesItem<LocalDate> reportItem : feedbackReceivedOverTime.getData()) {
|
||||
// only one target feedback is created for each month
|
||||
assertThat(reportItem.getData().intValue()).isEqualTo(1);
|
||||
}
|
||||
|
||||
// check cache evict
|
||||
for (int month = 0; month < maxMonthBackAmountCreateTargets; month++) {
|
||||
dynamicDateTimeProvider.nowMinusMonths(month);
|
||||
final Target createTarget = targetManagement.createTarget(new Target("t2" + month));
|
||||
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(distributionSet,
|
||||
Lists.newArrayList(createTarget));
|
||||
controllerManagament.registerRetrieved(result.getActions().get(0),
|
||||
"Controller retrieved update action and should start now the download.");
|
||||
}
|
||||
feedbackReceivedOverTime = reportManagement.feedbackReceivedOverTime(DateTypes.perMonth(), from, to);
|
||||
for (final DataReportSeriesItem<LocalDate> reportItem : feedbackReceivedOverTime.getData()) {
|
||||
assertThat(reportItem.getData().intValue()).isEqualTo(2);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void distributionUsageInstalled() {
|
||||
final Target knownTarget1 = targetManagement.createTarget(new Target("t1"));
|
||||
final Target knownTarget2 = targetManagement.createTarget(new Target("t2"));
|
||||
final Target knownTarget3 = targetManagement.createTarget(new Target("t3"));
|
||||
final Target knownTarget4 = targetManagement.createTarget(new Target("t4"));
|
||||
final Target knownTarget5 = targetManagement.createTarget(new Target("t5"));
|
||||
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
final SoftwareModule jvm = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
|
||||
final SoftwareModule os = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
|
||||
|
||||
final DistributionSet distributionSet1 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.0", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet11 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.1", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet2 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds2", "0.0.2", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet3 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds3", "0.0.3", standardDsType, os, jvm, ah));
|
||||
|
||||
// ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3]
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId());
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId());
|
||||
deploymentManagement.assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId());
|
||||
|
||||
// ds2=[target4]
|
||||
deploymentManagement.assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId());
|
||||
|
||||
// ds3=[target5] --> ONLY ASSIGNED AND NOT INSTALLED
|
||||
deploymentManagement.assignDistributionSet(distributionSet3.getId(), knownTarget5.getControllerId());
|
||||
|
||||
// set installed status
|
||||
sendUpdateActionStatusToTargets(distributionSet1, Lists.newArrayList(knownTarget1, knownTarget2),
|
||||
Status.FINISHED, "some message");
|
||||
sendUpdateActionStatusToTargets(distributionSet11, Lists.newArrayList(knownTarget3), Status.FINISHED,
|
||||
"some message");
|
||||
sendUpdateActionStatusToTargets(distributionSet2, Lists.newArrayList(knownTarget4), Status.FINISHED,
|
||||
"some message");
|
||||
|
||||
List<InnerOuterDataReportSeries<String>> distributionUsage = reportManagement.distributionUsageInstalled(100);
|
||||
|
||||
for (final InnerOuterDataReportSeries<String> innerOuterDataReportSeries : distributionUsage) {
|
||||
|
||||
// innerseries only have one data of the name and the total count
|
||||
final DataReportSeriesItem<String> dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries()
|
||||
.getData()[0];
|
||||
if (dataReportSeriesItem.getType().equals("ds1")) {
|
||||
// total count of three because ds1 has two different versions
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(3L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(Arrays.stream(outerData).map(DataReportSeriesItem::getType).collect(Collectors.toList()))
|
||||
.contains("0.0.0", "0.0.1");
|
||||
} else if (dataReportSeriesItem.getType().equals("ds2")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(1L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(outerData).hasSize(1);
|
||||
assertThat(outerData[0].getType()).isEqualTo("0.0.2");
|
||||
|
||||
} else if (dataReportSeriesItem.getType().equals("ds3")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(0L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(outerData).hasSize(1);
|
||||
assertThat(outerData[0].getType()).isEqualTo("0.0.3");
|
||||
} else {
|
||||
fail("no assertion count for distribution set " + dataReportSeriesItem.getType());
|
||||
}
|
||||
}
|
||||
|
||||
// Test cache evict
|
||||
final Target knownTarget6 = targetManagement.createTarget(new Target("t6"));
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget6.getControllerId());
|
||||
sendUpdateActionStatusToTargets(distributionSet1, Lists.newArrayList(knownTarget6), Status.FINISHED,
|
||||
"some message");
|
||||
distributionUsage = reportManagement.distributionUsageInstalled(100);
|
||||
for (final InnerOuterDataReportSeries<String> innerOuterDataReportSeries : distributionUsage) {
|
||||
final DataReportSeriesItem<String> dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries()
|
||||
.getData()[0];
|
||||
if (dataReportSeriesItem.getType().equals("ds1")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(4L);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void targetStatusReport() {
|
||||
|
||||
final long knownErrorCount = 5;
|
||||
final long knownSyncCount = 4;
|
||||
final long knownPendingCount = 3;
|
||||
final long knownRegCount = 2;
|
||||
final long knownUnknownCount = 1;
|
||||
|
||||
createTargetsWithStatus("error", knownErrorCount, TargetUpdateStatus.ERROR);
|
||||
createTargetsWithStatus("snyc", knownSyncCount, TargetUpdateStatus.IN_SYNC);
|
||||
createTargetsWithStatus("pending", knownPendingCount, TargetUpdateStatus.PENDING);
|
||||
createTargetsWithStatus("reg", knownRegCount, TargetUpdateStatus.REGISTERED);
|
||||
createTargetsWithStatus("unknown", knownUnknownCount, TargetUpdateStatus.UNKNOWN);
|
||||
|
||||
DataReportSeries<TargetUpdateStatus> targetStatus = reportManagement.targetStatus();
|
||||
for (final DataReportSeriesItem<TargetUpdateStatus> reportItem : targetStatus.getData()) {
|
||||
|
||||
switch (reportItem.getType()) {
|
||||
case ERROR:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownErrorCount);
|
||||
break;
|
||||
case IN_SYNC:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownSyncCount);
|
||||
break;
|
||||
case PENDING:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownPendingCount);
|
||||
break;
|
||||
case REGISTERED:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownRegCount);
|
||||
break;
|
||||
case UNKNOWN:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownUnknownCount);
|
||||
break;
|
||||
default:
|
||||
fail("missing case for unknown target update status " + reportItem.getType());
|
||||
}
|
||||
}
|
||||
|
||||
// test cache evict
|
||||
createTargetsWithStatus("error2", knownErrorCount, TargetUpdateStatus.ERROR);
|
||||
createTargetsWithStatus("snyc2", knownSyncCount, TargetUpdateStatus.IN_SYNC);
|
||||
createTargetsWithStatus("pending2", knownPendingCount, TargetUpdateStatus.PENDING);
|
||||
createTargetsWithStatus("reg2", knownRegCount, TargetUpdateStatus.REGISTERED);
|
||||
createTargetsWithStatus("unknown2", knownUnknownCount, TargetUpdateStatus.UNKNOWN);
|
||||
|
||||
targetStatus = reportManagement.targetStatus();
|
||||
for (final DataReportSeriesItem<TargetUpdateStatus> reportItem : targetStatus.getData()) {
|
||||
|
||||
switch (reportItem.getType()) {
|
||||
case ERROR:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownErrorCount * 2);
|
||||
break;
|
||||
case IN_SYNC:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownSyncCount * 2);
|
||||
break;
|
||||
case PENDING:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownPendingCount * 2);
|
||||
break;
|
||||
case REGISTERED:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownRegCount * 2);
|
||||
break;
|
||||
case UNKNOWN:
|
||||
assertThat(reportItem.getData()).isEqualTo(knownUnknownCount * 2);
|
||||
break;
|
||||
default:
|
||||
fail("missing case for unknown target update status " + reportItem.getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void topXDistributionUsage() {
|
||||
|
||||
final Target knownTarget1 = targetManagement.createTarget(new Target("t1"));
|
||||
final Target knownTarget2 = targetManagement.createTarget(new Target("t2"));
|
||||
final Target knownTarget3 = targetManagement.createTarget(new Target("t3"));
|
||||
final Target knownTarget4 = targetManagement.createTarget(new Target("t4"));
|
||||
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
final SoftwareModule jvm = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
|
||||
final SoftwareModule os = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
|
||||
|
||||
final DistributionSet distributionSet1 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.0", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet11 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds1", "0.0.1", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet2 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds2", "0.0.2", standardDsType, os, jvm, ah));
|
||||
final DistributionSet distributionSet3 = distributionSetManagement
|
||||
.createDistributionSet(TestDataUtil.buildDistributionSet("ds3", "0.0.3", standardDsType, os, jvm, ah));
|
||||
|
||||
// ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3]
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget1.getControllerId());
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget2.getControllerId());
|
||||
deploymentManagement.assignDistributionSet(distributionSet11.getId(), knownTarget3.getControllerId());
|
||||
|
||||
// ds2=[target4]
|
||||
deploymentManagement.assignDistributionSet(distributionSet2.getId(), knownTarget4.getControllerId());
|
||||
|
||||
// expect: ds1(0.0.0)=[target1,target2], ds1(0.0.1)=[target3],
|
||||
// ds2=[target4], ds3=[]
|
||||
|
||||
List<InnerOuterDataReportSeries<String>> distributionUsage = reportManagement.distributionUsageAssigned(100);
|
||||
|
||||
for (final InnerOuterDataReportSeries<String> innerOuterDataReportSeries : distributionUsage) {
|
||||
|
||||
// innerseries only have one data of the name and the total count
|
||||
final DataReportSeriesItem<String> dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries()
|
||||
.getData()[0];
|
||||
if (dataReportSeriesItem.getType().equals("ds1")) {
|
||||
// total count of three because ds1 has two different versions
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(3L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(Arrays.stream(outerData).map(DataReportSeriesItem::getType).collect(Collectors.toList()))
|
||||
.contains("0.0.0", "0.0.1");
|
||||
} else if (dataReportSeriesItem.getType().equals("ds2")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(1L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(outerData).hasSize(1);
|
||||
assertThat(outerData[0].getType()).isEqualTo("0.0.2");
|
||||
|
||||
} else if (dataReportSeriesItem.getType().equals("ds3")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(0L);
|
||||
final DataReportSeriesItem<String>[] outerData = innerOuterDataReportSeries.getOuterSeries().getData();
|
||||
assertThat(outerData).hasSize(1);
|
||||
assertThat(outerData[0].getType()).isEqualTo("0.0.3");
|
||||
} else {
|
||||
fail("no assertion count for distribution set " + dataReportSeriesItem.getType());
|
||||
}
|
||||
}
|
||||
|
||||
// test cache evict
|
||||
final Target knownTarget5 = targetManagement.createTarget(new Target("t5"));
|
||||
deploymentManagement.assignDistributionSet(distributionSet1.getId(), knownTarget5.getControllerId());
|
||||
distributionUsage = reportManagement.distributionUsageAssigned(100);
|
||||
for (final InnerOuterDataReportSeries<String> innerOuterDataReportSeries : distributionUsage) {
|
||||
final DataReportSeriesItem<String> dataReportSeriesItem = innerOuterDataReportSeries.getInnerSeries()
|
||||
.getData()[0];
|
||||
if (dataReportSeriesItem.getType().equals("ds1")) {
|
||||
assertThat(dataReportSeriesItem.getData()).isEqualTo(4L);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests correct statistics calculation including a correct cache evict.")
|
||||
public void lastPollTargets() {
|
||||
// --- prepare ---
|
||||
final LocalDateTime now = LocalDateTime.now();
|
||||
final int knownTargetsPollLastHour = 2;
|
||||
final int knownTargetsPollLastDay = 3;
|
||||
final int knownTargetsPollLastWeek = 4;
|
||||
final int knownTargetsPollLastMonth = 5;
|
||||
final int knownTargetsPollLastYear = 6;
|
||||
final int knownTargetsNeverPoll = 7;
|
||||
// never
|
||||
createTargets("neverPoll", knownTargetsNeverPoll, null);
|
||||
// hour
|
||||
createTargets("hourPoll", knownTargetsPollLastHour, now.minusMinutes(59));
|
||||
// day
|
||||
createTargets("dayPoll", knownTargetsPollLastDay, now.minusHours(23));
|
||||
// week
|
||||
createTargets("weekPoll", knownTargetsPollLastWeek, now.minusDays(6));
|
||||
// month
|
||||
createTargets("monthPoll", knownTargetsPollLastMonth, now.minusWeeks(3));
|
||||
// year
|
||||
createTargets("yearPoll", knownTargetsPollLastYear, now.minusMonths(11));
|
||||
|
||||
// --- Test ---
|
||||
DataReportSeries<SeriesTime> targetsNotLastPoll = reportManagement.targetsLastPoll();
|
||||
DataReportSeriesItem<SeriesTime>[] data = targetsNotLastPoll.getData();
|
||||
|
||||
// for( final DataReportSeriesItem<SeriesTime> dataReportSeriesItem :
|
||||
// data ) {
|
||||
// System.out.println( dataReportSeriesItem.getData() );
|
||||
// }
|
||||
|
||||
// --- Verfiy ---
|
||||
|
||||
// verify hour
|
||||
assertThat(data[0].getType()).isEqualTo(SeriesTime.HOUR);
|
||||
assertThat(data[0].getData()).isEqualTo((long) knownTargetsPollLastHour);
|
||||
// verify day
|
||||
assertThat(data[1].getType()).isEqualTo(SeriesTime.DAY);
|
||||
assertThat(data[1].getData()).isEqualTo((long) knownTargetsPollLastDay);
|
||||
// verify week
|
||||
assertThat(data[2].getType()).isEqualTo(SeriesTime.WEEK);
|
||||
assertThat(data[2].getData()).isEqualTo((long) knownTargetsPollLastWeek);
|
||||
|
||||
// test cache evict
|
||||
createTargets("hourPoll2", knownTargetsPollLastHour, now.minusMinutes(59));
|
||||
targetsNotLastPoll = reportManagement.targetsLastPoll();
|
||||
data = targetsNotLastPoll.getData();
|
||||
assertThat(data[0].getType()).isEqualTo(SeriesTime.HOUR);
|
||||
assertThat(data[0].getData()).isEqualTo((long) knownTargetsPollLastHour * 2);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(tenantId = "mytenant", allSpPermissions = true)
|
||||
@Description("Ensures that targets created report is tenant aware and only creates a report for the current tenant.")
|
||||
public void targetsCreatedOverPeriodMultiTenancyAware() throws Exception {
|
||||
final int targetCreateAmount = 10;
|
||||
|
||||
// create targets for another tenant
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "anotherTenant"), new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
for (int index = 0; index < targetCreateAmount; index++) {
|
||||
targetManagement.createTarget(new Target("t" + index));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// ensure targets has been created for 'anotherTenant'
|
||||
final Slice<Target> targetsForAnotherTenant = securityRule.runAs(
|
||||
WithSpringAuthorityRule.withUserAndTenant("user", "anotherTenant"), new Callable<Slice<Target>>() {
|
||||
@Override
|
||||
public Slice<Target> call() throws Exception {
|
||||
return targetManagement.findTargetsAll(new PageRequest(0, 1000));
|
||||
}
|
||||
});
|
||||
assertThat(targetsForAnotherTenant).hasSize(targetCreateAmount);
|
||||
|
||||
final LocalDateTime to = LocalDateTime.now();
|
||||
final LocalDateTime from = to.minusMonths(targetCreateAmount);
|
||||
// now retrieve the report for the 'mytenant'
|
||||
final DataReportSeries<LocalDate> targetsCreatedOverPeriod = reportManagement
|
||||
.targetsCreatedOverPeriod(DateTypes.perMonth(), from, to);
|
||||
// final no targets should final be created for this tenant
|
||||
assertThat(targetsCreatedOverPeriod.getData()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
private void createTargets(final String prefix, final int amount, final LocalDateTime lastTargetQuery) {
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final Target target = new Target(prefix + index);
|
||||
final Target createTarget = targetManagement.createTarget(target);
|
||||
if (lastTargetQuery != null) {
|
||||
final TargetInfo targetInfo = createTarget.getTargetInfo();
|
||||
targetInfo.setNew(false);
|
||||
targetInfo
|
||||
.setLastTargetQuery(lastTargetQuery.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
|
||||
targetInfoRepository.save(targetInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createTargetsWithStatus(final String prefix, final long amount, final TargetUpdateStatus status) {
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final Target target = new Target(prefix + index);
|
||||
final Target sTarget = targetRepository.save(target);
|
||||
final TargetInfo targetInfo = sTarget.getTargetInfo();
|
||||
targetInfo.setUpdateStatus(status);
|
||||
targetInfoRepository.save(targetInfo);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Target> sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable<Target> targs,
|
||||
final Status status, final String... msgs) {
|
||||
final List<Target> result = new ArrayList<Target>();
|
||||
for (final Target t : targs) {
|
||||
final List<Action> findByTarget = actionRepository.findByTarget(t);
|
||||
for (final Action action : findByTarget) {
|
||||
result.add(sendUpdateActionStatusToTarget(status, action, t, msgs));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t,
|
||||
final String... msgs) {
|
||||
updActA.setStatus(status);
|
||||
|
||||
final ActionStatus statusMessages = new ActionStatus();
|
||||
statusMessages.setAction(updActA);
|
||||
statusMessages.setOccurredAt(System.currentTimeMillis());
|
||||
statusMessages.setStatus(status);
|
||||
for (final String msg : msgs) {
|
||||
statusMessages.addMessage(msg);
|
||||
}
|
||||
controllerManagament.addUpdateActionStatus(statusMessages, updActA);
|
||||
return targetManagement.findTargetByControllerID(t.getControllerId());
|
||||
}
|
||||
|
||||
private class DynamicDateTimeProvider implements DateTimeProvider {
|
||||
|
||||
private Calendar datetime = Calendar.getInstance();
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see org.springframework.data.auditing.DateTimeProvider#getNow()
|
||||
*/
|
||||
@Override
|
||||
public Calendar getNow() {
|
||||
return datetime;
|
||||
}
|
||||
|
||||
public void now() {
|
||||
datetime = Calendar.getInstance();
|
||||
}
|
||||
|
||||
public void nowMinusMonths(final int amount) {
|
||||
datetime = Calendar.getInstance();
|
||||
datetime.add(Calendar.MONTH, -amount);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param datetime
|
||||
* the datetime to set
|
||||
*/
|
||||
public void setDatetime(final Calendar datetime) {
|
||||
this.datetime = datetime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,794 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder;
|
||||
import org.eclipse.hawkbit.repository.exception.DistributionSetTypeUndefinedException;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityLockedException;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityReadOnlyException;
|
||||
import org.eclipse.hawkbit.repository.exception.UnsupportedSoftwareModuleForThisDistributionSetException;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* {@link SoftwareManagement} test focused on {@link DistributionSet} and
|
||||
* {@link DistributionSetType} related stuff.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Software Management")
|
||||
public class SoftwareManagementForDSTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests the successfull module update of unused distribution set type which is in fact allowed.")
|
||||
public void updateUnassignedDistributionSetTypeModules() {
|
||||
DistributionSetType updatableType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("updatableType", "to be deleted", ""));
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.isEmpty();
|
||||
|
||||
// add OS
|
||||
updatableType.addMandatoryModuleType(osType);
|
||||
updatableType = distributionSetManagement.updateDistributionSetType(updatableType);
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.containsOnly(osType);
|
||||
|
||||
// add JVM
|
||||
updatableType.addMandatoryModuleType(runtimeType);
|
||||
updatableType = distributionSetManagement.updateDistributionSetType(updatableType);
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.containsOnly(osType, runtimeType);
|
||||
|
||||
// remove OS
|
||||
updatableType.removeModuleType(osType.getId());
|
||||
updatableType = distributionSetManagement.updateDistributionSetType(updatableType);
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.containsOnly(runtimeType);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the successfull update of used distribution set type meta data hich is in fact allowed.")
|
||||
public void updateAssignedDistributionSetTypeMetaData() {
|
||||
final DistributionSetType nonUpdatableType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", ""));
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.isEmpty();
|
||||
distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null));
|
||||
|
||||
nonUpdatableType.setDescription("a new description");
|
||||
nonUpdatableType.setColour("test123");
|
||||
|
||||
distributionSetManagement.updateDistributionSetType(nonUpdatableType);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getDescription())
|
||||
.isEqualTo("a new description");
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getColour())
|
||||
.isEqualTo("test123");
|
||||
}
|
||||
|
||||
@Test(expected = EntityReadOnlyException.class)
|
||||
@Description("Tests the unsuccessfull update of used distribution set type (module addition).")
|
||||
public void addModuleToAssignedDistributionSetTypeFails() {
|
||||
final DistributionSetType nonUpdatableType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", ""));
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.isEmpty();
|
||||
distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null));
|
||||
|
||||
nonUpdatableType.addMandatoryModuleType(osType);
|
||||
distributionSetManagement.updateDistributionSetType(nonUpdatableType);
|
||||
}
|
||||
|
||||
@Test(expected = EntityReadOnlyException.class)
|
||||
@Description("Tests the unsuccessfull update of used distribution set type (module removal).")
|
||||
public void removeModuleToAssignedDistributionSetTypeFails() {
|
||||
DistributionSetType nonUpdatableType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("updatableType", "to be deletd", ""));
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("updatableType").getMandatoryModuleTypes())
|
||||
.isEmpty();
|
||||
|
||||
nonUpdatableType.addMandatoryModuleType(osType);
|
||||
nonUpdatableType = distributionSetManagement.updateDistributionSetType(nonUpdatableType);
|
||||
distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null));
|
||||
|
||||
nonUpdatableType.removeModuleType(osType.getId());
|
||||
nonUpdatableType = distributionSetManagement.updateDistributionSetType(nonUpdatableType);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the successfull deletion of unused (hard delete) distribution set types.")
|
||||
public void deleteUnassignedDistributionSetType() {
|
||||
final DistributionSetType hardDelete = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("deleted", "to be deleted", ""));
|
||||
|
||||
assertThat(distributionSetTypeRepository.findAll()).contains(hardDelete);
|
||||
distributionSetManagement.deleteDistributionSetType(hardDelete);
|
||||
|
||||
assertThat(distributionSetTypeRepository.findAll()).doesNotContain(hardDelete);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the successfull deletion of used (soft delete) distribution set types.")
|
||||
public void deleteAssignedDistributionSetType() {
|
||||
final DistributionSetType softDelete = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("softdeleted", "to be deletd", ""));
|
||||
|
||||
assertThat(distributionSetTypeRepository.findAll()).contains(softDelete);
|
||||
final DistributionSet dsNewType = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("newtypesoft", "1", "", softDelete, null));
|
||||
|
||||
distributionSetManagement.deleteDistributionSetType(softDelete);
|
||||
assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").isDeleted()).isEqualTo(true);
|
||||
}
|
||||
|
||||
// TODO: kzimmerm: test N+1
|
||||
|
||||
@Test(expected = EntityAlreadyExistsException.class)
|
||||
@Description("Ensures that it is not possible to create a DS that already exists (unique constraint is on name,version for DS).")
|
||||
public void createDuplicateDistributionSetsFailsWithException() {
|
||||
TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement);
|
||||
|
||||
TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks that metadata for a distribution set can be created.")
|
||||
public void createDistributionSetMetadata() {
|
||||
final String knownKey = "dsMetaKnownKey";
|
||||
final String knownValue = "dsMetaKnownValue";
|
||||
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("testDs", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final DistributionSetMetadata metadata = new DistributionSetMetadata(knownKey, ds, knownValue);
|
||||
final DistributionSetMetadata createdMetadata = distributionSetManagement
|
||||
.createDistributionSetMetadata(metadata);
|
||||
|
||||
assertThat(createdMetadata).isNotNull();
|
||||
assertThat(createdMetadata.getId().getKey()).isEqualTo(knownKey);
|
||||
assertThat(createdMetadata.getDistributionSet().getId()).isEqualTo(ds.getId());
|
||||
assertThat(createdMetadata.getValue()).isEqualTo(knownValue);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that updates concerning the internal software structure of a DS are not possible if the DS is already assigned.")
|
||||
public void updateDistributionSetForbiddedWithIllegalUpdate() {
|
||||
// prepare data
|
||||
Target target = new Target("4711");
|
||||
target = targetManagement.createTarget(target);
|
||||
|
||||
SoftwareModule ah2 = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, "");
|
||||
SoftwareModule os2 = new SoftwareModule(osType, "poky2", "3.0.3", null, "");
|
||||
|
||||
DistributionSet ds = TestDataUtil.generateDistributionSet("ds-1", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
ah2 = softwareManagement.createSoftwareModule(ah2);
|
||||
os2 = softwareManagement.createSoftwareModule(os2);
|
||||
|
||||
// update is allowed as it is still not assigned to a target
|
||||
ds.addModule(ah2);
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
|
||||
// assign target
|
||||
deploymentManagement.assignDistributionSet(ds.getId(), target.getControllerId());
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
|
||||
// description change is still allowed
|
||||
ds.setDescription("a different desc");
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
|
||||
// description change is still allowed
|
||||
ds.setName("a new name");
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
|
||||
// description change is still allowed
|
||||
ds.setVersion("a new version");
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
|
||||
// not allowed as it is assigned now
|
||||
ds.addModule(os2);
|
||||
try {
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
fail("Expected EntityLockedException");
|
||||
} catch (final EntityLockedException e) {
|
||||
|
||||
}
|
||||
|
||||
// not allowed as it is assigned now
|
||||
ds.removeModule(ds.findFirstModuleByType(appType));
|
||||
try {
|
||||
ds = distributionSetManagement.updateDistributionSet(ds);
|
||||
fail("Expected EntityLockedException");
|
||||
} catch (final EntityLockedException e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = DistributionSetTypeUndefinedException.class)
|
||||
@Description("Ensures that it is not possible to add a software module to a set that has no type defined.")
|
||||
public void updateDistributionSetModuleWithUndefinedTypeFails() {
|
||||
final DistributionSet testSet = new DistributionSet();
|
||||
final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, "");
|
||||
|
||||
// update data
|
||||
testSet.addModule(module);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedSoftwareModuleForThisDistributionSetException.class)
|
||||
@Description("Ensures that it is not possible to add a software module that is not defined of the DS's type.")
|
||||
public void updateDistributionSetUnsupportedModuleFails() {
|
||||
final DistributionSet set = new DistributionSet("agent-hub2", "1.0.5", "desc",
|
||||
new DistributionSetType("test", "test", "test").addMandatoryModuleType(osType), null);
|
||||
final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, "");
|
||||
|
||||
// update data
|
||||
set.addModule(module);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Legal updates of a DS, e.g. name or description and module addition, removal while still unassigned.")
|
||||
public void updateDistributionSet() {
|
||||
// prepare data
|
||||
Target target = new Target("4711");
|
||||
target = targetManagement.createTarget(target);
|
||||
|
||||
SoftwareModule os2 = new SoftwareModule(osType, "poky2", "3.0.3", null, "");
|
||||
final SoftwareModule app2 = new SoftwareModule(appType, "app2", "3.0.3", null, "");
|
||||
|
||||
DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement);
|
||||
|
||||
os2 = softwareManagement.createSoftwareModule(os2);
|
||||
|
||||
// update data
|
||||
// legal update of module addition
|
||||
ds.addModule(os2);
|
||||
distributionSetManagement.updateDistributionSet(ds);
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
assertThat(ds.findFirstModuleByType(osType)).isEqualTo(os2);
|
||||
|
||||
// legal update of module removal
|
||||
ds.removeModule(ds.findFirstModuleByType(appType));
|
||||
distributionSetManagement.updateDistributionSet(ds);
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
assertThat(ds.findFirstModuleByType(appType)).isNull();
|
||||
|
||||
// Update description
|
||||
ds.setDescription("a new description");
|
||||
distributionSetManagement.updateDistributionSet(ds);
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
assertThat(ds.getDescription()).isEqualTo("a new description");
|
||||
|
||||
// Update name
|
||||
ds.setName("a new name");
|
||||
distributionSetManagement.updateDistributionSet(ds);
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
assertThat(ds.getName()).isEqualTo("a new name");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(allSpPermissions = true)
|
||||
@Description("Checks that metadata for a distribution set can be updated.")
|
||||
public void updateDistributionSetMetadata() throws InterruptedException {
|
||||
final String knownKey = "myKnownKey";
|
||||
final String knownValue = "myKnownValue";
|
||||
final String knownUpdateValue = "myNewUpdatedValue";
|
||||
|
||||
// create a DS
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("testDs", softwareManagement,
|
||||
distributionSetManagement);
|
||||
// initial opt lock revision must be zero
|
||||
assertThat(ds.getOptLockRevision()).isEqualTo(1L);
|
||||
|
||||
// create an DS meta data entry
|
||||
final DistributionSetMetadata dsMetadata = distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, ds, knownValue));
|
||||
|
||||
DistributionSet changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId());
|
||||
assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(2L);
|
||||
|
||||
// modifying the meta data value
|
||||
dsMetadata.setValue(knownUpdateValue);
|
||||
dsMetadata.setKey(knownKey);
|
||||
dsMetadata.setDistributionSet(changedLockRevisionDS);
|
||||
|
||||
Thread.sleep(100);
|
||||
|
||||
// update the DS metadata
|
||||
final DistributionSetMetadata updated = distributionSetManagement.updateDistributionSetMetadata(dsMetadata);
|
||||
// we are updating the sw meta data so also modifying the base software
|
||||
// module so opt lock
|
||||
// revision must be three
|
||||
changedLockRevisionDS = distributionSetManagement.findDistributionSetById(ds.getId());
|
||||
assertThat(changedLockRevisionDS.getOptLockRevision()).isEqualTo(3L);
|
||||
assertThat(changedLockRevisionDS.getLastModifiedAt()).isGreaterThan(0L);
|
||||
|
||||
// verify updated meta data contains the updated value
|
||||
assertThat(updated).isNotNull();
|
||||
assertThat(updated.getValue()).isEqualTo(knownUpdateValue);
|
||||
assertThat(updated.getId().getKey()).isEqualTo(knownKey);
|
||||
assertThat(updated.getDistributionSet().getId()).isEqualTo(ds.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests that a DS queue is possible where the result is ordered by the target assignment, i.e. assigned first in the list.")
|
||||
public void findDistributionSetsAllOrderedByLinkTarget() {
|
||||
|
||||
final List<DistributionSet> buildDistributionSets = TestDataUtil.generateDistributionSets("dsOrder", 10,
|
||||
softwareManagement, distributionSetManagement);
|
||||
|
||||
final List<Target> buildTargetFixtures = targetManagement
|
||||
.createTargets(TestDataUtil.buildTargetFixtures(5, "tOrder", "someDesc"));
|
||||
|
||||
final Iterator<DistributionSet> dsIterator = buildDistributionSets.iterator();
|
||||
final Iterator<Target> tIterator = buildTargetFixtures.iterator();
|
||||
final DistributionSet dsFirst = dsIterator.next();
|
||||
final DistributionSet dsSecond = dsIterator.next();
|
||||
final DistributionSet dsThree = dsIterator.next();
|
||||
final DistributionSet dsFour = dsIterator.next();
|
||||
final Target tFirst = tIterator.next();
|
||||
final Target tSecond = tIterator.next();
|
||||
|
||||
// set assigned
|
||||
deploymentManagement.assignDistributionSet(dsSecond.getId(), tSecond.getControllerId());
|
||||
deploymentManagement.assignDistributionSet(dsThree.getId(), tFirst.getControllerId());
|
||||
// set installed
|
||||
final ArrayList<Target> installedDSSecond = new ArrayList<>();
|
||||
installedDSSecond.add(tSecond);
|
||||
sendUpdateActionStatusToTargets(dsSecond, installedDSSecond, Status.FINISHED, "some message");
|
||||
|
||||
deploymentManagement.assignDistributionSet(dsFour.getId(), tSecond.getControllerId());
|
||||
|
||||
final DistributionSetFilterBuilder distributionSetFilterBuilder = new DistributionSetFilterBuilder()
|
||||
.setIsDeleted(false).setIsComplete(true).setSelectDSWithNoTag(Boolean.FALSE);
|
||||
|
||||
// target first only has an assigned DS-three so check order correct
|
||||
final List<DistributionSet> tFirstPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget(
|
||||
pageReq, distributionSetFilterBuilder, tFirst.getControllerId()).getContent();
|
||||
assertThat(tFirstPin.get(0)).isEqualTo(dsThree);
|
||||
assertThat(tFirstPin).hasSize(10);
|
||||
|
||||
// target second has installed DS-2 and assigned DS-4 so check order
|
||||
// correct
|
||||
final List<DistributionSet> tSecondPin = distributionSetManagement.findDistributionSetsAllOrderedByLinkTarget(
|
||||
pageReq, distributionSetFilterBuilder, tSecond.getControllerId()).getContent();
|
||||
assertThat(tSecondPin.get(0)).isEqualTo(dsSecond);
|
||||
assertThat(tSecondPin.get(1)).isEqualTo(dsFour);
|
||||
assertThat(tFirstPin).hasSize(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("searches for distribution sets based on the various filter options, e.g. name, version, desc., tags.")
|
||||
public void searchDistributionSetsOnFilters() {
|
||||
DistributionSetTag dsTagA = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("DistributionSetTag-A"));
|
||||
final DistributionSetTag dsTagB = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("DistributionSetTag-B"));
|
||||
final DistributionSetTag dsTagC = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("DistributionSetTag-C"));
|
||||
final DistributionSetTag dsTagD = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("DistributionSetTag-D"));
|
||||
|
||||
List<DistributionSet> ds100Group1 = TestDataUtil.generateDistributionSets("", 100, softwareManagement,
|
||||
distributionSetManagement);
|
||||
List<DistributionSet> ds100Group2 = TestDataUtil.generateDistributionSets("test2", 100, softwareManagement,
|
||||
distributionSetManagement);
|
||||
DistributionSet dsDeleted = TestDataUtil.generateDistributionSet("deleted", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final DistributionSet dsInComplete = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("notcomplete", "1", "", standardDsType, null));
|
||||
|
||||
final DistributionSetType newType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("foo", "bar", "test").addMandatoryModuleType(osType)
|
||||
.addOptionalModuleType(appType).addOptionalModuleType(runtimeType));
|
||||
|
||||
final DistributionSet dsNewType = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("newtype", "1", "", newType, dsDeleted.getModules()));
|
||||
|
||||
deploymentManagement.assignDistributionSet(dsDeleted,
|
||||
targetManagement.createTargets(Lists.newArrayList(TestDataUtil.generateTargets(5))));
|
||||
distributionSetManagement.deleteDistributionSet(dsDeleted);
|
||||
dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId());
|
||||
|
||||
ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagA).getAssignedDs();
|
||||
dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName());
|
||||
ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagB).getAssignedDs();
|
||||
dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName());
|
||||
ds100Group2 = distributionSetManagement.toggleTagAssignment(ds100Group2, dsTagA).getAssignedDs();
|
||||
dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName());
|
||||
|
||||
// check setup
|
||||
assertThat(distributionSetRepository.findAll()).hasSize(203);
|
||||
|
||||
// Find all
|
||||
List<DistributionSet> expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group1);
|
||||
expected.addAll(ds100Group2);
|
||||
expected.add(dsDeleted);
|
||||
expected.add(dsInComplete);
|
||||
expected.add(dsNewType);
|
||||
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, getDistributionSetFilterBuilder().build()).getContent())
|
||||
.hasSize(203).containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
DistributionSetFilterBuilder distributionSetFilterBuilder;
|
||||
|
||||
// search for not deleted
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(false);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(202);
|
||||
|
||||
// search for completed
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group1);
|
||||
expected.addAll(ds100Group2);
|
||||
expected.add(dsDeleted);
|
||||
expected.add(dsNewType);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(202)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.add(dsInComplete);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
// search for type
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(202);
|
||||
|
||||
// search for text
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setSearchText("%test2");
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(100);
|
||||
|
||||
// search for tags
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
|
||||
.setTagNames(Lists.newArrayList(dsTagA.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(200);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
|
||||
.setTagNames(Lists.newArrayList(dsTagB.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(100);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
|
||||
.setTagNames(Lists.newArrayList(dsTagA.getName(), dsTagB.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(200);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
|
||||
.setTagNames(Lists.newArrayList(dsTagC.getName(), dsTagB.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent())
|
||||
.hasSize(100);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder()
|
||||
.setTagNames(Lists.newArrayList(dsTagC.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
// combine deleted and complete
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group1);
|
||||
expected.addAll(ds100Group2);
|
||||
expected.add(dsNewType);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setIsDeleted(Boolean.FALSE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(201)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.add(dsInComplete);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.FALSE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.add(dsDeleted);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setIsDeleted(Boolean.TRUE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
|
||||
.setIsComplete(Boolean.FALSE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
// combine deleted and complete and type
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group1);
|
||||
expected.addAll(ds100Group2);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.FALSE)
|
||||
.setIsComplete(Boolean.TRUE).setType(standardDsType);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(200)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.add(dsDeleted);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setType(standardDsType).setIsDeleted(Boolean.TRUE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.TRUE)
|
||||
.setIsComplete(Boolean.FALSE).setType(standardDsType);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.add(dsNewType);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE).setType(newType);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(1)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
// combine deleted and complete and type and text
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group2);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setType(standardDsType).setSearchText("%test2");
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setIsDeleted(Boolean.TRUE).setType(standardDsType).setSearchText("%test2");
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
|
||||
.setIsComplete(false).setIsDeleted(false);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(newType).setSearchText("%test2")
|
||||
.setIsComplete(Boolean.TRUE).setIsDeleted(false);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
// combine deleted and complete and type and text and tag
|
||||
expected = new ArrayList<DistributionSet>();
|
||||
expected.addAll(ds100Group2);
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true).setType(standardDsType)
|
||||
.setSearchText("%test2").setTagNames(Lists.newArrayList(dsTagA.getName()));
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(100)
|
||||
.containsOnly(expected.toArray(new DistributionSet[0]));
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setType(standardDsType).setSearchText("%test2")
|
||||
.setTagNames(Lists.newArrayList(dsTagA.getName())).setIsComplete(Boolean.FALSE)
|
||||
.setIsDeleted(Boolean.FALSE);
|
||||
assertThat(distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
private DistributionSetFilterBuilder getDistributionSetFilterBuilder() {
|
||||
return new DistributionSetFilterBuilder();
|
||||
}
|
||||
|
||||
private List<Target> sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable<Target> targs,
|
||||
final Status status, final String... msgs) {
|
||||
final List<Target> result = new ArrayList<Target>();
|
||||
for (final Target t : targs) {
|
||||
final List<Action> findByTarget = actionRepository.findByTarget(t);
|
||||
for (final Action action : findByTarget) {
|
||||
result.add(sendUpdateActionStatusToTarget(status, action, t, msgs));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Simple DS load without the related data that should be loaded lazy.")
|
||||
public void findDistributionSetsWithoutLazy() {
|
||||
TestDataUtil.generateDistributionSets(20, softwareManagement, distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Deltes a DS that is no in use. Expected behaviour is a hard delete on the database.")
|
||||
public void deleteUnassignedDistributionSet() {
|
||||
DistributionSet ds1 = TestDataUtil.generateDistributionSet("ds-1", softwareManagement,
|
||||
distributionSetManagement);
|
||||
DistributionSet ds2 = TestDataUtil.generateDistributionSet("ds-2", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion());
|
||||
ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion());
|
||||
|
||||
// delete a ds
|
||||
assertThat(distributionSetRepository.findAll()).hasSize(2);
|
||||
distributionSetManagement.deleteDistributionSet(ds1.getId());
|
||||
// not assigned so not marked as deleted but fully deleted
|
||||
assertThat(distributionSetRepository.findAll()).hasSize(1);
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, Boolean.FALSE, Boolean.TRUE)
|
||||
.getTotalElements()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Queries and loads the metadata related to a given software module.")
|
||||
public void findAllDistributionSetMetadataByDsId() {
|
||||
// create a DS
|
||||
DistributionSet ds1 = TestDataUtil.generateDistributionSet("testDs1", softwareManagement,
|
||||
distributionSetManagement);
|
||||
DistributionSet ds2 = TestDataUtil.generateDistributionSet("testDs2", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
for (int index = 0; index < 10; index++) {
|
||||
|
||||
ds1 = distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata("key" + index, ds1, "value" + index))
|
||||
.getDistributionSet();
|
||||
}
|
||||
|
||||
for (int index = 0; index < 20; index++) {
|
||||
|
||||
ds2 = distributionSetManagement
|
||||
.createDistributionSetMetadata(new DistributionSetMetadata("key" + index, ds2, "value" + index))
|
||||
.getDistributionSet();
|
||||
}
|
||||
|
||||
final Page<DistributionSetMetadata> metadataOfDs1 = distributionSetManagement
|
||||
.findDistributionSetMetadataByDistributionSetId(ds1.getId(), new PageRequest(0, 100));
|
||||
|
||||
final Page<DistributionSetMetadata> metadataOfDs2 = distributionSetManagement
|
||||
.findDistributionSetMetadataByDistributionSetId(ds2.getId(), new PageRequest(0, 100));
|
||||
|
||||
assertThat(metadataOfDs1.getNumberOfElements()).isEqualTo(10);
|
||||
assertThat(metadataOfDs1.getTotalElements()).isEqualTo(10);
|
||||
|
||||
assertThat(metadataOfDs2.getNumberOfElements()).isEqualTo(20);
|
||||
assertThat(metadataOfDs2.getTotalElements()).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Deltes a DS that is no in use. Expected behaviour is a soft delete on the database, i.e. only marked as "
|
||||
+ "deleted, kept eas refernce and unavailable for future use..")
|
||||
public void deleteAssignedDistributionSet() {
|
||||
DistributionSet ds1 = TestDataUtil.generateDistributionSet("ds-1", softwareManagement,
|
||||
distributionSetManagement);
|
||||
DistributionSet ds2 = TestDataUtil.generateDistributionSet("ds-2", softwareManagement,
|
||||
distributionSetManagement);
|
||||
DistributionSet dsAssigned = TestDataUtil.generateDistributionSet("ds-3", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
ds1 = distributionSetManagement.findDistributionSetByNameAndVersion(ds1.getName(), ds1.getVersion());
|
||||
ds2 = distributionSetManagement.findDistributionSetByNameAndVersion(ds2.getName(), ds2.getVersion());
|
||||
|
||||
// create assigned DS
|
||||
dsAssigned = distributionSetManagement.findDistributionSetByNameAndVersion(dsAssigned.getName(),
|
||||
dsAssigned.getVersion());
|
||||
final Target target = new Target("4712");
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
deploymentManagement.assignDistributionSet(dsAssigned, toAssign);
|
||||
|
||||
// delete a ds
|
||||
assertThat(distributionSetRepository.findAll()).hasSize(3);
|
||||
distributionSetManagement.deleteDistributionSet(dsAssigned.getId());
|
||||
|
||||
// not assigned so not marked as deleted
|
||||
assertThat(distributionSetRepository.findAll()).hasSize(3);
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, Boolean.FALSE, Boolean.TRUE)
|
||||
.getTotalElements()).isEqualTo(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* helper method which re-orders a list as expected. Re-orders the given
|
||||
* distribution set in the order as given and returns a new list with the
|
||||
* new order.
|
||||
*
|
||||
* @param dsThree
|
||||
* @param buildDistributionSets
|
||||
* @return
|
||||
*/
|
||||
private List<DistributionSet> reOrderDSList(final Iterable<DistributionSet> buildDistributionSets,
|
||||
final DistributionSet... ds) {
|
||||
final List<DistributionSet> reOrderedList = new ArrayList<>();
|
||||
|
||||
final Iterator<DistributionSet> iterator = buildDistributionSets.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
final DistributionSet next = iterator.next();
|
||||
int reorder = -1;
|
||||
for (int index = 0; index < ds.length; index++) {
|
||||
if (next.equals(ds[index])) {
|
||||
reorder = index;
|
||||
}
|
||||
}
|
||||
if (reorder >= 0) {
|
||||
reOrderedList.add(reorder, next);
|
||||
} else {
|
||||
reOrderedList.add(next);
|
||||
}
|
||||
}
|
||||
|
||||
return reOrderedList;
|
||||
}
|
||||
|
||||
private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t,
|
||||
final String... msgs) {
|
||||
updActA.setStatus(status);
|
||||
|
||||
final ActionStatus statusMessages = new ActionStatus();
|
||||
statusMessages.setAction(updActA);
|
||||
statusMessages.setOccurredAt(System.currentTimeMillis());
|
||||
statusMessages.setStatus(status);
|
||||
for (final String msg : msgs) {
|
||||
statusMessages.addMessage(msg);
|
||||
}
|
||||
controllerManagament.addUpdateActionStatus(statusMessages, updActA);
|
||||
return targetManagement.findTargetByControllerID(t.getControllerId());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.RandomGeneratedInputStream;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Sets;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Software Management")
|
||||
public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB {
|
||||
|
||||
@Test
|
||||
@Description("searched for software modules based on the various filter options, e.g. name,desc,type, version.")
|
||||
public void findSoftwareModuleByFilters() {
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
final SoftwareModule jvm = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
|
||||
final SoftwareModule os = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
|
||||
|
||||
final SoftwareModule ah2 = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.2", null, ""));
|
||||
DistributionSet ds = distributionSetManagement.createDistributionSet(
|
||||
TestDataUtil.buildDistributionSet("ds-1", "1.0.1", standardDsType, os, jvm, ah2));
|
||||
|
||||
final Target target = targetManagement.createTarget(new Target("test123"));
|
||||
ds = assignSet(target, ds).getDistributionSet();
|
||||
|
||||
// standard searches
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "poky", osType).getContent()).hasSize(1);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "poky", osType).getContent().get(0))
|
||||
.isEqualTo(os);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "oracle%", runtimeType).getContent())
|
||||
.hasSize(1);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "oracle%", runtimeType).getContent().get(0))
|
||||
.isEqualTo(jvm);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0.1", appType).getContent()).hasSize(1);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0.1", appType).getContent().get(0))
|
||||
.isEqualTo(ah);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType).getContent()).hasSize(2);
|
||||
|
||||
// no we search with on entity marked as deleted
|
||||
softwareManagement.deleteSoftwareModule(
|
||||
softwareManagement.findSoftwareModuleByAssignedToAndType(pageReq, ds, appType).getContent().get(0));
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType).getContent()).hasSize(1);
|
||||
assertThat(softwareManagement.findSoftwareModuleByFilters(pageReq, "1.0%", appType).getContent().get(0))
|
||||
.isEqualTo(ah);
|
||||
}
|
||||
|
||||
private Action assignSet(final Target target, final DistributionSet ds) {
|
||||
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { target.getControllerId() });
|
||||
assertThat(
|
||||
targetManagement.findTargetByControllerID(target.getControllerId()).getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getAssignedDistributionSet())
|
||||
.isEqualTo(ds);
|
||||
final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0);
|
||||
assertThat(action).isNotNull();
|
||||
return action;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Searches for software modules based on a list of IDs.")
|
||||
public void findSoftwareModulesByIdAndType() {
|
||||
|
||||
final List<Long> modules = new ArrayList<Long>();
|
||||
|
||||
modules.add(softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky-una", "3.0.2", null, ""))
|
||||
.getId());
|
||||
modules.add(softwareManagement.createSoftwareModule(new SoftwareModule(osType, "poky-u2na", "3.0.3", null, ""))
|
||||
.getId());
|
||||
modules.add(624355263L);
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModulesById(modules)).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).")
|
||||
public void deleteAssignedAndUnassignedSoftwareModuleTypes() {
|
||||
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType,
|
||||
appType);
|
||||
|
||||
SoftwareModuleType type = softwareManagement.createSoftwareModuleType(
|
||||
new SoftwareModuleType("bundle", "OSGi Bundle", "fancy stuff", Integer.MAX_VALUE));
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType,
|
||||
appType, type);
|
||||
|
||||
// delete unassigned
|
||||
softwareManagement.deleteSoftwareModuleType(type);
|
||||
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType,
|
||||
appType);
|
||||
assertThat(softwareModuleTypeRepository.findAll()).hasSize(3).contains(osType, runtimeType, appType);
|
||||
|
||||
type = softwareManagement.createSoftwareModuleType(
|
||||
new SoftwareModuleType("bundle2", "OSGi Bundle2", "fancy stuff", Integer.MAX_VALUE));
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(4).contains(osType, runtimeType,
|
||||
appType, type);
|
||||
|
||||
softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(type, "Test SM", "1.0", "cool module", "from meeee"));
|
||||
|
||||
// delete assigned
|
||||
softwareManagement.deleteSoftwareModuleType(type);
|
||||
assertThat(softwareManagement.findSoftwareModuleTypesAll(pageReq)).hasSize(3).contains(osType, runtimeType,
|
||||
appType);
|
||||
|
||||
assertThat(softwareModuleTypeRepository.findAll()).hasSize(4).contains(osType, runtimeType, appType,
|
||||
softwareModuleTypeRepository.findOne(type.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Deletes an artifact, which is not assigned to a Distribution Set")
|
||||
public void hardDeleteOfNotAssignedArtifact() {
|
||||
|
||||
// [STEP1]: Create SoftwareModuleX with Artifacts
|
||||
SoftwareModule unassignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2);
|
||||
Iterator<Artifact> artifactsIt = unassignedModule.getArtifacts().iterator();
|
||||
Artifact artifact1 = artifactsIt.next();
|
||||
Artifact artifact2 = artifactsIt.next();
|
||||
|
||||
// [STEP2]: Delete unassigned SoftwareModule
|
||||
softwareManagement.deleteSoftwareModule(unassignedModule);
|
||||
|
||||
// [VERIFY EXPECTED RESULT]:
|
||||
// verify: SoftwareModule is deleted
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(0);
|
||||
assertThat(softwareManagement.findSoftwareModuleById(unassignedModule.getId())).isNull();
|
||||
|
||||
// verify: binary data of artifact is deleted
|
||||
assertArtfiactNull(artifact1, artifact2);
|
||||
|
||||
// verify: meta data of artifact is deleted
|
||||
assertThat(artifactRepository.findOne(artifact1.getId())).isNull();
|
||||
assertThat(artifactRepository.findOne(artifact2.getId())).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Deletes an artifact, which is assigned to a Distribution Set")
|
||||
public void softDeleteOfAssignedArtifact() {
|
||||
|
||||
// Init DistributionSet
|
||||
DistributionSet disSet = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("ds1", "v1.0", "test ds", standardDsType, null));
|
||||
|
||||
// [STEP1]: Create SoftwareModuleX with ArtifactX
|
||||
SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2);
|
||||
|
||||
// [STEP2]: Assign SoftwareModule to DistributionSet
|
||||
distributionSetManagement.assignSoftwareModules(disSet, Sets.newHashSet(assignedModule));
|
||||
|
||||
// [STEP3]: Delete the assigned SoftwareModule
|
||||
softwareManagement.deleteSoftwareModule(assignedModule);
|
||||
|
||||
// [VERIFY EXPECTED RESULT]:
|
||||
// verify: assignedModule is marked as deleted
|
||||
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId());
|
||||
assertTrue(assignedModule.isDeleted());
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(1);
|
||||
|
||||
// verify: binary data is deleted
|
||||
Iterator<Artifact> artifactsIt = assignedModule.getArtifacts().iterator();
|
||||
Artifact artifact1 = artifactsIt.next();
|
||||
Artifact artifact2 = artifactsIt.next();
|
||||
assertArtfiactNull(artifact1, artifact2);
|
||||
|
||||
// verify: artifact meta data is still available
|
||||
assertThat(artifactRepository.findOne(artifact1.getId())).isNotNull();
|
||||
assertThat(artifactRepository.findOne(artifact2.getId())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Delete an artifact, which has been assigned to a rolled out DistributionSet in the past")
|
||||
public void softDeleteOfHistoricalAssignedArtifact() {
|
||||
|
||||
// Init target and DistributionSet
|
||||
final Target target = targetManagement.createTarget(new Target("test123"));
|
||||
DistributionSet disSet = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("ds1", "v1.0", "test ds", standardDsType, null));
|
||||
|
||||
// [STEP1]: Create SoftwareModuleX and include the new ArtifactX
|
||||
SoftwareModule assignedModule = createSoftwareModuleWithArtifacts(osType, "moduleX", "3.0.2", 2);
|
||||
|
||||
// [STEP2]: Assign SoftwareModule to DistributionSet
|
||||
distributionSetManagement.assignSoftwareModules(disSet, Sets.newHashSet(assignedModule));
|
||||
|
||||
// [STEP3]: Assign DistributionSet to a Device
|
||||
deploymentManagement.assignDistributionSet(disSet, Lists.newArrayList(target));
|
||||
|
||||
// [STEP4]: Delete the DistributionSet
|
||||
distributionSetManagement.deleteDistributionSet(disSet);
|
||||
|
||||
// [STEP5]: Delete the assigned SoftwareModule
|
||||
softwareManagement.deleteSoftwareModule(assignedModule);
|
||||
|
||||
// [VERIFY EXPECTED RESULT]:
|
||||
// verify: assignedModule is marked as deleted
|
||||
assignedModule = softwareManagement.findSoftwareModuleById(assignedModule.getId());
|
||||
assertTrue(assignedModule.isDeleted());
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(1);
|
||||
|
||||
// verify: binary data is deleted
|
||||
Iterator<Artifact> artifactsIt = assignedModule.getArtifacts().iterator();
|
||||
Artifact artifact1 = artifactsIt.next();
|
||||
Artifact artifact2 = artifactsIt.next();
|
||||
assertArtfiactNull(artifact1, artifact2);
|
||||
|
||||
// verify: artifact meta data is still available
|
||||
assertThat(artifactRepository.findOne(artifact1.getId())).isNotNull();
|
||||
assertThat(artifactRepository.findOne(artifact2.getId())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Delete an softwaremodule with an artifact, which is also used by another softwaremodule.")
|
||||
public void deleteSoftwareModulesWithSharedArtifact() throws IOException {
|
||||
|
||||
// Precondition: Make sure MongoDB is Empty
|
||||
assertThat(operations.find(new Query())).hasSize(0);
|
||||
|
||||
// Init artifact binary data, target and DistributionSets
|
||||
byte[] source = RandomUtils.nextBytes(1024);
|
||||
|
||||
// [STEP1]: Create SoftwareModuleX and add a new ArtifactX
|
||||
SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0);
|
||||
|
||||
// [STEP2]: Create newArtifactX and add it to SoftwareModuleX
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false);
|
||||
moduleX = softwareManagement.findSoftwareModuleWithDetails(moduleX.getId());
|
||||
Artifact artifactX = moduleX.getArtifacts().iterator().next();
|
||||
|
||||
// [STEP3]: Create SoftwareModuleY and add the same ArtifactX
|
||||
SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0);
|
||||
|
||||
// [STEP4]: Assign the same ArtifactX to SoftwareModuleY
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false);
|
||||
moduleY = softwareManagement.findSoftwareModuleWithDetails(moduleY.getId());
|
||||
Artifact artifactY = moduleY.getArtifacts().iterator().next();
|
||||
|
||||
// verify: that only one entry was created in mongoDB
|
||||
assertThat(operations.find(new Query())).hasSize(1);
|
||||
|
||||
// [STEP5]: Delete SoftwareModuleX
|
||||
softwareManagement.deleteSoftwareModule(moduleX);
|
||||
|
||||
// [VERIFY EXPECTED RESULT]:
|
||||
// verify: SoftwareModuleX is deleted, and ModuelY still exists
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(1);
|
||||
assertThat(softwareManagement.findSoftwareModuleById(moduleX.getId())).isNull();
|
||||
assertThat(softwareManagement.findSoftwareModuleById(moduleY.getId())).isNotNull();
|
||||
|
||||
// verify: binary data of artifact is not deleted
|
||||
assertArtfiactNotNull(artifactY);
|
||||
|
||||
// verify: meta data of artifactX is deleted
|
||||
assertThat(artifactRepository.findOne(artifactX.getId())).isNull();
|
||||
|
||||
// verify: meta data of artifactY is not deleted
|
||||
assertThat(artifactRepository.findOne(artifactY.getId())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Delete two assigned softwaremodules which share an artifact.")
|
||||
public void deleteMultipleSoftwareModulesWhichShareAnArtifact() throws IOException {
|
||||
|
||||
// Precondition: Make sure MongoDB is Empty
|
||||
assertThat(operations.find(new Query())).hasSize(0);
|
||||
|
||||
// Init artifact binary data, target and DistributionSets
|
||||
final byte[] source = RandomUtils.nextBytes(1024);
|
||||
final Target target = targetManagement.createTarget(new Target("test123"));
|
||||
final DistributionSet disSetX = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("dsX", "v1.0", "test dsX", standardDsType, null));
|
||||
final DistributionSet disSetY = distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("dsY", "v1.0", "test dsY", standardDsType, null));
|
||||
|
||||
// [STEP1]: Create SoftwareModuleX and add a new ArtifactX
|
||||
SoftwareModule moduleX = createSoftwareModuleWithArtifacts(osType, "modulex", "v1.0", 0);
|
||||
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(source), moduleX.getId(), "artifactx", false);
|
||||
moduleX = softwareManagement.findSoftwareModuleWithDetails(moduleX.getId());
|
||||
Artifact artifactX = moduleX.getArtifacts().iterator().next();
|
||||
|
||||
// [STEP2]: Create SoftwareModuleY and add the same ArtifactX
|
||||
SoftwareModule moduleY = createSoftwareModuleWithArtifacts(osType, "moduley", "v1.0", 0);
|
||||
|
||||
artifactManagement.createLocalArtifact(new ByteArrayInputStream(source), moduleY.getId(), "artifactx", false);
|
||||
moduleY = softwareManagement.findSoftwareModuleWithDetails(moduleY.getId());
|
||||
Artifact artifactY = moduleY.getArtifacts().iterator().next();
|
||||
|
||||
// verify: that only one entry was created in mongoDB
|
||||
assertThat(operations.find(new Query())).hasSize(1);
|
||||
|
||||
// [STEP3]: Assign SoftwareModuleX to DistributionSetX and to target
|
||||
distributionSetManagement.assignSoftwareModules(disSetX, Sets.newHashSet(moduleX));
|
||||
deploymentManagement.assignDistributionSet(disSetX, Lists.newArrayList(target));
|
||||
|
||||
// [STEP4]: Assign SoftwareModuleY to DistributionSet and to target
|
||||
distributionSetManagement.assignSoftwareModules(disSetY, Sets.newHashSet(moduleY));
|
||||
deploymentManagement.assignDistributionSet(disSetY, Lists.newArrayList(target));
|
||||
|
||||
// [STEP5]: Delete SoftwareModuleX
|
||||
softwareManagement.deleteSoftwareModule(moduleX);
|
||||
|
||||
// [STEP6]: Delete SoftwareModuleY
|
||||
softwareManagement.deleteSoftwareModule(moduleY);
|
||||
|
||||
// [VERIFY EXPECTED RESULT]:
|
||||
moduleX = softwareManagement.findSoftwareModuleById(moduleX.getId());
|
||||
moduleY = softwareManagement.findSoftwareModuleById(moduleY.getId());
|
||||
|
||||
// verify: SoftwareModuleX and SofwtareModule are marked as deleted
|
||||
assertThat(moduleX).isNotNull();
|
||||
assertThat(moduleY).isNotNull();
|
||||
assertTrue(moduleX.isDeleted());
|
||||
assertTrue(moduleY.isDeleted());
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize(2);
|
||||
|
||||
// verify: binary data of artifact is deleted
|
||||
assertArtfiactNull(artifactX, artifactY);
|
||||
|
||||
// verify: meta data of artifactX and artifactY is not deleted
|
||||
assertThat(artifactRepository.findOne(artifactY.getId())).isNotNull();
|
||||
}
|
||||
|
||||
private SoftwareModule createSoftwareModuleWithArtifacts(SoftwareModuleType type, String name, String version,
|
||||
int numberArtifacts) {
|
||||
|
||||
long countSoftwareModule = softwareModuleRepository.count();
|
||||
|
||||
// create SoftwareModule
|
||||
SoftwareModule softwareModule = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(type, name, version, "description of artifact " + name, ""));
|
||||
|
||||
for (int i = 0; i < numberArtifacts; i++) {
|
||||
artifactManagement.createLocalArtifact(new RandomGeneratedInputStream(5 * 1024), softwareModule.getId(),
|
||||
"file" + (i + 1), false);
|
||||
}
|
||||
|
||||
// Verify correct Creation of SoftwareModule and corresponding artifacts
|
||||
softwareModule = softwareManagement.findSoftwareModuleWithDetails(softwareModule.getId());
|
||||
assertThat(softwareModuleRepository.findAll()).hasSize((int) countSoftwareModule + 1);
|
||||
|
||||
List<Artifact> artifacts = softwareModule.getArtifacts();
|
||||
|
||||
assertThat(artifacts).hasSize(numberArtifacts);
|
||||
if (numberArtifacts != 0) {
|
||||
assertArtfiactNotNull(artifacts.toArray(new Artifact[artifacts.size()]));
|
||||
}
|
||||
|
||||
artifacts.forEach(artifact -> {
|
||||
assertThat(artifactRepository.findOne(artifact.getId())).isNotNull();
|
||||
});
|
||||
return softwareModule;
|
||||
}
|
||||
|
||||
private void assertArtfiactNotNull(final Artifact... results) {
|
||||
assertThat(artifactRepository.findAll()).hasSize(results.length);
|
||||
for (final Artifact result : results) {
|
||||
assertThat(result.getId()).isNotNull();
|
||||
assertThat(operations.findOne(new Query()
|
||||
.addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
private void assertArtfiactNull(final Artifact... results) {
|
||||
for (final Artifact result : results) {
|
||||
assertThat(operations.findOne(new Query()
|
||||
.addCriteria(Criteria.where("filename").is(((LocalArtifact) result).getGridFsFileName()))))
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param findAll
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
private Collection iterable2Collection(final Iterable iterable) {
|
||||
final Collection<Object> col = new ArrayList<Object>();
|
||||
for (final Object o : iterable) {
|
||||
col.add(o);
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private void printDSTags() {
|
||||
System.out.println("==============================================================================");
|
||||
for (final DistributionSet d : distributionSetRepository.findAll()) {
|
||||
System.out.printf("%s\t[", d.getName());
|
||||
for (final DistributionSetTag t : d.getTags()) {
|
||||
System.out.printf("%s ", t.getName());
|
||||
}
|
||||
System.out.println("]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks that metadata for a software module can be created.")
|
||||
public void createSoftwareModuleMetadata() {
|
||||
|
||||
final String knownKey1 = "myKnownKey1";
|
||||
final String knownValue1 = "myKnownValue1";
|
||||
|
||||
final String knownKey2 = "myKnownKey2";
|
||||
final String knownValue2 = "myKnownValue2";
|
||||
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
|
||||
assertThat(ah.getOptLockRevision()).isEqualTo(1L);
|
||||
|
||||
final SoftwareModuleMetadata swMetadata1 = new SoftwareModuleMetadata(knownKey1, ah, knownValue1);
|
||||
|
||||
final SoftwareModuleMetadata swMetadata2 = new SoftwareModuleMetadata(knownKey2, ah, knownValue2);
|
||||
|
||||
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareManagement
|
||||
.createSoftwareModuleMetadata(Lists.newArrayList(swMetadata1, swMetadata2));
|
||||
|
||||
final SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId());
|
||||
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2L);
|
||||
|
||||
assertThat(softwareModuleMetadata).hasSize(2);
|
||||
assertThat(softwareModuleMetadata.get(0)).isNotNull();
|
||||
assertThat(softwareModuleMetadata.get(0).getValue()).isEqualTo(knownValue1);
|
||||
assertThat(softwareModuleMetadata.get(0).getId().getKey()).isEqualTo(knownKey1);
|
||||
assertThat(softwareModuleMetadata.get(0).getSoftwareModule().getId()).isEqualTo(ah.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(allSpPermissions = true)
|
||||
@Description("Checks that metadata for a software module can be updated.")
|
||||
public void updateSoftwareModuleMetadata() throws InterruptedException {
|
||||
final String knownKey = "myKnownKey";
|
||||
final String knownValue = "myKnownValue";
|
||||
final String knownUpdateValue = "myNewUpdatedValue";
|
||||
|
||||
// create a base software module
|
||||
final SoftwareModule ah = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
// initial opt lock revision must be 1
|
||||
assertThat(ah.getOptLockRevision()).isEqualTo(1L);
|
||||
|
||||
// create an software module meta data entry
|
||||
final List<SoftwareModuleMetadata> softwareModuleMetadata = softwareManagement.createSoftwareModuleMetadata(
|
||||
Collections.singleton(new SoftwareModuleMetadata(knownKey, ah, knownValue)));
|
||||
assertThat(softwareModuleMetadata).hasSize(1);
|
||||
// base software module should have now the opt lock revision one
|
||||
// because we are modifying the
|
||||
// base software module
|
||||
SoftwareModule changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId());
|
||||
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(2L);
|
||||
|
||||
// modifying the meta data value
|
||||
softwareModuleMetadata.get(0).setValue(knownUpdateValue);
|
||||
softwareModuleMetadata.get(0).setSoftwareModule(softwareManagement.findSoftwareModuleById(ah.getId()));
|
||||
softwareModuleMetadata.get(0).setKey(knownKey);
|
||||
|
||||
// update the software module metadata
|
||||
Thread.sleep(100);
|
||||
final SoftwareModuleMetadata updated = softwareManagement
|
||||
.updateSoftwareModuleMetadata(softwareModuleMetadata.get(0));
|
||||
// we are updating the sw meta data so also modiying the base software
|
||||
// module so opt lock
|
||||
// revision must be two
|
||||
changedLockRevisionModule = softwareManagement.findSoftwareModuleById(ah.getId());
|
||||
assertThat(changedLockRevisionModule.getOptLockRevision()).isEqualTo(3L);
|
||||
|
||||
// verify updated meta data contains the updated value
|
||||
assertThat(updated).isNotNull();
|
||||
assertThat(updated.getValue()).isEqualTo(knownUpdateValue);
|
||||
assertThat(updated.getId().getKey()).isEqualTo(knownKey);
|
||||
assertThat(updated.getSoftwareModule().getId()).isEqualTo(ah.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Queries and loads the metadata related to a given software module.")
|
||||
public void findAllSoftwareModuleMetadataBySwId() {
|
||||
|
||||
SoftwareModule sw1 = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
|
||||
|
||||
SoftwareModule sw2 = softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(osType, "os", "1.0.1", null, ""));
|
||||
|
||||
for (int index = 0; index < 10; index++) {
|
||||
sw1 = softwareManagement
|
||||
.createSoftwareModuleMetadata(new SoftwareModuleMetadata("key" + index, sw1, "value" + index))
|
||||
.getSoftwareModule();
|
||||
}
|
||||
|
||||
for (int index = 0; index < 20; index++) {
|
||||
sw2 = softwareManagement
|
||||
.createSoftwareModuleMetadata(new SoftwareModuleMetadata("key" + index, sw2, "value" + index))
|
||||
.getSoftwareModule();
|
||||
}
|
||||
|
||||
final Page<SoftwareModuleMetadata> metadataOfSw1 = softwareManagement
|
||||
.findSoftwareModuleMetadataBySoftwareModuleId(sw1.getId(), new PageRequest(0, 100));
|
||||
|
||||
final Page<SoftwareModuleMetadata> metadataOfSw2 = softwareManagement
|
||||
.findSoftwareModuleMetadataBySoftwareModuleId(sw2.getId(), new PageRequest(0, 100));
|
||||
|
||||
assertThat(metadataOfSw1.getNumberOfElements()).isEqualTo(10);
|
||||
assertThat(metadataOfSw1.getTotalElements()).isEqualTo(10);
|
||||
|
||||
assertThat(metadataOfSw2.getNumberOfElements()).isEqualTo(20);
|
||||
assertThat(metadataOfSw2.getTotalElements()).isEqualTo(20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.WithSpringAuthorityRule;
|
||||
import org.eclipse.hawkbit.repository.model.TenantConfiguration;
|
||||
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey;
|
||||
import org.junit.Test;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class SystemManagementTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that findTenants returns all tenants and not only restricted to the tenant which currently is logged in")
|
||||
public void findTenantsReturnsAllTenantsNotOnlyWhichLoggedIn() throws Exception {
|
||||
final String knownTenant1 = "knownTenant1";
|
||||
final String knownTenant2 = "knownTenant2";
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("bumlux", knownTenant1), new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
systemManagement.getTenantMetadata(knownTenant1);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("bumlux", knownTenant2), new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
systemManagement.getTenantMetadata(knownTenant2);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests that tenant specific configuration can be persisted and in case the tenant does not have specific configuration the default from environment is used instead.")
|
||||
public void storeTenantSpecificConfiguration() {
|
||||
final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
|
||||
final String envPropertyDefault = environment.getProperty(configKey.getDefaultKeyName());
|
||||
assertThat(envPropertyDefault).isNotNull();
|
||||
|
||||
// get the configuration from the system management
|
||||
final String defaultConfigValue = systemManagement.getConfigurationValue(configKey, String.class);
|
||||
assertThat(envPropertyDefault).isEqualTo(defaultConfigValue);
|
||||
|
||||
// update the tenant specific configuration
|
||||
final String newConfigurationValue = "thisIsAnotherValueForPolling";
|
||||
assertThat(newConfigurationValue).isNotEqualTo(defaultConfigValue);
|
||||
systemManagement
|
||||
.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), newConfigurationValue));
|
||||
|
||||
// verify that new configuration value is used
|
||||
final String updatedConfigurationValue = systemManagement.getConfigurationValue(configKey, String.class);
|
||||
assertThat(updatedConfigurationValue).isEqualTo(newConfigurationValue);
|
||||
assertThat(systemManagement.getTenantConfigurations()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests that the tenant specific configuration can be updated")
|
||||
public void updateTenantSpecifcConfiguration() {
|
||||
final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
|
||||
final String value1 = "firstValue";
|
||||
final String value2 = "secondValue";
|
||||
|
||||
// add value first
|
||||
systemManagement.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), value1));
|
||||
assertThat(systemManagement.getConfigurationValue(configKey, String.class)).isEqualTo(value1);
|
||||
|
||||
// update to value second
|
||||
systemManagement.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), value2));
|
||||
assertThat(systemManagement.getConfigurationValue(configKey, String.class)).isEqualTo(value2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests that the configuration value can be converted from String to Integer automatically")
|
||||
public void tenantConfigurationValueConversion() {
|
||||
final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
|
||||
final Integer value1 = 123;
|
||||
systemManagement
|
||||
.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), String.valueOf(value1)));
|
||||
assertThat(systemManagement.getConfigurationValue(configKey, Integer.class)).isEqualTo(value1);
|
||||
}
|
||||
|
||||
@Test(expected = ConversionFailedException.class)
|
||||
@Description("Tests that the get configuration throws exception in case the value cannot be automatically converted from String to Integer")
|
||||
public void wrongTenantConfigurationValueConversionThrowsException() {
|
||||
final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED;
|
||||
final String value1 = "thisIsNotANumber";
|
||||
// add value as String
|
||||
systemManagement
|
||||
.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), String.valueOf(value1)));
|
||||
// try to get it as Integer
|
||||
systemManagement.getConfigurationValue(configKey, Integer.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests that a deletion of a tenant specific configuration deletes it from the database.")
|
||||
public void deleteConfigurationReturnNullConfiguration() {
|
||||
final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY;
|
||||
|
||||
// gateway token does not have default value so no configuration value
|
||||
// is should be available
|
||||
final String defaultConfigValue = systemManagement.getConfigurationValue(configKey, String.class);
|
||||
assertThat(defaultConfigValue).isNull();
|
||||
|
||||
// update the tenant specific configuration
|
||||
final String newConfigurationValue = "thisIsAnotherValueForPolling";
|
||||
assertThat(newConfigurationValue).isNotEqualTo(defaultConfigValue);
|
||||
systemManagement
|
||||
.addOrUpdateConfiguration(new TenantConfiguration(configKey.getKeyName(), newConfigurationValue));
|
||||
|
||||
// verify that new configuration value is used
|
||||
final String updatedConfigurationValue = systemManagement.getConfigurationValue(configKey, String.class);
|
||||
assertThat(updatedConfigurationValue).isEqualTo(newConfigurationValue);
|
||||
|
||||
// delete the tenant specific configuration
|
||||
systemManagement.deleteConfiguration(configKey);
|
||||
// ensure that now gateway token is set again, because is deleted and
|
||||
// must be null now
|
||||
assertThat(systemManagement.getConfigurationValue(configKey, String.class)).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.Tag;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test class for {@link TagManagement}.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Tag Management")
|
||||
// TODO: fully document tests -> @Description for long text and reasonable
|
||||
// method name as short text
|
||||
public class TagManagementTest extends AbstractIntegrationTest {
|
||||
public TagManagementTest() {
|
||||
LOG = LoggerFactory.getLogger(TagManagementTest.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Full DS tag lifecycle tested. Create tags, assign them to sets and delete the tags.")
|
||||
public void createAndAssignAndDeleteDistributionSetTags() {
|
||||
final List<DistributionSet> dsAs = TestDataUtil.generateDistributionSets("DS-A", 20, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsBs = TestDataUtil.generateDistributionSets("DS-B", 10, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsCs = TestDataUtil.generateDistributionSets("DS-C", 25, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsABs = TestDataUtil.generateDistributionSets("DS-AB", 5, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsACs = TestDataUtil.generateDistributionSets("DS-AC", 11, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsBCs = TestDataUtil.generateDistributionSets("DS-BC", 13, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final List<DistributionSet> dsABCs = TestDataUtil.generateDistributionSets("DS-ABC", 9, softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final DistributionSetTag tagA = tagManagement.createDistributionSetTag(new DistributionSetTag("A"));
|
||||
final DistributionSetTag tagB = tagManagement.createDistributionSetTag(new DistributionSetTag("B"));
|
||||
final DistributionSetTag tagC = tagManagement.createDistributionSetTag(new DistributionSetTag("C"));
|
||||
final DistributionSetTag tagX = tagManagement.createDistributionSetTag(new DistributionSetTag("X"));
|
||||
final DistributionSetTag tagY = tagManagement.createDistributionSetTag(new DistributionSetTag("Y"));
|
||||
|
||||
distributionSetManagement.toggleTagAssignment(dsAs, tagA);
|
||||
distributionSetManagement.toggleTagAssignment(dsBs, tagB);
|
||||
distributionSetManagement.toggleTagAssignment(dsCs, tagC);
|
||||
|
||||
distributionSetManagement.toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagA.getName()));
|
||||
distributionSetManagement.toggleTagAssignment(dsABs, tagManagement.findDistributionSetTag(tagB.getName()));
|
||||
|
||||
distributionSetManagement.toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagA.getName()));
|
||||
distributionSetManagement.toggleTagAssignment(dsACs, tagManagement.findDistributionSetTag(tagC.getName()));
|
||||
|
||||
distributionSetManagement.toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagB.getName()));
|
||||
distributionSetManagement.toggleTagAssignment(dsBCs, tagManagement.findDistributionSetTag(tagC.getName()));
|
||||
|
||||
distributionSetManagement.toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagA.getName()));
|
||||
distributionSetManagement.toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagB.getName()));
|
||||
distributionSetManagement.toggleTagAssignment(dsABCs, tagManagement.findDistributionSetTag(tagC.getName()));
|
||||
|
||||
DistributionSetFilterBuilder distributionSetFilterBuilder;
|
||||
|
||||
// search for not deleted
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
|
||||
.setTagNames(Lists.newArrayList(tagA.getName()));
|
||||
assertEquals(
|
||||
dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
|
||||
+ dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
|
||||
distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build())
|
||||
.getTotalElements());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
|
||||
.setTagNames(Lists.newArrayList(tagB.getName()));
|
||||
assertEquals(
|
||||
dsBs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
|
||||
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
|
||||
distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build())
|
||||
.getTotalElements());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
|
||||
.setTagNames(Lists.newArrayList(tagC.getName()));
|
||||
assertEquals(
|
||||
dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown()
|
||||
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
|
||||
distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build())
|
||||
.getTotalElements());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true)
|
||||
.setTagNames(Lists.newArrayList(tagX.getName()));
|
||||
assertEquals(0, distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getTotalElements());
|
||||
|
||||
assertEquals(5, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown());
|
||||
|
||||
tagManagement.deleteDistributionSetTag(tagY.getName());
|
||||
assertEquals(4, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown());
|
||||
tagManagement.deleteDistributionSetTag(tagX.getName());
|
||||
assertEquals(3, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown());
|
||||
|
||||
tagManagement.deleteDistributionSetTag(tagB.getName());
|
||||
assertEquals(2, distributionSetTagRepository.findAll().spliterator().getExactSizeIfKnown());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setTagNames(Lists.newArrayList(tagA.getName()));
|
||||
assertEquals(
|
||||
dsAs.spliterator().getExactSizeIfKnown() + dsABs.spliterator().getExactSizeIfKnown()
|
||||
+ dsACs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
|
||||
distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build())
|
||||
.getTotalElements());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setTagNames(Lists.newArrayList(tagB.getName()));
|
||||
assertEquals(0, distributionSetManagement
|
||||
.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getTotalElements());
|
||||
|
||||
distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE)
|
||||
.setTagNames(Lists.newArrayList(tagC.getName()));
|
||||
assertEquals(
|
||||
dsCs.spliterator().getExactSizeIfKnown() + dsACs.spliterator().getExactSizeIfKnown()
|
||||
+ dsBCs.spliterator().getExactSizeIfKnown() + dsABCs.spliterator().getExactSizeIfKnown(),
|
||||
distributionSetManagement.findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build())
|
||||
.getTotalElements());
|
||||
}
|
||||
|
||||
private DistributionSetFilterBuilder getDistributionSetFilterBuilder() {
|
||||
return new DistributionSetFilterBuilder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#findTargetTag(java.lang.String)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testFindTargetTag() {
|
||||
assertThat(targetTagRepository.findAll()).isEmpty();
|
||||
|
||||
final List<TargetTag> tags = createTargetsWithTags();
|
||||
|
||||
assertThat(targetTagRepository.findAll()).isEqualTo(tagManagement.findAllTargetTags()).isEqualTo(tags)
|
||||
.hasSize(20);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#createTargetTag(org.eclipse.hawkbit.repository.model.TargetTag)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testCreateTargetTag() {
|
||||
assertThat(targetTagRepository.findAll()).isEmpty();
|
||||
|
||||
final Tag tag = tagManagement.createTargetTag(new TargetTag("kai1", "kai2", "colour"));
|
||||
|
||||
assertThat(targetTagRepository.findByNameEquals("kai1").getDescription()).isEqualTo("kai2");
|
||||
assertThat(tagManagement.findTargetTag("kai1").getColour()).isEqualTo("colour");
|
||||
assertThat(tagManagement.findTargetTagById(tag.getId()).getColour()).isEqualTo("colour");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#deleteTargetTag(java.lang.String[])}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testDeleteTargetTagsStringArray() {
|
||||
assertThat(targetTagRepository.findAll()).isEmpty();
|
||||
|
||||
// create test data
|
||||
final Iterable<TargetTag> tags = createTargetsWithTags();
|
||||
final TargetTag toDelete = tags.iterator().next();
|
||||
|
||||
for (final Target target : targetRepository.findAll()) {
|
||||
assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags())
|
||||
.contains(toDelete);
|
||||
}
|
||||
|
||||
// delete
|
||||
tagManagement.deleteTargetTag(toDelete.getName());
|
||||
|
||||
// check
|
||||
for (final Target target : targetRepository.findAll()) {
|
||||
assertThat(targetManagement.findTargetByControllerID(target.getControllerId()).getTags())
|
||||
.doesNotContain(toDelete);
|
||||
}
|
||||
assertThat(targetTagRepository.findOne(toDelete.getId())).isNull();
|
||||
assertThat(tagManagement.findAllTargetTags()).hasSize(19);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the creation of a target tag.")
|
||||
public void updateTargetTag() {
|
||||
assertThat(targetTagRepository.findAll()).isEmpty();
|
||||
|
||||
// create test data
|
||||
final List<TargetTag> tags = createTargetsWithTags();
|
||||
|
||||
// change data
|
||||
final TargetTag savedAssigned = tags.iterator().next();
|
||||
savedAssigned.setName("test123");
|
||||
|
||||
// persist
|
||||
tagManagement.updateTargetTag(savedAssigned);
|
||||
|
||||
// check data
|
||||
assertThat(tagManagement.findAllTargetTags()).hasSize(tags.size());
|
||||
assertThat(targetTagRepository.findOne(savedAssigned.getId()).getName()).isEqualTo("test123");
|
||||
assertThat(targetTagRepository.findOne(savedAssigned.getId()).getOptLockRevision()).isEqualTo(2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testCreateDistributionSetTag() {
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
|
||||
final Tag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("kai1", "kai2", "colour"));
|
||||
|
||||
assertThat(distributionSetTagRepository.findByNameEquals("kai1").getDescription()).isEqualTo("kai2");
|
||||
assertThat(tagManagement.findDistributionSetTag("kai1").getColour()).isEqualTo("colour");
|
||||
assertThat(tagManagement.findDistributionSetTagById(tag.getId()).getColour()).isEqualTo("colour");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#createDistributionSetTags(java.lang.Iterable)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testCreateDistributionSetTags() {
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
|
||||
final List<DistributionSetTag> tags = createDsSetsWithTags();
|
||||
|
||||
assertThat(distributionSetTagRepository.findAll()).hasSize(tags.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#deleteDistributionSetTag(java.lang.String[])}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testDeleteDistributionSetTag() {
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
|
||||
// create test data
|
||||
final Iterable<DistributionSetTag> tags = createDsSetsWithTags();
|
||||
final DistributionSetTag toDelete = tags.iterator().next();
|
||||
|
||||
for (final DistributionSet set : distributionSetRepository.findAll()) {
|
||||
assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags())
|
||||
.contains(toDelete);
|
||||
}
|
||||
|
||||
// delete
|
||||
tagManagement.deleteDistributionSetTag(tags.iterator().next().getName());
|
||||
|
||||
// check
|
||||
assertThat(distributionSetTagRepository.findOne(toDelete.getId())).isNull();
|
||||
assertThat(tagManagement.findDistributionSetTagsAll()).hasSize(19);
|
||||
for (final DistributionSet set : distributionSetRepository.findAll()) {
|
||||
assertThat(distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()).getTags())
|
||||
.doesNotContain(toDelete);
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = EntityAlreadyExistsException.class)
|
||||
public void testFailedDuplicateTargetTagNameException() {
|
||||
tagManagement.createTargetTag(new TargetTag("A"));
|
||||
tagManagement.createTargetTag(new TargetTag("A"));
|
||||
}
|
||||
|
||||
@Test(expected = EntityAlreadyExistsException.class)
|
||||
public void testFailedDuplicateDsTagNameException() {
|
||||
tagManagement.createDistributionSetTag(new DistributionSetTag("A"));
|
||||
tagManagement.createDistributionSetTag(new DistributionSetTag("A"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#updateDistributionSetTag(org.eclipse.hawkbit.repository.model.DistributionSetTag)}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testUpdateDistributionSetTag() {
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
|
||||
// create test data
|
||||
final List<DistributionSetTag> tags = createDsSetsWithTags();
|
||||
|
||||
// change data
|
||||
final DistributionSetTag savedAssigned = tags.iterator().next();
|
||||
savedAssigned.setName("test123");
|
||||
|
||||
// persist
|
||||
tagManagement.updateDistributionSetTag(savedAssigned);
|
||||
|
||||
// check data
|
||||
assertThat(tagManagement.findDistributionSetTagsAll()).hasSize(tags.size());
|
||||
assertThat(distributionSetTagRepository.findOne(savedAssigned.getId()).getName()).isEqualTo("test123");
|
||||
}
|
||||
|
||||
/**
|
||||
* Test method for
|
||||
* {@link org.eclipse.hawkbit.repository.TagManagement#findDistributionSetTagsAll()}
|
||||
* .
|
||||
*/
|
||||
@Test
|
||||
public void testFindDistributionSetTagsAll() {
|
||||
assertThat(distributionSetTagRepository.findAll()).isEmpty();
|
||||
|
||||
final List<DistributionSetTag> tags = createDsSetsWithTags();
|
||||
|
||||
// test
|
||||
assertThat(tagManagement.findDistributionSetTagsAll()).hasSize(tags.size());
|
||||
assertThat(distributionSetTagRepository.findAll()).hasSize(20);
|
||||
}
|
||||
|
||||
private List<TargetTag> createTargetsWithTags() {
|
||||
targetManagement.createTargets(TestDataUtil.generateTargets(20));
|
||||
final Iterable<TargetTag> tags = tagManagement.createTargetTags(TestDataUtil.generateTargetTags(20));
|
||||
|
||||
tags.forEach(tag -> targetManagement.toggleTagAssignment(targetRepository.findAll(), tag));
|
||||
|
||||
return tagManagement.findAllTargetTags();
|
||||
}
|
||||
|
||||
private List<DistributionSetTag> createDsSetsWithTags() {
|
||||
|
||||
final List<DistributionSet> sets = TestDataUtil.generateDistributionSets(20, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final Iterable<DistributionSetTag> tags = tagManagement
|
||||
.createDistributionSetTags(TestDataUtil.generateDistributionSetTags(20));
|
||||
|
||||
tags.forEach(tag -> distributionSetManagement.toggleTagAssignment(sets, tag));
|
||||
|
||||
return tagManagement.findDistributionSetTagsAll();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
|
||||
import org.eclipse.hawkbit.repository.model.TargetFilterQuery;
|
||||
import org.junit.Test;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test class for {@link TargetFilterQueryManagement}.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Target Filter Query Management")
|
||||
public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test creation of target filter query.")
|
||||
public void createTargetFilterQuery() {
|
||||
final String filterName = "new target filter";
|
||||
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
|
||||
.createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001"));
|
||||
assertEquals("Retrieved newly created custom target filter", targetFilterQuery,
|
||||
targetFilterQueryManagement.findTargetFilterQueryByName(filterName));
|
||||
}
|
||||
|
||||
@Test(expected = EntityAlreadyExistsException.class)
|
||||
@Description("Checks if the EntityAlreadyExistsException is thrown if a targetfilterquery with the same name are created more than once.")
|
||||
public void createDuplicateTargetFilterQuery() {
|
||||
final String filterName = "new target filter duplicate";
|
||||
targetFilterQueryManagement
|
||||
.createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001"));
|
||||
|
||||
targetFilterQueryManagement
|
||||
.createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test deletion of target filter query.")
|
||||
public void deleteTargetFilterQuery() {
|
||||
final String filterName = "delete_target_filter_query";
|
||||
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
|
||||
.createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001"));
|
||||
targetFilterQueryManagement.deleteTargetFilterQuery(targetFilterQuery.getId());
|
||||
assertEquals("Returns null as the target filter is deleted", null,
|
||||
targetFilterQueryManagement.findTargetFilterQueryById(targetFilterQuery.getId()));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test updation of target filter query.")
|
||||
public void updateTargetFilterQuery() {
|
||||
final String filterName = "target_filter_01";
|
||||
final TargetFilterQuery targetFilterQuery = targetFilterQueryManagement
|
||||
.createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001"));
|
||||
|
||||
final String newQuery = "status==UNKNOWN";
|
||||
targetFilterQuery.setQuery(newQuery);
|
||||
targetFilterQueryManagement.updateTargetFilterQuery(targetFilterQuery);
|
||||
assertEquals("Returns updated target filter query", newQuery, targetFilterQueryManagement
|
||||
.findTargetFilterQueryByName(filterName).getQuery());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.BaseEntity;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Slice;
|
||||
|
||||
import com.google.common.primitives.Ints;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Target Management Searches")
|
||||
public class TargetManagementSearchTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests different parameter combinations for target search operations. That includes both the test itself as a count operation with the same filters.")
|
||||
public void targetSearchWithVariousFilterCombinations() {
|
||||
final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("TargTag-A"));
|
||||
final TargetTag targTagB = tagManagement.createTargetTag(new TargetTag("TargTag-B"));
|
||||
final TargetTag targTagC = tagManagement.createTargetTag(new TargetTag("TargTag-C"));
|
||||
final TargetTag targTagD = tagManagement.createTargetTag(new TargetTag("TargTag-D"));
|
||||
|
||||
// TODO kzimmerm: test also installedDS (not only assignedDS)
|
||||
|
||||
final DistributionSet setA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final String targetDsAIdPref = "targ-A";
|
||||
List<Target> targAs = targetManagement.createTargets(
|
||||
TestDataUtil.buildTargetFixtures(100, targetDsAIdPref, targetDsAIdPref.concat(" description")));
|
||||
targAs = targetManagement.toggleTagAssignment(targAs, targTagA).getAssignedTargets();
|
||||
|
||||
final String targetDsBIdPref = "targ-B";
|
||||
List<Target> targBs = targetManagement.createTargets(
|
||||
TestDataUtil.buildTargetFixtures(100, targetDsBIdPref, targetDsBIdPref.concat(" description")));
|
||||
targBs = targetManagement.toggleTagAssignment(targBs, targTagB).getAssignedTargets();
|
||||
targBs = targetManagement.toggleTagAssignment(targBs, targTagD).getAssignedTargets();
|
||||
|
||||
final String targetDsCIdPref = "targ-C";
|
||||
List<Target> targCs = targetManagement.createTargets(
|
||||
TestDataUtil.buildTargetFixtures(100, targetDsCIdPref, targetDsCIdPref.concat(" description")));
|
||||
targCs = targetManagement.toggleTagAssignment(targCs, targTagC).getAssignedTargets();
|
||||
targCs = targetManagement.toggleTagAssignment(targCs, targTagD).getAssignedTargets();
|
||||
|
||||
final String targetDsDIdPref = "targ-D";
|
||||
final Iterable<Target> targDs = targetManagement.createTargets(
|
||||
TestDataUtil.buildTargetFixtures(100, targetDsDIdPref, targetDsDIdPref.concat(" description")));
|
||||
|
||||
deploymentManagement.assignDistributionSet(setA.getId(), targCs.iterator().next().getControllerId());
|
||||
deploymentManagement.assignDistributionSet(setA.getId(), targAs.iterator().next().getControllerId());
|
||||
deploymentManagement.assignDistributionSet(setA.getId(), targBs.iterator().next().getControllerId());
|
||||
|
||||
final List<TargetUpdateStatus> unknown = new ArrayList<TargetUpdateStatus>();
|
||||
unknown.add(TargetUpdateStatus.UNKNOWN);
|
||||
|
||||
final List<TargetUpdateStatus> pending = new ArrayList<TargetUpdateStatus>();
|
||||
pending.add(TargetUpdateStatus.PENDING);
|
||||
|
||||
final List<TargetUpdateStatus> both = new ArrayList<TargetUpdateStatus>();
|
||||
both.add(TargetUpdateStatus.UNKNOWN);
|
||||
both.add(TargetUpdateStatus.PENDING);
|
||||
|
||||
final PageRequest pageReq = new PageRequest(0, 500);
|
||||
// try to find several targets with different filter settings
|
||||
|
||||
// TODO kzimmerm: comment and check also the content itself, not only
|
||||
// the numbers
|
||||
// (containsOnly)
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(400);
|
||||
|
||||
assertThat(targetManagement.findTargetByFilters(pageReq, null, null, null, Boolean.FALSE, targTagD.getName())
|
||||
.getNumberOfElements()).isEqualTo(200).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
Slice<Target> x = targetManagement.findTargetByFilters(pageReq, null, "%targ-B%", null, Boolean.FALSE,
|
||||
targTagB.getName(), targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(100).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(null, "%targ-B%", null, Boolean.FALSE, targTagB.getName(), targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE,
|
||||
targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE,
|
||||
targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(null, "%targ-A%", setA.getId(), Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE,
|
||||
targTagA.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagA.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, null, null, setA.getId(), Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo(Ints
|
||||
.saturatedCast(targetManagement.countTargetByFilters(null, null, setA.getId(), Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(null, "%targ-A%", setA.getId(), Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(397).isEqualTo(
|
||||
Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, null, Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagB.getName(),
|
||||
targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(198).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(unknown, null, null, Boolean.FALSE, targTagB.getName(), targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, null, setA.getId(), Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(unknown, null, setA.getId(), Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, "%targ-A%", null, Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(99).isEqualTo(Ints
|
||||
.saturatedCast(targetManagement.countTargetByFilters(unknown, "%targ-A%", null, Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, "%targ-B%", null, Boolean.FALSE, targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(99).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(unknown, "%targ-B%", null, Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(198).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(unknown, null, null, Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo(
|
||||
Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, null, Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(pending, null, setA.getId(), Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, "%targ-A%", setA.getId(), Boolean.FALSE, null);
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(pending, "%targ-A%", setA.getId(), Boolean.FALSE, null)));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, "%targ-B%", setA.getId(), Boolean.FALSE,
|
||||
targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(targetManagement
|
||||
.countTargetByFilters(pending, "%targ-B%", setA.getId(), Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE,
|
||||
targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(2).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(pending, null, setA.getId(), Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
x = targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, targTagD.getName());
|
||||
assertThat(x.getNumberOfElements()).isEqualTo(2).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(pending, null, null, Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
// Both status: 2 pending and 198 unknown
|
||||
assertThat(targetManagement.findTargetByFilters(pageReq, both, null, null, Boolean.FALSE, targTagD.getName())
|
||||
.getNumberOfElements()).isEqualTo(200).isEqualTo(Ints.saturatedCast(
|
||||
targetManagement.countTargetByFilters(both, null, null, Boolean.FALSE, targTagD.getName())));
|
||||
|
||||
}
|
||||
|
||||
// TODO kzimmerm: add filter tests
|
||||
@Test
|
||||
@Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.")
|
||||
public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() {
|
||||
|
||||
final List<Target> notAssigned = targetManagement
|
||||
.createTargets(TestDataUtil.buildTargetFixtures(3, "not", "first description"));
|
||||
List<Target> targAssigned = targetManagement
|
||||
.createTargets(TestDataUtil.buildTargetFixtures(3, "assigned", "first description"));
|
||||
List<Target> targInstalled = targetManagement
|
||||
.createTargets(TestDataUtil.buildTargetFixtures(3, "installed", "first description"));
|
||||
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("a", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedTargets();
|
||||
targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedTargets();
|
||||
targInstalled = sendUpdateActionStatusToTargets(ds, targInstalled, Status.FINISHED, "installed");
|
||||
|
||||
final Slice<Target> result = targetManagement.findTargetsAllOrderByLinkedDistributionSet(pageReq, ds.getId(),
|
||||
null, null, null, Boolean.FALSE, null);
|
||||
|
||||
final Comparator<BaseEntity> byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId());
|
||||
|
||||
assertThat(result.getNumberOfElements()).isEqualTo(9);
|
||||
final List<Target> expected = new ArrayList<Target>();
|
||||
Collections.sort(targInstalled, byId);
|
||||
Collections.sort(targAssigned, byId);
|
||||
Collections.sort(notAssigned, byId);
|
||||
expected.addAll(targInstalled);
|
||||
expected.addAll(targAssigned);
|
||||
expected.addAll(notAssigned);
|
||||
|
||||
assertThat(result.getContent()).containsExactly(expected.toArray(new Target[0]));
|
||||
|
||||
}
|
||||
|
||||
private List<Target> sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable<Target> targs,
|
||||
final Status status, final String... msgs) {
|
||||
final List<Target> result = new ArrayList<Target>();
|
||||
for (final Target t : targs) {
|
||||
final List<Action> findByTarget = actionRepository.findByTarget(t);
|
||||
for (final Action action : findByTarget) {
|
||||
result.add(sendUpdateActionStatusToTarget(status, action, t, msgs));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t,
|
||||
final String... msgs) {
|
||||
updActA.setStatus(status);
|
||||
|
||||
final ActionStatus statusMessages = new ActionStatus();
|
||||
statusMessages.setAction(updActA);
|
||||
statusMessages.setOccurredAt(System.currentTimeMillis());
|
||||
statusMessages.setStatus(status);
|
||||
for (final String msg : msgs) {
|
||||
statusMessages.addMessage(msg);
|
||||
}
|
||||
controllerManagament.addUpdateActionStatus(statusMessages, updActA);
|
||||
return targetManagement.findTargetByControllerID(t.getControllerId());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.persistence.Query;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
|
||||
import org.eclipse.hawkbit.repository.exception.TenantNotExistException;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Tag;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetIdName;
|
||||
import org.eclipse.hawkbit.repository.model.TargetInfo;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Target Management")
|
||||
public class TargetManagementTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that targets cannot be created e.g. in plug'n play scenarios when tenant does not exists.")
|
||||
@WithUser(tenantId = "tenantWhichDoesNotExists", allSpPermissions = true, autoCreateTenant = false)
|
||||
public void createTargetForTenantWhichDoesNotExistThrowsTenantNotExistException() {
|
||||
try {
|
||||
targetManagement.createTarget(new Target("targetId123"));
|
||||
fail("tenant not exist");
|
||||
} catch (final TenantNotExistException e) {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that targets can deleted e.g. test all cascades")
|
||||
public void deleteAndCreateTargets() {
|
||||
Target target = targetManagement.createTarget(new Target("targetId123"));
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(1);
|
||||
targetManagement.deleteTargets(target.getId());
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(0);
|
||||
|
||||
target = createTargetWithAttributes("4711");
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(1);
|
||||
targetManagement.deleteTargets(target.getId());
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(0);
|
||||
|
||||
final List<Long> targets = new ArrayList<Long>();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
target = targetManagement.createTarget(new Target("" + i));
|
||||
targets.add(target.getId());
|
||||
targets.add(createTargetWithAttributes("" + (i * i + 1000)).getId());
|
||||
}
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(10);
|
||||
targetManagement.deleteTargets(targets.toArray(new Long[targets.size()]));
|
||||
assertThat(targetManagement.countTargetsAll()).isEqualTo(0);
|
||||
}
|
||||
|
||||
private Target createTargetWithAttributes(final String controllerId) {
|
||||
Target target = new Target(controllerId);
|
||||
final Map<String, String> testData = new HashMap<>();
|
||||
testData.put("test1", "testdata1");
|
||||
|
||||
target = targetManagement.createTarget(target);
|
||||
target = controllerManagament.updateControllerAttributes(controllerId, testData);
|
||||
|
||||
target = targetManagement.findTargetByControllerIDWithDetails(controllerId);
|
||||
assertThat(target.getTargetInfo().getControllerAttributes()).isEqualTo(testData);
|
||||
return target;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Finds a target by given ID and checks if all data is in the reponse (including the data defined as lazy).")
|
||||
public void findTargetByControllerIDWithDetails() {
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("test", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final DistributionSet set2 = TestDataUtil.generateDistributionSet("test2", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).isEqualTo(0);
|
||||
assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).isEqualTo(0);
|
||||
assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).isEqualTo(0);
|
||||
assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).isEqualTo(0);
|
||||
|
||||
Target target = createTargetWithAttributes("4711");
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
controllerManagament.updateLastTargetQuery("4711", null);
|
||||
|
||||
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(set.getId(), "4711");
|
||||
|
||||
final Action action = result.getActions().get(0);
|
||||
action.setStatus(Status.FINISHED);
|
||||
controllerManagament.addUpdateActionStatus(new ActionStatus(action, Status.FINISHED,
|
||||
System.currentTimeMillis(), "message"), action);
|
||||
deploymentManagement.assignDistributionSet(set2.getId(), "4711");
|
||||
|
||||
target = targetManagement.findTargetByControllerIDWithDetails("4711");
|
||||
// read data
|
||||
|
||||
assertThat(targetManagement.countTargetByAssignedDistributionSet(set.getId())).isEqualTo(0);
|
||||
assertThat(targetManagement.countTargetByInstalledDistributionSet(set.getId())).isEqualTo(1);
|
||||
assertThat(targetManagement.countTargetByAssignedDistributionSet(set2.getId())).isEqualTo(1);
|
||||
assertThat(targetManagement.countTargetByInstalledDistributionSet(set2.getId())).isEqualTo(0);
|
||||
assertThat(target.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(target.getAssignedDistributionSet()).isEqualTo(set2);
|
||||
assertThat(target.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(set.getId());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.")
|
||||
public void createMultipleTargetsDuplicate() {
|
||||
final List<Target> targets = TestDataUtil.buildTargetFixtures(5, "mySimpleTargs", "my simple targets");
|
||||
targetManagement.createTargets(targets);
|
||||
try {
|
||||
targetManagement.createTargets(targets);
|
||||
fail("Targets already exists");
|
||||
} catch (final EntityAlreadyExistsException e) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks if the EntityAlreadyExistsException is thrown if a single target with the same controller ID are created twice.")
|
||||
public void createTargetDuplicate() {
|
||||
targetManagement.createTarget(new Target("4711"));
|
||||
try {
|
||||
targetManagement.createTarget(new Target("4711"));
|
||||
fail("Target already exists");
|
||||
} catch (final EntityAlreadyExistsException e) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* verifies, that all {@link TargetTag} of parameter. NOTE: it's accepted
|
||||
* that the target have additional tags assigned to them which are not
|
||||
* contained within parameter tags.
|
||||
*
|
||||
* @param strict
|
||||
* if true, the given targets MUST contain EXACTLY ALL given
|
||||
* tags, AND NO OTHERS. If false, the given targets MUST contain
|
||||
* ALL given tags, BUT MAY CONTAIN FURTHER ONE
|
||||
* @param targets
|
||||
* targets to be verified
|
||||
* @param tags
|
||||
* are contained within tags of all targets.
|
||||
* @param tags
|
||||
* to be found in the tags of the targets
|
||||
*/
|
||||
private void checkTargetHasTags(final boolean strict, final Iterable<Target> targets, final TargetTag... tags) {
|
||||
_target: for (final Target tl : targets) {
|
||||
final Target t = targetManagement.findTargetByControllerID(tl.getControllerId());
|
||||
|
||||
for (final Tag tt : t.getTags()) {
|
||||
for (final Tag tag : tags) {
|
||||
if (tag.getName().equals(tt.getName())) {
|
||||
continue _target;
|
||||
}
|
||||
}
|
||||
if (strict) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
private void checkTargetHasNotTags(final Iterable<Target> targets, final TargetTag... tags) {
|
||||
for (final Target tl : targets) {
|
||||
final Target t = targetManagement.findTargetByControllerID(tl.getControllerId());
|
||||
|
||||
for (final Tag tag : tags) {
|
||||
for (final Tag tt : t.getTags()) {
|
||||
if (tag.getName().equals(tt.getName())) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(allSpPermissions = true)
|
||||
@Description("Creates and updates a target and verifies the changes in the repository.")
|
||||
public void singleTargetIsInsertedIntoRepo() throws Exception {
|
||||
|
||||
final String myCtrlID = "myCtrlID";
|
||||
final Target target = TestDataUtil.buildTargetFixture(myCtrlID, "the description!");
|
||||
|
||||
Target savedTarget = targetManagement.createTarget(target);
|
||||
assertNotNull(savedTarget);
|
||||
final Long createdAt = savedTarget.getCreatedAt();
|
||||
Long modifiedAt = savedTarget.getLastModifiedAt();
|
||||
assertEquals(createdAt, modifiedAt);
|
||||
assertNotNull(savedTarget.getCreatedAt());
|
||||
assertNotNull(savedTarget.getLastModifiedAt());
|
||||
assertEquals(target, savedTarget);
|
||||
|
||||
savedTarget.setDescription("changed description");
|
||||
Thread.sleep(1);
|
||||
savedTarget = targetManagement.updateTarget(savedTarget);
|
||||
|
||||
assertNotNull(savedTarget.getLastModifiedAt());
|
||||
assertNotEquals(createdAt, savedTarget.getLastModifiedAt());
|
||||
assertNotEquals(modifiedAt, savedTarget.getLastModifiedAt());
|
||||
modifiedAt = savedTarget.getLastModifiedAt();
|
||||
|
||||
final Target foundTarget = targetManagement.findTargetByControllerID(savedTarget.getControllerId());
|
||||
|
||||
assertNotNull(foundTarget);
|
||||
assertEquals(myCtrlID, foundTarget.getControllerId());
|
||||
assertEquals(savedTarget, foundTarget);
|
||||
assertEquals(createdAt, foundTarget.getCreatedAt());
|
||||
assertEquals(modifiedAt, foundTarget.getLastModifiedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(allSpPermissions = true)
|
||||
@Description("Create multiple tragets as bulk operation and delete them in bulk.")
|
||||
public void bulkTargetCreationAndDelete() throws Exception {
|
||||
final String myCtrlID = "myCtrlID";
|
||||
final List<Target> firstList = TestDataUtil.buildTargetFixtures(100, myCtrlID, "first description");
|
||||
|
||||
final Target extra = TestDataUtil.buildTargetFixture("myCtrlID-00081XX", "first description");
|
||||
|
||||
List<Target> firstSaved = targetManagement.createTargets(firstList);
|
||||
|
||||
final Target savedExtra = targetManagement.createTarget(extra);
|
||||
|
||||
Iterable<Target> allFound = targetRepository.findAll();
|
||||
assertEquals(firstList.size(), firstSaved.spliterator().getExactSizeIfKnown());
|
||||
assertEquals(firstList.size() + 1, allFound.spliterator().getExactSizeIfKnown());
|
||||
|
||||
// change the objects and save to again to trigger a change on
|
||||
// lastModifiedAt
|
||||
firstSaved.forEach(t -> t.setName(t.getName().concat("\tchanged")));
|
||||
firstSaved = targetManagement.updateTargets(firstSaved);
|
||||
|
||||
// verify that all entries are found
|
||||
_founds: for (final Target foundTarget : allFound) {
|
||||
for (final Target changedTarget : firstSaved) {
|
||||
if (changedTarget.getControllerId().equals(foundTarget.getControllerId())) {
|
||||
assertEquals(changedTarget.getDescription(), foundTarget.getDescription());
|
||||
assertTrue(changedTarget.getName().startsWith(foundTarget.getName()));
|
||||
assertTrue(changedTarget.getName().endsWith("changed"));
|
||||
assertEquals(changedTarget.getCreatedAt(), foundTarget.getCreatedAt());
|
||||
assertThat(changedTarget.getLastModifiedAt()).isNotEqualTo(changedTarget.getCreatedAt());
|
||||
|
||||
continue _founds;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundTarget.getControllerId().equals(savedExtra.getControllerId())) {
|
||||
fail();
|
||||
}
|
||||
}
|
||||
|
||||
targetManagement.deleteTargets(savedExtra.getId());
|
||||
|
||||
final int nr2Del = 50;
|
||||
int i = nr2Del;
|
||||
final Long[] deletedTargetIDs = new Long[nr2Del];
|
||||
final Target[] deletedTargets = new Target[nr2Del];
|
||||
|
||||
final Iterator<Target> it = firstSaved.iterator();
|
||||
while (nr2Del > 0 && it.hasNext() && i > 0) {
|
||||
final Target pt = it.next();
|
||||
deletedTargetIDs[i - 1] = pt.getId();
|
||||
deletedTargets[i - 1] = pt;
|
||||
i--;
|
||||
}
|
||||
|
||||
targetManagement.deleteTargets(deletedTargetIDs);
|
||||
|
||||
allFound = targetManagement.findTargetsAll(new PageRequest(0, 200)).getContent();
|
||||
assertEquals(firstSaved.spliterator().getExactSizeIfKnown() - nr2Del, allFound.spliterator()
|
||||
.getExactSizeIfKnown());
|
||||
|
||||
// verify that all undeleted are still found
|
||||
assertThat(allFound).doesNotContain(deletedTargets);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Stores target attributes and verfies existence in the repository.")
|
||||
public void savingTargetControllerAttributes() {
|
||||
Iterable<Target> ts = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(100, "myCtrlID",
|
||||
"first description"));
|
||||
|
||||
final Map<String, String> attribs = new HashMap<String, String>();
|
||||
attribs.put("a.b.c", "abc");
|
||||
attribs.put("x.y.z", "");
|
||||
attribs.put("1.2.3", "123");
|
||||
attribs.put("1.2.3.4", "1234");
|
||||
attribs.put("1.2.3.4.5", "12345");
|
||||
final Set<String> attribs2Del = new HashSet<String>();
|
||||
attribs2Del.add("x.y.z");
|
||||
attribs2Del.add("1.2.3");
|
||||
|
||||
for (final Target t : ts) {
|
||||
TargetInfo targetInfo = t.getTargetInfo();
|
||||
targetInfo.setNew(false);
|
||||
for (final Entry<String, String> attrib : attribs.entrySet()) {
|
||||
final String key = attrib.getKey();
|
||||
final String value = String.format("%s-%s", attrib.getValue(), t.getControllerId());
|
||||
targetInfo.getControllerAttributes().put(key, value);
|
||||
}
|
||||
targetInfo = targetInfoRepository.save(targetInfo);
|
||||
}
|
||||
final Query qry = entityManager.createNativeQuery("select * from sp_target_attributes ta");
|
||||
final List result = qry.getResultList();
|
||||
assertEquals(attribs.size() * ts.spliterator().getExactSizeIfKnown(), result.size());
|
||||
|
||||
for (final Target myT : ts) {
|
||||
final Target t = targetManagement.findTargetByControllerIDWithDetails(myT.getControllerId());
|
||||
assertEquals(attribs.size(), t.getTargetInfo().getControllerAttributes().size());
|
||||
for (final Entry<String, String> ca : t.getTargetInfo().getControllerAttributes().entrySet()) {
|
||||
assertTrue(attribs.containsKey(ca.getKey()));
|
||||
// has the same value: see string concatenation above
|
||||
assertEquals(String.format("%s-%s", attribs.get(ca.getKey()), t.getControllerId()), ca.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
ts = targetManagement.findTargetsAll(new PageRequest(0, 100)).getContent();
|
||||
final Iterator<Target> tsIt = ts.iterator();
|
||||
// all attributs of the target are deleted
|
||||
final Target[] ts2DelAllAttribs = new Target[] { tsIt.next(), tsIt.next(), tsIt.next() };
|
||||
// a few attributs are deleted
|
||||
final Target[] ts2DelAttribs = new Target[] { tsIt.next(), tsIt.next() };
|
||||
|
||||
// perform the deletion operations accordingly
|
||||
for (final Target ta : ts2DelAllAttribs) {
|
||||
final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId());
|
||||
|
||||
final TargetInfo targetStatus = t.getTargetInfo();
|
||||
targetStatus.getControllerAttributes().clear();
|
||||
targetInfoRepository.save(targetStatus);
|
||||
}
|
||||
|
||||
for (final Target ta : ts2DelAttribs) {
|
||||
final Target t = targetManagement.findTargetByControllerIDWithDetails(ta.getControllerId());
|
||||
|
||||
final TargetInfo targetStatus = t.getTargetInfo();
|
||||
for (final String attribKey : attribs2Del) {
|
||||
targetStatus.getControllerAttributes().remove(attribKey);
|
||||
}
|
||||
targetInfoRepository.save(targetStatus);
|
||||
}
|
||||
|
||||
// only the number of the remaining targets and controller attributes
|
||||
// are checked
|
||||
final Iterable<Target> restTS = targetRepository.findAll();
|
||||
|
||||
restTarget_: for (final Target targetl : restTS) {
|
||||
final Target target = targetManagement.findTargetByControllerIDWithDetails(targetl.getControllerId());
|
||||
|
||||
// verify that all members of the list ts2DelAllAttribs don't have
|
||||
// any attributes
|
||||
for (final Target tNoAttribl : ts2DelAllAttribs) {
|
||||
final Target tNoAttrib = targetManagement.findTargetByControllerID(tNoAttribl.getControllerId());
|
||||
|
||||
if (tNoAttrib.getControllerId().equals(target.getControllerId())) {
|
||||
assertThat(target.getTargetInfo().getControllerAttributes()).isEmpty();
|
||||
continue restTarget_;
|
||||
}
|
||||
}
|
||||
// verify that that the attribute list of all members of the list
|
||||
// ts2DelAttribs don't have
|
||||
// attributes which have been deleted
|
||||
for (final Target tNoAttribl : ts2DelAttribs) {
|
||||
final Target tNoAttrib = targetManagement.findTargetByControllerID(tNoAttribl.getControllerId());
|
||||
|
||||
if (tNoAttrib.getControllerId().equals(target.getControllerId())) {
|
||||
assertThat(target.getTargetInfo().getControllerAttributes().keySet().toArray()).doesNotContain(
|
||||
attribs2Del.toArray());
|
||||
continue restTarget_;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the assigment of tags to the a single target.")
|
||||
public void targetTagAssignment() {
|
||||
Target t1 = TestDataUtil.buildTargetFixture("id-1", "blablub");
|
||||
final int noT2Tags = 4;
|
||||
final int noT1Tags = 3;
|
||||
final List<TargetTag> t1Tags = tagManagement.createTargetTags(TestDataUtil.buildTargetTagFixtures(noT1Tags,
|
||||
"tag1"));
|
||||
t1.getTags().addAll(t1Tags);
|
||||
t1 = targetManagement.createTarget(t1);
|
||||
|
||||
Target t2 = TestDataUtil.buildTargetFixture("id-2", "blablub");
|
||||
final List<TargetTag> t2Tags = tagManagement.createTargetTags(TestDataUtil.buildTargetTagFixtures(noT2Tags,
|
||||
"tag2"));
|
||||
t2.getTags().addAll(t2Tags);
|
||||
t2 = targetManagement.createTarget(t2);
|
||||
|
||||
t1 = targetManagement.findTargetByControllerID(t1.getControllerId());
|
||||
assertThat(t1.getTags()).hasSize(noT1Tags).containsAll(t1Tags);
|
||||
assertThat(t1.getTags()).hasSize(noT1Tags).doesNotContain(Iterables.toArray(t2Tags, TargetTag.class));
|
||||
|
||||
t2 = targetManagement.findTargetByControllerID(t2.getControllerId());
|
||||
assertThat(t2.getTags()).hasSize(noT2Tags).containsAll(t2Tags);
|
||||
assertThat(t2.getTags()).hasSize(noT2Tags).doesNotContain(Iterables.toArray(t1Tags, TargetTag.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the assigment of tags to multiple targets.")
|
||||
public void targetTagBulkAssignments() {
|
||||
final List<Target> tagATargets = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(10,
|
||||
"tagATargets", "first description"));
|
||||
final List<Target> tagBTargets = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(10,
|
||||
"tagBTargets", "first description"));
|
||||
final List<Target> tagCTargets = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(10,
|
||||
"tagCTargets", "first description"));
|
||||
|
||||
final List<Target> tagABTargets = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(10,
|
||||
"tagABTargets", "first description"));
|
||||
|
||||
final List<Target> tagABCTargets = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(10,
|
||||
"tagABCTargets", "first description"));
|
||||
|
||||
final TargetTag tagA = tagManagement.createTargetTag(new TargetTag("A"));
|
||||
final TargetTag tagB = tagManagement.createTargetTag(new TargetTag("B"));
|
||||
final TargetTag tagC = tagManagement.createTargetTag(new TargetTag("C"));
|
||||
final TargetTag tagX = tagManagement.createTargetTag(new TargetTag("X"));
|
||||
|
||||
// doing different assignments
|
||||
targetManagement.toggleTagAssignment(tagATargets, tagA);
|
||||
targetManagement.toggleTagAssignment(tagBTargets, tagB);
|
||||
targetManagement.toggleTagAssignment(tagCTargets, tagC);
|
||||
|
||||
targetManagement.toggleTagAssignment(tagABTargets, tagA);
|
||||
targetManagement.toggleTagAssignment(tagABTargets, tagB);
|
||||
|
||||
targetManagement.toggleTagAssignment(tagABCTargets, tagA);
|
||||
targetManagement.toggleTagAssignment(tagABCTargets, tagB);
|
||||
targetManagement.toggleTagAssignment(tagABCTargets, tagC);
|
||||
|
||||
assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "X")).isEqualTo(0);
|
||||
|
||||
// search for targets with tag tagA
|
||||
final List<Target> targetWithTagA = new ArrayList<Target>();
|
||||
final List<Target> targetWithTagB = new ArrayList<Target>();
|
||||
final List<Target> targetWithTagC = new ArrayList<Target>();
|
||||
|
||||
// storing target lists to enable easy evaluation
|
||||
Iterables.addAll(targetWithTagA, tagATargets);
|
||||
Iterables.addAll(targetWithTagA, tagABTargets);
|
||||
Iterables.addAll(targetWithTagA, tagABCTargets);
|
||||
|
||||
Iterables.addAll(targetWithTagB, tagBTargets);
|
||||
Iterables.addAll(targetWithTagB, tagABTargets);
|
||||
Iterables.addAll(targetWithTagB, tagABCTargets);
|
||||
|
||||
Iterables.addAll(targetWithTagC, tagCTargets);
|
||||
Iterables.addAll(targetWithTagC, tagABCTargets);
|
||||
|
||||
// check the target lists as returned by assignTag
|
||||
checkTargetHasTags(false, targetWithTagA, tagA);
|
||||
checkTargetHasTags(false, targetWithTagB, tagB);
|
||||
checkTargetHasTags(false, targetWithTagC, tagC);
|
||||
|
||||
checkTargetHasNotTags(tagATargets, tagB, tagC);
|
||||
checkTargetHasNotTags(tagBTargets, tagA, tagC);
|
||||
checkTargetHasNotTags(tagCTargets, tagA, tagB);
|
||||
|
||||
// check again target lists refreshed from DB
|
||||
assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "A")).isEqualTo(
|
||||
targetWithTagA.size());
|
||||
assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "B")).isEqualTo(
|
||||
targetWithTagB.size());
|
||||
assertThat(targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, "C")).isEqualTo(
|
||||
targetWithTagC.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the unassigment of tags to multiple targets.")
|
||||
public void targetTagBulkUnassignments() {
|
||||
final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag"));
|
||||
final TargetTag targTagB = tagManagement.createTargetTag(new TargetTag("Targ-B-Tag"));
|
||||
final TargetTag targTagC = tagManagement.createTargetTag(new TargetTag("Targ-C-Tag"));
|
||||
|
||||
final List<Target> targAs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A",
|
||||
"first description"));
|
||||
final List<Target> targBs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(20, "target-id-B",
|
||||
"first description"));
|
||||
final List<Target> targCs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(15, "target-id-C",
|
||||
"first description"));
|
||||
|
||||
final List<Target> targABs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(12,
|
||||
"target-id-AB", "first description"));
|
||||
final List<Target> targACs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(13,
|
||||
"target-id-AC", "first description"));
|
||||
final List<Target> targBCs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(7, "target-id-BC",
|
||||
"first description"));
|
||||
final List<Target> targABCs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(17,
|
||||
"target-id-ABC", "first description"));
|
||||
|
||||
targetManagement.toggleTagAssignment(targAs, targTagA);
|
||||
targetManagement.toggleTagAssignment(targABs, targTagA);
|
||||
targetManagement.toggleTagAssignment(targACs, targTagA);
|
||||
targetManagement.toggleTagAssignment(targABCs, targTagA);
|
||||
|
||||
targetManagement.toggleTagAssignment(targBs, targTagB);
|
||||
targetManagement.toggleTagAssignment(targABs, targTagB);
|
||||
targetManagement.toggleTagAssignment(targBCs, targTagB);
|
||||
targetManagement.toggleTagAssignment(targABCs, targTagB);
|
||||
|
||||
targetManagement.toggleTagAssignment(targCs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targACs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targBCs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targABCs, targTagC);
|
||||
|
||||
checkTargetHasTags(true, targAs, targTagA);
|
||||
checkTargetHasTags(true, targBs, targTagB);
|
||||
checkTargetHasTags(true, targABs, targTagA, targTagB);
|
||||
checkTargetHasTags(true, targACs, targTagA, targTagC);
|
||||
checkTargetHasTags(true, targBCs, targTagB, targTagC);
|
||||
checkTargetHasTags(true, targABCs, targTagA, targTagB, targTagC);
|
||||
|
||||
targetManagement.toggleTagAssignment(targCs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targACs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targBCs, targTagC);
|
||||
targetManagement.toggleTagAssignment(targABCs, targTagC);
|
||||
|
||||
checkTargetHasTags(true, targAs, targTagA);
|
||||
checkTargetHasTags(true, targBs, targTagB);
|
||||
checkTargetHasTags(true, targABs, targTagA, targTagB);
|
||||
checkTargetHasTags(true, targBCs, targTagB);
|
||||
checkTargetHasTags(true, targACs, targTagA);
|
||||
|
||||
checkTargetHasNotTags(targCs, targTagC);
|
||||
checkTargetHasNotTags(targACs, targTagC);
|
||||
checkTargetHasNotTags(targBCs, targTagC);
|
||||
checkTargetHasNotTags(targABCs, targTagC);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Retrieves targets by ID with lazy loading of the tags. Checks the successfull load.")
|
||||
public void findTargetsByControllerIDsWithTags() {
|
||||
final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag"));
|
||||
|
||||
final List<Target> targAs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A",
|
||||
"first description"));
|
||||
|
||||
targetManagement.toggleTagAssignment(targAs, targTagA);
|
||||
|
||||
assertThat(
|
||||
targetManagement.findTargetsByControllerIDsWithTags(targAs.stream()
|
||||
.map(target -> target.getControllerId()).collect(Collectors.toList()))).hasSize(25);
|
||||
|
||||
// no lazy loading exception and tag correctly assigned
|
||||
assertThat(
|
||||
targetManagement
|
||||
.findTargetsByControllerIDsWithTags(
|
||||
targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))
|
||||
.stream().map(target -> target.getTags().contains(targTagA)).collect(Collectors.toList()))
|
||||
.containsOnly(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test the optimized quere for retrieving all ID/name pairs of targets.")
|
||||
public void findAllTargetIdNamePaiss() {
|
||||
final List<Target> targAs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A",
|
||||
"first description"));
|
||||
final String[] createdTargetIds = targAs.stream().map(t -> t.getControllerId())
|
||||
.toArray(size -> new String[size]);
|
||||
|
||||
final List<TargetIdName> findAllTargetIdNames = targetManagement.findAllTargetIds();
|
||||
final List<String> findAllTargetIds = findAllTargetIdNames.stream().map(TargetIdName::getControllerId)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
assertThat(findAllTargetIds).containsOnly(createdTargetIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test that NO TAG functionality which gives all targets with no tag assigned.")
|
||||
public void findTargetsWithNoTag() {
|
||||
|
||||
final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("Targ-A-Tag"));
|
||||
final List<Target> targAs = targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-A",
|
||||
"first description"));
|
||||
targetManagement.toggleTagAssignment(targAs, targTagA);
|
||||
|
||||
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(25, "target-id-B", "first description"));
|
||||
|
||||
final String[] tagNames = null;
|
||||
final List<Target> targetsListWithNoTag = targetManagement.findTargetByFilters(new PageRequest(0, 500), null,
|
||||
null, null, Boolean.TRUE, tagNames).getContent();
|
||||
|
||||
// Total targets
|
||||
assertEquals(50, targetManagement.findAllTargetIds().size());
|
||||
// Targets with no tag
|
||||
assertEquals(25, targetsListWithNoTag.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.repository.utils;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Calendar;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.Query;
|
||||
import javax.transaction.Transactional;
|
||||
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
|
||||
import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails;
|
||||
import org.eclipse.hawkbit.repository.ControllerManagement;
|
||||
import org.eclipse.hawkbit.repository.DeploymentManagement;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult;
|
||||
import org.eclipse.hawkbit.repository.DistributionSetManagement;
|
||||
import org.eclipse.hawkbit.repository.SoftwareManagement;
|
||||
import org.eclipse.hawkbit.repository.TagManagement;
|
||||
import org.eclipse.hawkbit.repository.TargetManagement;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.ActionStatus;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetTag;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.eclipse.hawkbit.util.IpUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.data.auditing.AuditingHandler;
|
||||
import org.springframework.data.auditing.DateTimeProvider;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.security.authentication.TestingAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.context.SecurityContextImpl;
|
||||
|
||||
import net._01001111.text.LoremIpsum;
|
||||
|
||||
/**
|
||||
* Generates test data for setting up the repository for test or demonstration
|
||||
* purpose.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public final class RepositoryDataGenerator {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RepositoryDataGenerator.class);
|
||||
|
||||
public static void initDemoRepo(final ConfigurableApplicationContext context) {
|
||||
final PersistentInitDemoDataBuilder initDemoDataBuilder = new PersistentInitDemoDataBuilder(context);
|
||||
initDemoDataBuilder.initDemoRepo(20, 0);
|
||||
}
|
||||
|
||||
public static void initLoadRepo(final ConfigurableApplicationContext context) {
|
||||
final PersistentInitDemoDataBuilder initDemoDataBuilder = new PersistentInitDemoDataBuilder(context);
|
||||
initDemoDataBuilder.initDemoRepo(200, 200);
|
||||
}
|
||||
|
||||
/**
|
||||
* builder which build initial demo data and stores it to the repos.
|
||||
*
|
||||
*/
|
||||
private static final class PersistentInitDemoDataBuilder {
|
||||
|
||||
private final SoftwareManagement softwareManagement;
|
||||
private final TargetManagement targetManagement;
|
||||
private final DeploymentManagement deploymentManagement;
|
||||
private final TagManagement tagManagement;
|
||||
private final ControllerManagement controllerManagement;
|
||||
private final DistributionSetManagement distributionSetManagement;
|
||||
|
||||
private final DatabaseCleanupUtil dbCleanupUtil;
|
||||
|
||||
private final AuditingHandler auditingHandler;
|
||||
|
||||
final LoremIpsum jlorem = new LoremIpsum();
|
||||
|
||||
PersistentInitDemoDataBuilder(final ConfigurableApplicationContext context) {
|
||||
softwareManagement = context.getBean(SoftwareManagement.class);
|
||||
targetManagement = context.getBean(TargetManagement.class);
|
||||
tagManagement = context.getBean(TagManagement.class);
|
||||
deploymentManagement = context.getBean(DeploymentManagement.class);
|
||||
controllerManagement = context.getBean(ControllerManagement.class);
|
||||
distributionSetManagement = context.getBean(DistributionSetManagement.class);
|
||||
|
||||
dbCleanupUtil = context.getBean(DatabaseCleanupUtil.class);
|
||||
|
||||
auditingHandler = context.getBean(AuditingHandler.class);
|
||||
}
|
||||
|
||||
private void runAsAllAuthorityContext(final Runnable runnable) {
|
||||
final SecurityContext oldContext = SecurityContextHolder.getContext();
|
||||
try {
|
||||
final SecurityContextImpl securityContextImpl = new SecurityContextImpl();
|
||||
final TestingAuthenticationToken authentication = new TestingAuthenticationToken("repogenator",
|
||||
"repogenator", SpPermission.CREATE_REPOSITORY, SpPermission.CREATE_TARGET,
|
||||
SpPermission.DELETE_REPOSITORY, SpPermission.DELETE_TARGET, SpPermission.READ_REPOSITORY,
|
||||
SpPermission.READ_TARGET, SpPermission.UPDATE_REPOSITORY, SpPermission.UPDATE_TARGET,
|
||||
SpringEvalExpressions.CONTROLLER_ROLE);
|
||||
securityContextImpl.setAuthentication(authentication);
|
||||
authentication.setDetails(new TenantAwareAuthenticationDetails("default", false));
|
||||
SecurityContextHolder.setContext(securityContextImpl);
|
||||
runnable.run();
|
||||
} finally {
|
||||
SecurityContextHolder.setContext(oldContext);
|
||||
}
|
||||
}
|
||||
|
||||
public void generateTestTagetGroup(final String group, final int sizeMultiplikator) {
|
||||
final DistributionSetTag dsTag = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("For " + group + "s"));
|
||||
|
||||
auditingHandler.setDateTimeProvider(new DateTimeProvider() {
|
||||
@Override
|
||||
public Calendar getNow() {
|
||||
final Calendar instance = Calendar.getInstance();
|
||||
instance.add(Calendar.MONTH, -new Random().nextInt(7));
|
||||
|
||||
return instance;
|
||||
}
|
||||
});
|
||||
|
||||
final List<Target> targets = createTargetTestGroup(group, 20 * sizeMultiplikator);
|
||||
|
||||
auditingHandler.setDateTimeProvider(new DateTimeProvider() {
|
||||
@Override
|
||||
public Calendar getNow() {
|
||||
final Calendar instance = Calendar.getInstance();
|
||||
return instance;
|
||||
}
|
||||
});
|
||||
|
||||
LOG.debug("initDemoRepo - start now real action history for group: {}", group);
|
||||
|
||||
// Old history of succesfully finished operations
|
||||
IntStream.range(0, 10).forEach(idx -> {
|
||||
final DistributionSet dsReal = TestDataUtil.generateDistributionSet(group + " Release", "v1." + idx,
|
||||
softwareManagement, distributionSetManagement,
|
||||
Arrays.asList(new DistributionSetTag[] { dsTag }));
|
||||
|
||||
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(dsReal,
|
||||
targets);
|
||||
|
||||
createSimpleActionStatusHistory(result.getActions());
|
||||
});
|
||||
|
||||
final List<List<Target>> targetGroups = splitIntoGroups(targets);
|
||||
|
||||
IntStream.range(0, targetGroups.size()).forEach(idx -> {
|
||||
final DistributionSet dsReal = TestDataUtil.generateDistributionSet(group + " Release", "v2." + idx,
|
||||
softwareManagement, distributionSetManagement,
|
||||
Arrays.asList(new DistributionSetTag[] { dsTag }));
|
||||
|
||||
final DistributionSetAssignmentResult result = deploymentManagement.assignDistributionSet(dsReal,
|
||||
targetGroups.get(idx));
|
||||
|
||||
createActionStatusHistory(result.getActions(), sizeMultiplikator);
|
||||
});
|
||||
|
||||
LOG.debug("initDemoRepo - real action history finished for group: {}", group);
|
||||
}
|
||||
|
||||
private List<List<Target>> splitIntoGroups(final List<Target> allTargets) {
|
||||
|
||||
final int elements = allTargets.size();
|
||||
|
||||
final int group1 = elements * (5 + new Random().nextInt(5)) / 100;
|
||||
final int group2 = elements * (15 + new Random().nextInt(5)) / 100;
|
||||
|
||||
final List<List<Target>> result = new ArrayList<List<Target>>();
|
||||
|
||||
result.add(allTargets.subList(0, group1));
|
||||
result.add(allTargets.subList(group1, group2));
|
||||
result.add(allTargets.subList(group2, elements));
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
private void createActionStatusHistory(final List<Action> actions, final int sizeMultiplikator) {
|
||||
final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
int index = 0;
|
||||
for (final Action actionGiven : actions) {
|
||||
// retrieved
|
||||
Action action = controllerManagement.registerRetrieved(actionGiven,
|
||||
"Controller retrieved update action and should start now the download.");
|
||||
|
||||
// download
|
||||
final ActionStatus download = new ActionStatus();
|
||||
download.setAction(action);
|
||||
download.setStatus(Status.DOWNLOAD);
|
||||
download.addMessage("Controller started download.");
|
||||
action = controllerManagement.addUpdateActionStatus(download, action);
|
||||
|
||||
// warning
|
||||
final ActionStatus warning = new ActionStatus();
|
||||
warning.setAction(action);
|
||||
warning.setStatus(Status.WARNING);
|
||||
warning.addMessage("Some warning: " + jlorem.words(new Random().nextInt(50)));
|
||||
action = controllerManagement.addUpdateActionStatus(warning, action);
|
||||
|
||||
// garbage
|
||||
for (int i = 0; i < new Random().nextInt(10); i++) {
|
||||
final ActionStatus running = new ActionStatus();
|
||||
running.setAction(action);
|
||||
running.setStatus(Status.RUNNING);
|
||||
running.addMessage("Still running: " + jlorem.words(new Random().nextInt(50)));
|
||||
action = controllerManagement.addUpdateActionStatus(running, action);
|
||||
for (int g = 0; g < new Random().nextInt(5); g++) {
|
||||
final ActionStatus rand = new ActionStatus();
|
||||
rand.setAction(action);
|
||||
rand.setStatus(Status.RUNNING);
|
||||
rand.addMessage(jlorem.words(new Random().nextInt(50)));
|
||||
action = controllerManagement.addUpdateActionStatus(rand, action);
|
||||
}
|
||||
}
|
||||
|
||||
// close
|
||||
final ActionStatus close = new ActionStatus();
|
||||
close.setAction(action);
|
||||
|
||||
// with error
|
||||
final int incrementAndGet = counter.incrementAndGet();
|
||||
if (incrementAndGet % 5 == 0) {
|
||||
close.setStatus(Status.ERROR);
|
||||
close.addMessage("Controller reported CLOSED with ERROR!");
|
||||
action = controllerManagement.addUpdateActionStatus(close, action);
|
||||
}
|
||||
// with OK
|
||||
else {
|
||||
close.setStatus(Status.FINISHED);
|
||||
close.addMessage("Controller reported CLOSED with OK!");
|
||||
action = controllerManagement.addUpdateActionStatus(close, action);
|
||||
}
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
private void createSimpleActionStatusHistory(final List<Action> actions) {
|
||||
for (final Action actionGiven : actions) {
|
||||
// retrieved
|
||||
Action action = controllerManagement.registerRetrieved(actionGiven,
|
||||
"Controller retrieved update action and should start now the download.");
|
||||
|
||||
// close
|
||||
final ActionStatus close = new ActionStatus();
|
||||
close.setAction(action);
|
||||
close.setStatus(Status.FINISHED);
|
||||
close.addMessage("Controller reported CLOSED with OK!");
|
||||
action = controllerManagement.addUpdateActionStatus(close, action);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private List<Target> createTargetTestGroup(final String group, final int targets) {
|
||||
LOG.debug("createTargetTestGroup: create group {}", group);
|
||||
|
||||
final TargetTag targTag = tagManagement.createTargetTag(new TargetTag(group));
|
||||
|
||||
final List<Target> targAs = targetManagement.createTargets(buildTargets(targets, group),
|
||||
TargetUpdateStatus.REGISTERED, System.currentTimeMillis() - new Random().nextInt(50_000_000),
|
||||
generateIPAddress());
|
||||
LOG.debug("createTargetTestGroup: {} created", group);
|
||||
|
||||
LOG.debug("createTargetTestGroup: {} targets status updated including IP", group);
|
||||
|
||||
return targetManagement.toggleTagAssignment(targAs, targTag).getAssignedTargets();
|
||||
}
|
||||
|
||||
private List<Target> buildTargets(final int noOfTgts, final String descriptionPrefix) {
|
||||
|
||||
final List<Target> result = new ArrayList<Target>(noOfTgts);
|
||||
|
||||
for (int i = 0; i < noOfTgts; i++) {
|
||||
final Target target = new Target(UUID.randomUUID().toString());
|
||||
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
builder.append(descriptionPrefix);
|
||||
builder.append(jlorem.words(5));
|
||||
|
||||
target.setDescription(builder.toString());
|
||||
target.getTargetInfo().getControllerAttributes().put("revision", "1.1");
|
||||
target.getTargetInfo().getControllerAttributes().put("capacity", "128M");
|
||||
target.getTargetInfo().getControllerAttributes().put("serial",
|
||||
String.valueOf(System.currentTimeMillis()));
|
||||
|
||||
result.add(target);
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* method writes initial test/demo data to the repositories.
|
||||
*
|
||||
* @param sizeMultiplikator
|
||||
* the entire scenario
|
||||
* @param loadtestgroups
|
||||
* packages of 1_000 targets
|
||||
*/
|
||||
private void initDemoRepo(final int sizeMultiplikator, final int loadtestgroups) {
|
||||
final LoremIpsum jlorem = new LoremIpsum();
|
||||
|
||||
runAsAllAuthorityContext(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
dbCleanupUtil.cleanupDB(null);
|
||||
|
||||
// generate targets and assign DS
|
||||
// 5 groups - 100 targets each -> 500
|
||||
final String[] targetTestGroups = { "SHC", "CCU", "Vehicle", "Vending machine", "ECU" };
|
||||
|
||||
final String[] modulesTypes = { "HeadUnit_FW", "EDC17_FW", "OSGi_Bundle" };
|
||||
|
||||
final DistributionSetTag depTag = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("deprecated"));
|
||||
|
||||
Arrays.stream(targetTestGroups).forEach(group -> {
|
||||
generateTestTagetGroup(group, sizeMultiplikator);
|
||||
});
|
||||
|
||||
// garbage DS
|
||||
LOG.debug("initDemoRepo - start now DS garbage");
|
||||
TestDataUtil.generateDistributionSets("Generic Software Package", sizeMultiplikator,
|
||||
softwareManagement, distributionSetManagement);
|
||||
LOG.debug("initDemoRepo - DS garbage finished");
|
||||
|
||||
LOG.debug("initDemoRepo - start now Extra Software Modules and types");
|
||||
Arrays.stream(modulesTypes).forEach(typeName -> {
|
||||
final SoftwareModuleType smtype = softwareManagement.createSoftwareModuleType(
|
||||
new SoftwareModuleType(typeName.toLowerCase().replaceAll("\\s+", ""), typeName,
|
||||
jlorem.words(5), Integer.MAX_VALUE));
|
||||
|
||||
for (int i = 0; i < sizeMultiplikator; i++) {
|
||||
softwareManagement.createSoftwareModule(new SoftwareModule(smtype, typeName + i, "1.0." + i,
|
||||
jlorem.words(5), "the " + typeName + " vendor Inc."));
|
||||
}
|
||||
|
||||
});
|
||||
LOG.debug("initDemoRepo - Extra Software Modules and types finished");
|
||||
|
||||
LOG.debug("initDemoRepo - start now target garbage");
|
||||
|
||||
// garbage targets
|
||||
// unknown
|
||||
targetManagement
|
||||
.createTargets(TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator));
|
||||
|
||||
// registered
|
||||
targetManagement.createTargets(
|
||||
TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "registered"),
|
||||
TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), generateIPAddress());
|
||||
|
||||
// pending
|
||||
final DistributionSetTag dsTag = tagManagement
|
||||
.createDistributionSetTag(new DistributionSetTag("OnlyAssignedTag"));
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("Pending DS", "v1.0",
|
||||
softwareManagement, distributionSetManagement,
|
||||
Arrays.asList(new DistributionSetTag[] { dsTag }));
|
||||
deploymentManagement.assignDistributionSet(ds, targetManagement.createTargets(
|
||||
TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "pending")));
|
||||
|
||||
// Load test means additional 1_000_000 target
|
||||
|
||||
for (int i = 0; i < loadtestgroups; i++) {
|
||||
targetManagement.createTargets(TestDataUtil.generateTargets(i * 1_000, 1_000, "loadtest-"));
|
||||
}
|
||||
|
||||
LOG.debug("initDemoRepo complete");
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Adding controller attributes for given {@link Target}.
|
||||
*/
|
||||
// private Target setControllerAttributes( final String targetId ) {
|
||||
// final Target target =
|
||||
// targetManagement.findTargetByControllerIDWithDetails( targetId );
|
||||
// target.getTargetStatus().getControllerAttributes().put( "revision",
|
||||
// "1.1" );
|
||||
// target.getTargetStatus().getControllerAttributes().put( "capacity",
|
||||
// "128M" );
|
||||
// target.getTargetStatus().getControllerAttributes().put( "serial",
|
||||
// String.valueOf(
|
||||
// System.currentTimeMillis()) );
|
||||
// return targetManagement.updateTarget( target );
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Data clean up class.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public static class DatabaseCleanupUtil {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DatabaseCleanupUtil.class);
|
||||
@Autowired
|
||||
private EntityManager entityManager;
|
||||
|
||||
private static final String[] CLEAN_UP_SQLS = new String[] { "sp_tenant", "sp_tenant_configuration",
|
||||
"sp_artifact", "sp_external_artifact", "sp_external_provider", "sp_target_target_tag",
|
||||
"sp_target_attributes", "sp_target_tag", "sp_action_status_messages", "sp_action_status", "sp_action",
|
||||
"sp_ds_dstag", "sp_distributionset_tag", "sp_target_info", "sp_target", "sp_sw_metadata",
|
||||
"sp_ds_metadata", "sp_ds_module", "sp_distribution_set", "sp_base_software_module",
|
||||
"sp_ds_type_element", "sp_distribution_set_type", "sp_software_module_type" };
|
||||
|
||||
/**
|
||||
* delete all entries from the DB tables.
|
||||
*/
|
||||
@Transactional
|
||||
@Modifying
|
||||
public void cleanupDB(final String database) {
|
||||
LOG.debug("Data clean up is started...");
|
||||
final boolean isMySql = "MYSQL".equals(database);
|
||||
if (isMySql) {
|
||||
// disable foreign key check because otherwise mysql cannot
|
||||
// delete sp_active_actions due
|
||||
// the self constraint within the table, stupid MySql
|
||||
entityManager.createNativeQuery("SET FOREIGN_KEY_CHECKS = 0").executeUpdate();
|
||||
}
|
||||
try {
|
||||
final String[] dbCmds = new String[] { "delete from" };
|
||||
for (final String dbCmd : dbCmds) {
|
||||
for (final String table : CLEAN_UP_SQLS) {
|
||||
final String sql = String.format("%s %s", dbCmd, table);
|
||||
final Query query = entityManager.createNativeQuery(sql);
|
||||
try {
|
||||
LOG.debug("cleanup table: {}", sql);
|
||||
LOG.debug("cleaned table: {}; deleted {} records", sql, query.executeUpdate());
|
||||
} catch (final Exception ex) {
|
||||
LOG.error(String.format("error on executing cleanup statement '%s'", sql), ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LOG.debug("Data clean up is finished...");
|
||||
} finally {
|
||||
if (isMySql) {
|
||||
// enable foreign key check again!
|
||||
entityManager.createNativeQuery("SET FOREIGN_KEY_CHECKS = 1").executeUpdate();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return a generated IPv4 address string.
|
||||
*/
|
||||
private static URI generateIPAddress() {
|
||||
final Random r = new Random();
|
||||
return IpUtil
|
||||
.createHttpUri(r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256));
|
||||
}
|
||||
|
||||
private RepositoryDataGenerator() {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
*
|
||||
* All rights reserved. This program and the accompanying materials
|
||||
* are made available under the terms of the Eclipse Public License v1.0
|
||||
* which accompanies this distribution, and is available at
|
||||
* http://www.eclipse.org/legal/epl-v10.html
|
||||
*/
|
||||
package org.eclipse.hawkbit.tenancy;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.WithSpringAuthorityRule;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSetType;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Slice;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Multi-Tenancy tests which testing the CRUD operations of entities that all
|
||||
* CRUD-Operations are tenant aware and cannot access or delete entities not
|
||||
* belonging to the current tenant.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Repository")
|
||||
@Stories("Multi Tenancy")
|
||||
public class MultiTenancyEntityTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description(value = "Ensures that multiple targets with same controller-ID can be created for different tenants.")
|
||||
public void createMultipleTargetsWithSameIdForDifferentTenant() throws Exception {
|
||||
// known controller ID for overall tenants same
|
||||
final String knownControllerId = "controllerId";
|
||||
|
||||
// known tenant names
|
||||
final String tenant = "aTenant";
|
||||
final String anotherTenant = "anotherTenant";
|
||||
// create targets
|
||||
createTargetForTenant(knownControllerId, tenant);
|
||||
createTargetForTenant(knownControllerId, anotherTenant);
|
||||
|
||||
// ensure both tenants see their target
|
||||
final Slice<Target> findTargetsForTenant = findTargetsForTenant(tenant);
|
||||
assertThat(findTargetsForTenant).hasSize(1);
|
||||
assertThat(findTargetsForTenant.getContent().get(0).getTenant().toUpperCase()).isEqualTo(tenant.toUpperCase());
|
||||
final Slice<Target> findTargetsForAnotherTenant = findTargetsForTenant(anotherTenant);
|
||||
assertThat(findTargetsForAnotherTenant).hasSize(1);
|
||||
assertThat(findTargetsForAnotherTenant.getContent().get(0).getTenant().toUpperCase())
|
||||
.isEqualTo(anotherTenant.toUpperCase());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description(value = "Ensures that targtes created by a tenant are not visible by another tenant.")
|
||||
@WithUser(tenantId = "mytenant", allSpPermissions = true)
|
||||
public void queryTargetFromDifferentTenantIsNotVisible() throws Exception {
|
||||
// create target for another tenant
|
||||
final String anotherTenant = "anotherTenant";
|
||||
final String controllerAnotherTenant = "anotherController";
|
||||
createTargetForTenant(controllerAnotherTenant, anotherTenant);
|
||||
|
||||
// find all targets for current tenant "mytenant"
|
||||
final Slice<Target> findTargetsAll = targetManagement.findTargetsAll(pageReq);
|
||||
// no target has been created for "mytenant"
|
||||
assertThat(findTargetsAll).hasSize(0);
|
||||
|
||||
// find all targets for anotherTenant
|
||||
final Slice<Target> findTargetsForTenant = findTargetsForTenant(anotherTenant);
|
||||
// another tenant should have targets
|
||||
assertThat(findTargetsForTenant).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description(value = "Ensures that tenant metadata is retrieved for the current tenant.")
|
||||
@WithUser(tenantId = "mytenant", autoCreateTenant = false, allSpPermissions = true)
|
||||
public void getTenanatMetdata() throws Exception {
|
||||
|
||||
// logged in tenant mytenant - check if tenant default data is
|
||||
// autogenerated
|
||||
assertThat(distributionSetManagement.findDistributionSetTypesAll(pageReq)).isEmpty();
|
||||
assertThat(systemManagement.getTenantMetadata().getTenant().toUpperCase()).isEqualTo("mytenant".toUpperCase());
|
||||
assertThat(distributionSetManagement.findDistributionSetTypesAll(pageReq)).isNotEmpty();
|
||||
|
||||
// check that the cache is not getting in the way, i.e. "bumlux" results
|
||||
// in bumlux and not
|
||||
// mytenant
|
||||
assertThat(
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", "bumlux"), new Callable<String>() {
|
||||
@Override
|
||||
public String call() throws Exception {
|
||||
return systemManagement.getTenantMetadata().getTenant().toUpperCase();
|
||||
}
|
||||
})).isEqualTo("bumlux".toUpperCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description(value = "Ensures that targets created from a different tenant cannot be deleted from other tenants")
|
||||
@WithUser(tenantId = "mytenant", allSpPermissions = true)
|
||||
public void deleteTargetFromOtherTenantIsNotPossible() throws Exception {
|
||||
// create target for another tenant
|
||||
final String anotherTenant = "anotherTenant";
|
||||
final String controllerAnotherTenant = "anotherController";
|
||||
final Target createTargetForTenant = createTargetForTenant(controllerAnotherTenant, anotherTenant);
|
||||
|
||||
// ensure target cannot be deleted by 'mytenant'
|
||||
targetManagement.deleteTargets(createTargetForTenant.getId());
|
||||
Slice<Target> targetsForAnotherTenant = findTargetsForTenant(anotherTenant);
|
||||
assertThat(targetsForAnotherTenant).hasSize(1);
|
||||
|
||||
// ensure another tenant can delete the target
|
||||
deleteTargetsForTenant(anotherTenant, createTargetForTenant.getId());
|
||||
targetsForAnotherTenant = findTargetsForTenant(anotherTenant);
|
||||
assertThat(targetsForAnotherTenant).hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description(value = "Ensures that multiple distribution sets with same name and version can be created for different tenants.")
|
||||
public void createMultipleDistributionSetsWithSameNameForDifferentTenants() throws Exception {
|
||||
|
||||
// known ds name for overall tenants same
|
||||
final String knownDistributionSetName = "dsName";
|
||||
final String knownDistributionSetVersion = "0.0.0";
|
||||
|
||||
// known tenant names
|
||||
final String tenant = "aTenant";
|
||||
final String anotherTenant = "anotherTenant";
|
||||
// create distribution sets
|
||||
createDistributionSetForTenant(knownDistributionSetName, knownDistributionSetVersion, tenant);
|
||||
createDistributionSetForTenant(knownDistributionSetName, knownDistributionSetVersion, anotherTenant);
|
||||
|
||||
// ensure both tenants see their distribution sets
|
||||
final Page<DistributionSet> findDistributionSetsForTenant = findDistributionSetForTenant(tenant);
|
||||
assertThat(findDistributionSetsForTenant).hasSize(1);
|
||||
assertThat(findDistributionSetsForTenant.getContent().get(0).getTenant().toUpperCase())
|
||||
.isEqualTo(tenant.toUpperCase());
|
||||
final Page<DistributionSet> findDistributionSetsForAnotherTenant = findDistributionSetForTenant(anotherTenant);
|
||||
assertThat(findDistributionSetsForAnotherTenant).hasSize(1);
|
||||
assertThat(findDistributionSetsForAnotherTenant.getContent().get(0).getTenant().toUpperCase())
|
||||
.isEqualTo(anotherTenant.toUpperCase());
|
||||
|
||||
}
|
||||
|
||||
private Target createTargetForTenant(final String controllerId, final String tenant) throws Exception {
|
||||
return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), new Callable<Target>() {
|
||||
@Override
|
||||
public Target call() throws Exception {
|
||||
return targetManagement.createTarget(new Target(controllerId));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Slice<Target> findTargetsForTenant(final String tenant) throws Exception {
|
||||
return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant),
|
||||
new Callable<Slice<Target>>() {
|
||||
@Override
|
||||
public Slice<Target> call() throws Exception {
|
||||
return targetManagement.findTargetsAll(pageReq);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void deleteTargetsForTenant(final String tenant, final Long... targetIds) throws Exception {
|
||||
securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant), new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
targetManagement.deleteTargets(targetIds);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private DistributionSet createDistributionSetForTenant(final String name, final String version, final String tenant)
|
||||
throws Exception {
|
||||
return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant),
|
||||
new Callable<DistributionSet>() {
|
||||
@Override
|
||||
public DistributionSet call() throws Exception {
|
||||
final DistributionSet ds = new DistributionSet();
|
||||
ds.setName(name);
|
||||
ds.setTenant(tenant);
|
||||
ds.setVersion(version);
|
||||
ds.setType(distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("typetest", "test", "foobar")));
|
||||
return distributionSetManagement.createDistributionSet(ds);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Page<DistributionSet> findDistributionSetForTenant(final String tenant) throws Exception {
|
||||
return securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("user", tenant),
|
||||
new Callable<Page<DistributionSet>>() {
|
||||
@Override
|
||||
public Page<DistributionSet> call() throws Exception {
|
||||
return distributionSetManagement.findDistributionSetsAll(pageReq, false, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
38
hawkbit-repository/src/test/resources/application-test.properties
Executable file
38
hawkbit-repository/src/test/resources/application-test.properties
Executable file
@@ -0,0 +1,38 @@
|
||||
#
|
||||
# Copyright (c) 2015 Bosch Software Innovations GmbH and others.
|
||||
#
|
||||
# All rights reserved. This program and the accompanying materials
|
||||
# are made available under the terms of the Eclipse Public License v1.0
|
||||
# which accompanies this distribution, and is available at
|
||||
# http://www.eclipse.org/legal/epl-v10.html
|
||||
#
|
||||
|
||||
spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value}
|
||||
spring.data.mongodb.port=28017
|
||||
|
||||
hawkbit.server.controller.security.authentication.header.enabled=true
|
||||
|
||||
hawkbit.server.artifact.repo.upload.maxFileSize=5MB
|
||||
|
||||
hawkbit.server.security.dos.maxStatusEntriesPerAction=100
|
||||
|
||||
hawkbit.server.security.dos.maxAttributeEntriesPerTarget=10
|
||||
|
||||
spring.jpa.database=H2
|
||||
flyway.enabled=true
|
||||
flyway.initOnMigrate=true
|
||||
flyway.sqlMigrationSuffix=${spring.jpa.database}.sql
|
||||
|
||||
spring.datasource.url=jdbc:h2:mem:sp-db;DB_CLOSE_ON_EXIT=FALSE
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=sa
|
||||
|
||||
# SP Controller configuration
|
||||
hawkbit.controller.pollingTime=00:01:00
|
||||
hawkbit.controller.pollingOverdueTime=00:01:00
|
||||
|
||||
## Configuration for RabbitMQ integration
|
||||
hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter
|
||||
hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter
|
||||
hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver
|
||||
Reference in New Issue
Block a user