Initial check in accordance with Parallel IP
This commit is contained in:
@@ -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;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
import org.springframework.test.web.servlet.ResultHandler;
|
||||
import org.springframework.test.web.servlet.result.PrintingResultHandler;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
public abstract class MockMvcResultPrinter {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(MockMvcResultPrinter.class);
|
||||
|
||||
private MockMvcResultPrinter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Print {@link MvcResult} details to the "standard" output stream.
|
||||
*/
|
||||
public static ResultHandler print() {
|
||||
return new ConsolePrintingResultHandler();
|
||||
}
|
||||
|
||||
/**
|
||||
* An {@link PrintingResultHandler} that writes to the "standard" output
|
||||
* stream
|
||||
*/
|
||||
private static class ConsolePrintingResultHandler extends PrintingResultHandler {
|
||||
|
||||
public ConsolePrintingResultHandler() {
|
||||
super(new ResultValuePrinter() {
|
||||
|
||||
@Override
|
||||
public void printHeading(final String heading) {
|
||||
LOG.debug(String.format("%20s:", heading));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void printValue(final String label, Object value) {
|
||||
if (value != null && value.getClass().isArray()) {
|
||||
value = CollectionUtils.arrayToList(value);
|
||||
}
|
||||
LOG.debug(String.format("%20s = %s", label, value));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
/**
|
||||
* 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.controller;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.Status;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.eventbus.EventBus;
|
||||
import com.google.common.eventbus.Subscribe;
|
||||
import com.google.common.net.HttpHeaders;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test artifact downloads from the controller.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Features("Component Tests - Controller RESTful API")
|
||||
@Stories("Artifact Download Resource")
|
||||
public class ArtifactDownloadTest extends AbstractIntegrationTestWithMongoDB {
|
||||
|
||||
private static final String AUTH_ANOYM = "ROLE_CONTROLLER_ANONYMOUS";
|
||||
|
||||
public ArtifactDownloadTest() {
|
||||
LOG = LoggerFactory.getLogger(ArtifactDownloadTest.class);
|
||||
}
|
||||
|
||||
private int downLoadProgress = 0;
|
||||
|
||||
@Autowired
|
||||
private EventBus eventBus;
|
||||
|
||||
@Test
|
||||
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
|
||||
public void invalidRequestsOnArtifactResource() throws Exception {
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList<>();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
// no artifact available
|
||||
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455",
|
||||
target.getControllerId(), ds.findFirstModuleByType(osType).getId())).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/123455.MD5SUM",
|
||||
target.getControllerId(), ds.findFirstModuleByType(osType).getId())).andExpect(status().isNotFound());
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/1234567890/artifacts/{filename}",
|
||||
target.getControllerId(), artifact.getFilename())).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/1234567890/artifacts/{filename}.MD5SUM",
|
||||
target.getControllerId(), artifact.getFilename())).andExpect(status().isNotFound());
|
||||
|
||||
// test now consistent data to test allowed methods
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename()).header(HttpHeaders.IF_MATCH, artifact.getSha1Hash()))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isOk());
|
||||
|
||||
// test failed If-match
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename()).header("If-Match", "fsjkhgjfdhg")).andExpect(status().isPreconditionFailed());
|
||||
|
||||
// test invalid range
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename()).header("Range", "bytes=1-10,hdsfjksdh"))
|
||||
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
|
||||
.andExpect(status().isRequestedRangeNotSatisfiable());
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename()).header("Range", "bytes=100-10"))
|
||||
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
|
||||
.andExpect(status().isRequestedRangeNotSatisfiable());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/{targetid}/softwaremodules/{smId}/artifacts/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(), ds.findFirstModuleByType(osType).getId(),
|
||||
artifact.getFilename())).andExpect(status().isMethodNotAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
|
||||
@Description("Tests non allowed requests on the artifact ressource, e.g. invalid URI, wrong if-match, wrong command.")
|
||||
public void invalidRequestsOnArtifactResourceByName() throws Exception {
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList<>();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
|
||||
// Binary
|
||||
// no artifact available
|
||||
mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1")).andExpect(status().isNotFound());
|
||||
|
||||
// no artifact available
|
||||
mvc.perform(get("/controller/artifacts/v1/filename/{filename}.MD5SUM", "file1"))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// test now consistent data to test allowed methods
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")
|
||||
.header(HttpHeaders.IF_MATCH, artifact.getSha1Hash()))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}.MD5SUM", tenantAware.getCurrentTenant(),
|
||||
"file1")).andExpect(status().isOk());
|
||||
|
||||
// test failed If-match
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")
|
||||
.header("If-Match", "fsjkhgjfdhg"))
|
||||
.andExpect(status().isPreconditionFailed());
|
||||
|
||||
// test invalid range
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")
|
||||
.header("Range", "bytes=1-10,hdsfjksdh"))
|
||||
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
|
||||
.andExpect(status().isRequestedRangeNotSatisfiable());
|
||||
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1")
|
||||
.header("Range", "bytes=100-10"))
|
||||
.andExpect(header().string("Content-Range", "bytes */" + 5 * 1024))
|
||||
.andExpect(status().isRequestedRangeNotSatisfiable());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(
|
||||
put("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1"))
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1")).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(
|
||||
post("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(), "file1"))
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/{tenant}/controller/artifacts/v1/filename/{filename}.MD5SUM", tenantAware.getCurrentTenant(),
|
||||
"file1")).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/artifacts/v1/filename/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), "file1")).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/artifacts/v1/filename/{filename}.MD5SUM", tenantAware.getCurrentTenant(),
|
||||
"file1")).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
|
||||
@Description("Tests valid downloads through the artifact resource by identifying the artifact not by ID but file name.")
|
||||
public void downloadArtifactThroughFileName() throws Exception {
|
||||
downLoadProgress = 1;
|
||||
eventBus.register(this);
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList<Target>();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
// download fails as artifact is not yet assigned
|
||||
mvc.perform(get("/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
|
||||
target.getControllerId(), ds.findFirstModuleByType(osType).getId(), artifact.getFilename()))
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// now assign and download successful
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
final MvcResult result = mvc
|
||||
.perform(
|
||||
get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(),
|
||||
ds.findFirstModuleByType(osType).getId(), artifact.getFilename()))
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=" + artifact.getFilename()))
|
||||
.andReturn();
|
||||
|
||||
assertTrue(Arrays.equals(result.getResponse().getContentAsByteArray(), random));
|
||||
|
||||
// download complete
|
||||
assertThat(downLoadProgress).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests valid MD5SUm file downloads through the artifact resource by identifying the artifact by ID.")
|
||||
public void downloadMd5sumThroughControllerApi() throws Exception {
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
// download
|
||||
final MvcResult result = mvc
|
||||
.perform(
|
||||
get("/{tenant}/controller/v1/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{filename}.MD5SUM",
|
||||
tenantAware.getCurrentTenant(), target.getControllerId(),
|
||||
ds.findFirstModuleByType(osType).getId(), artifact.getFilename()))
|
||||
.andExpect(status().isOk()).andExpect(header().string("Content-Disposition",
|
||||
"attachment;filename=" + artifact.getFilename() + ".MD5SUM"))
|
||||
.andReturn();
|
||||
|
||||
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(
|
||||
new String(artifact.getMd5Hash() + " " + artifact.getFilename()).getBytes(Charsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(authorities = "ROLE_CONTROLLER_ANONYMOUS", allSpPermissions = true)
|
||||
@Description("Ensures that even an authenticated controller is not permitted to download if "
|
||||
+ "anonymous as authorization is notpossible, e.g. chekc if the controller has the artifact assigned.")
|
||||
public void downloadArtifactByNameFailsIfNotAuthenticated() throws Exception {
|
||||
downLoadProgress = 1;
|
||||
eventBus.register(this);
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false);
|
||||
|
||||
// download fails as artifact is not yet assigned to target
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
|
||||
@Description("Ensures that an authenticated and named controller is permitted to download.")
|
||||
public void downloadArtifactByNameByNamedController() throws Exception {
|
||||
downLoadProgress = 1;
|
||||
eventBus.register(this);
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024 * 1024);
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
// download fails as artifact is not yet assigned to target
|
||||
mvc.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1.tar.bz2")).andExpect(status().isNotFound());
|
||||
|
||||
// now assign and download successful
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
final MvcResult result = mvc
|
||||
.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1"))
|
||||
.andExpect(status().isOk()).andExpect(header().string("ETag", artifact.getSha1Hash()))
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn();
|
||||
|
||||
assertTrue(Arrays.equals(result.getResponse().getContentAsByteArray(), random));
|
||||
|
||||
// one (update) action
|
||||
assertThat(actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent()).hasSize(1);
|
||||
final Action action = actionRepository.findByTargetAndDistributionSet(pageReq, target, ds).getContent().get(0);
|
||||
|
||||
// one status - download
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(2);
|
||||
assertThat(actionStatusRepository.findByAction(pageReq, action).getContent()).hasSize(2);
|
||||
assertThat(actionStatusRepository.findByAction(new PageRequest(0, 400, Direction.DESC, "id"), action)
|
||||
.getContent().get(0).getStatus()).isEqualTo(Status.DOWNLOAD);
|
||||
|
||||
// download complete
|
||||
assertThat(downLoadProgress).isEqualTo(10);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "4712", authorities = "ROLE_CONTROLLER", allSpPermissions = true)
|
||||
@Description("Test various HTTP range requests for artifact download, e.g. chunk download or download resume.")
|
||||
public void rangeDownloadArtifactByName() throws Exception {
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList<>();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final int resultLength = 5 * 1000 * 1024;
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(resultLength);
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1", false);
|
||||
|
||||
assertThat(random.length).isEqualTo(resultLength);
|
||||
|
||||
// now assign and download successful
|
||||
deploymentManagement.assignDistributionSet(ds, targets);
|
||||
|
||||
final int range = 100 * 1024;
|
||||
|
||||
// full file download with standard range request
|
||||
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
for (int i = 0; i < resultLength / range; i++) {
|
||||
final String rangeString = "" + i * range + "-" + ((i + 1) * range - 1);
|
||||
|
||||
final MvcResult result = mvc
|
||||
.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}",
|
||||
tenantAware.getCurrentTenant(), "file1").header("Range", "bytes=" + rangeString))
|
||||
.andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash()))
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().longValue("Content-Length", range))
|
||||
.andExpect(header().string("Content-Range", "bytes " + rangeString + "/" + resultLength))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn();
|
||||
|
||||
outputStream.write(result.getResponse().getContentAsByteArray());
|
||||
}
|
||||
|
||||
assertThat(outputStream.toByteArray()).isEqualTo(random);
|
||||
|
||||
// return last 1000 Bytes
|
||||
MvcResult result = mvc
|
||||
.perform(get("/${tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1").header("Range", "bytes=-1000"))
|
||||
.andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash()))
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().longValue("Content-Length", 1000))
|
||||
.andExpect(header().string("Content-Range",
|
||||
"bytes " + (resultLength - 1000) + "-" + (resultLength - 1) + "/" + resultLength))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn();
|
||||
|
||||
assertThat(result.getResponse().getContentAsByteArray())
|
||||
.isEqualTo(Arrays.copyOfRange(random, resultLength - 1000, resultLength));
|
||||
|
||||
// skip first 1000 Bytes and return the rest
|
||||
result = mvc
|
||||
.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1").header("Range", "bytes=1000-"))
|
||||
.andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash()))
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().longValue("Content-Length", resultLength - 1000))
|
||||
.andExpect(header().string("Content-Range",
|
||||
"bytes " + 1000 + "-" + (resultLength - 1) + "/" + resultLength))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn();
|
||||
|
||||
assertThat(result.getResponse().getContentAsByteArray())
|
||||
.isEqualTo(Arrays.copyOfRange(random, 1000, resultLength));
|
||||
|
||||
// multipart download - first 20 bytes in 2 parts
|
||||
result = mvc
|
||||
.perform(get("/{tenant}/controller/artifacts/v1/filename/{filename}", tenantAware.getCurrentTenant(),
|
||||
"file1").header("Range", "bytes=0-9,10-19"))
|
||||
.andExpect(status().isPartialContent()).andExpect(header().string("ETag", artifact.getSha1Hash()))
|
||||
.andExpect(content().contentType("multipart/byteranges; boundary=THIS_STRING_SEPARATES_MULTIPART"))
|
||||
.andExpect(header().string("Accept-Ranges", "bytes"))
|
||||
.andExpect(header().longValue("Last-Modified", artifact.getCreatedAt()))
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1")).andReturn();
|
||||
|
||||
outputStream.reset();
|
||||
|
||||
outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART\r\n".getBytes(StandardCharsets.ISO_8859_1));
|
||||
outputStream.write(("Content-Range: bytes 0-9/" + resultLength + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
|
||||
outputStream.write(Arrays.copyOfRange(random, 0, 10));
|
||||
outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART\r\n".getBytes(StandardCharsets.ISO_8859_1));
|
||||
outputStream
|
||||
.write(("Content-Range: bytes 10-19/" + resultLength + "\r\n").getBytes(StandardCharsets.ISO_8859_1));
|
||||
outputStream.write(Arrays.copyOfRange(random, 10, 20));
|
||||
outputStream.write("\r\n--THIS_STRING_SEPARATES_MULTIPART--".getBytes(StandardCharsets.ISO_8859_1));
|
||||
|
||||
assertThat(result.getResponse().getContentAsByteArray()).isEqualTo(outputStream.toByteArray());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the download fails if te controller is not authenticated.")
|
||||
public void faildDownloadArtifactByNameIfAuthenticationMissing() throws Exception {
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
final List<Target> targets = new ArrayList<>();
|
||||
targets.add(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false);
|
||||
|
||||
// download fails as artifact is not yet assigned to target
|
||||
mvc.perform(get("/controller/artifacts/v1/filename/{filename}", "file1.tar.bz2"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Downloads an MD5SUM file by the related artifacts filename.")
|
||||
public void downloadMd5sumFileByName() throws Exception {
|
||||
// create target
|
||||
Target target = new Target("4712");
|
||||
target = targetManagement.createTarget(target);
|
||||
|
||||
// create ds
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// create artifact
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final Artifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "file1.tar.bz2", false);
|
||||
|
||||
// download
|
||||
final MvcResult result = mvc
|
||||
.perform(get("/{tenant}/controller/artifacts/v1/filename/file1.tar.bz2.MD5SUM",
|
||||
tenantAware.getCurrentTenant()))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(header().string("Content-Disposition", "attachment;filename=file1.tar.bz2.MD5SUM"))
|
||||
.andReturn();
|
||||
|
||||
assertThat(result.getResponse().getContentAsByteArray())
|
||||
.isEqualTo(new String(artifact.getMd5Hash() + " file1.tar.bz2").getBytes(Charsets.US_ASCII));
|
||||
}
|
||||
|
||||
@Subscribe
|
||||
public void listen(final DownloadProgressEvent event) {
|
||||
downLoadProgress++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
/**
|
||||
* 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.controller;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
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.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.rest.resource.JsonBuilder;
|
||||
import org.junit.Test;
|
||||
import org.springframework.hateoas.MediaTypes;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Features("Component Tests - Controller RESTful API")
|
||||
@Stories("Cancel Action Resource")
|
||||
public class CancelActionTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test of the controller can continue a started update even after a cancel command if it so desires.")
|
||||
public void rootRsCancelActionButContinueAnyway() throws Exception {
|
||||
// prepare test data
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
|
||||
final Action updateAction = deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0);
|
||||
|
||||
final Action cancelAction = deploymentManagement.cancelAction(updateAction,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
|
||||
// controller rejects cancelation
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
|
||||
// get update action anyway
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId(),
|
||||
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(updateAction.getId()))))
|
||||
.andExpect(jsonPath("$deployment.download", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.update", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(osType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(appType).getVersion())));
|
||||
|
||||
// and finish it
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(
|
||||
JsonBuilder.deploymentActionFeedback(updateAction.getId().toString(), "closed", "success"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// check database after test
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet().getId())
|
||||
.isEqualTo(ds.getId());
|
||||
assertThat(targetManagement.findTargetByControllerIDWithDetails("4712").getTargetInfo()
|
||||
.getInstalledDistributionSet().getId()).isEqualTo(ds.getId());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getInstallationDate())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test for cancel operation of a update action.")
|
||||
public void rootRsCancelAction() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
|
||||
final Action updateAction = deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0);
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href",
|
||||
startsWith("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/deploymentBase/" + updateAction.getId())));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
// Retrieved is reported
|
||||
|
||||
List<Action> activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget);
|
||||
|
||||
assertThat(activeActionsByTarget).hasSize(1);
|
||||
assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.RUNNING);
|
||||
final Action cancelAction = deploymentManagement.cancelAction(updateAction,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
|
||||
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget);
|
||||
|
||||
// the canceled action should still be active!
|
||||
assertThat(cancelAction.isActive()).isTrue();
|
||||
assertThat(activeActionsByTarget).hasSize(1);
|
||||
assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.cancelAction.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/cancelAction/" + cancelAction.getId())));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction.getId()))))
|
||||
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
// controller confirmed cancelled action, should not be active anymore
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)
|
||||
.content(JsonBuilder.cancelActionFeedback(updateAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(savedTarget);
|
||||
assertThat(activeActionsByTarget).hasSize(0);
|
||||
final Action canceledAction = deploymentManagement.findAction(cancelAction.getId());
|
||||
assertThat(canceledAction.isActive()).isFalse();
|
||||
assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests various bad requests and if the server handles them as expected.")
|
||||
public void badCancelAction() throws Exception {
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
// non existing target
|
||||
mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
createCancelAction("34534543");
|
||||
|
||||
// wrong media type
|
||||
mvc.perform(get("/{tenant}/controller/v1/34534543/cancelAction/1", tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_ATOM_XML)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotAcceptable());
|
||||
|
||||
}
|
||||
|
||||
private Action createCancelAction(final String targetid) {
|
||||
final Target target = new Target(targetid);
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet(targetid, softwareManagement,
|
||||
distributionSetManagement);
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
final Action updateAction = deploymentManagement.assignDistributionSet(ds, toAssign).getActions().get(0);
|
||||
|
||||
return deploymentManagement.cancelAction(updateAction,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the feedback channel of the cancel operation.")
|
||||
public void rootRsCancelActionFeedback() throws Exception {
|
||||
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final Action updateAction = deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
|
||||
// cancel action manually
|
||||
final Action cancelAction = deploymentManagement.cancelAction(updateAction,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(2);
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(3);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "resumed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(4);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "scheduled"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(5);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
// cancelation canceled -> should remove the action from active
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "canceled"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(6);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
// cancelation rejected -> action still active until controller close it
|
||||
// with finished or
|
||||
// error
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "rejected"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(7);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
// cancelaction closed -> should remove the action from active
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(8);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the feeback chanel of for multiple open cancel operations on the same target.")
|
||||
public void multipleCancelActionFeedback() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds3 = TestDataUtil.generateDistributionSet("3", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final Action updateAction = deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
final Action updateAction2 = deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
final Action updateAction3 = deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(3);
|
||||
|
||||
// 3 update actions, 0 cancel actions
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3);
|
||||
final Action cancelAction = deploymentManagement.cancelAction(updateAction,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
final Action cancelAction2 = deploymentManagement.cancelAction(updateAction2,
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(3);
|
||||
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId(), tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction.getId()))))
|
||||
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction.getId()))));
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(6);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.cancelAction.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/cancelAction/" + cancelAction.getId())));
|
||||
|
||||
// now lets return feedback for the first cancelation
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(7);
|
||||
|
||||
// 1 update actions, 1 cancel actions
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId(),
|
||||
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction2.getId()))))
|
||||
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction2.getId()))));
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(8);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.cancelAction.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/cancelAction/" + cancelAction2.getId())));
|
||||
|
||||
// now lets return feedback for the second cancelation
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction2.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(9);
|
||||
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/" + updateAction3.getId(),
|
||||
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(10);
|
||||
|
||||
// 1 update actions, 0 cancel actions
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
final Action cancelAction3 = deploymentManagement.cancelAction(actionRepository.findOne(updateAction3.getId()),
|
||||
targetManagement.findTargetByControllerID(savedTarget.getControllerId()));
|
||||
|
||||
// action is in cancelling state
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId(),
|
||||
tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(cancelAction3.getId()))))
|
||||
.andExpect(jsonPath("$cancelAction.stopId", equalTo(String.valueOf(updateAction3.getId()))));
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(12);
|
||||
|
||||
// now lets return feedback for the third cancelation
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction3.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction3.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(13);
|
||||
|
||||
// final status
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(0);
|
||||
assertThat(deploymentManagement.findActionsByTarget(savedTarget)).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.")
|
||||
public void tooMuchCancelActionFeedback() throws Exception {
|
||||
final Target target = targetManagement.createTarget(new Target("4712"));
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(target);
|
||||
|
||||
final Action action = deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
|
||||
final Action cancelAction = deploymentManagement.cancelAction(action,
|
||||
targetManagement.findTargetByControllerID(target.getControllerId()));
|
||||
|
||||
final String feedback = JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "proceeding");
|
||||
// assignDistributionSet creates an ActionStatus and cancel action
|
||||
// stores an action status, so
|
||||
// only 97 action status left
|
||||
for (int i = 0; i < 98; i++) {
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("test the correct rejection of various invalid feedback requests")
|
||||
public void badCancelActionFeedback() throws Exception {
|
||||
final Action cancelAction = createCancelAction("4712");
|
||||
final Action cancelAction2 = createCancelAction("4715");
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
// bad content type
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_ATOM_XML).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// bad body
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "546456456"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// non existing target
|
||||
mvc.perform(post("/{tenant}/controller/v1/12345/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// invalid action
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("sdfsdfsdfs", "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(JsonBuilder.cancelActionFeedback("1234", "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// right action but for wrong target
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction2.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// finally get it right :)
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/cancelAction/" + cancelAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.cancelActionFeedback(cancelAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* 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.controller;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.rest.resource.JsonBuilder;
|
||||
import org.junit.Test;
|
||||
import org.springframework.hateoas.MediaTypes;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Features("Component Tests - Controller RESTful API")
|
||||
@Stories("Config Data Resource")
|
||||
public class ConfigDataTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "are requested only once from the device.")
|
||||
public void requestConfigDataIfEmpty() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.configData.href", equalTo(
|
||||
"http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/4712/configData")));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
savedTarget.getTargetInfo().getControllerAttributes().put("dsafsdf", "sdsds");
|
||||
|
||||
final Target updateControllerAttributes = controllerManagament.updateControllerAttributes(
|
||||
savedTarget.getControllerId(), savedTarget.getTargetInfo().getControllerAttributes());
|
||||
// request controller attributes need to be false because we don't want
|
||||
// to request the
|
||||
// controller attributes again
|
||||
assertThat(updateControllerAttributes.getTargetInfo().isRequestControllerAttributes()).isFalse();
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.configData.href").doesNotExist());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "can be uploaded correctly by the controller.")
|
||||
public void putConfigData() throws Exception {
|
||||
targetManagement.createTarget(new Target("4717"));
|
||||
|
||||
// initial
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("dsafsdf", "sdsds");
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(
|
||||
targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes())
|
||||
.isEqualTo(attributes);
|
||||
|
||||
// update
|
||||
attributes.put("sdsds", "123412");
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4717").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(
|
||||
targetManagement.findTargetByControllerIDWithDetails("4717").getTargetInfo().getControllerAttributes())
|
||||
.isEqualTo(attributes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "upload limitation is inplace which is meant to protect the server from malicious attempts.")
|
||||
public void putToMuchConfigData() throws Exception {
|
||||
targetManagement.createTarget(new Target("4717"));
|
||||
|
||||
// initial
|
||||
Map<String, String> attributes = new HashMap<>();
|
||||
for (int i = 0; i < 10; i++) {
|
||||
attributes.put("dsafsdf" + i, "sdsds" + i);
|
||||
}
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
attributes = new HashMap<>();
|
||||
attributes.put("on too many", "sdsds");
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "resource behaves as exptected in cae of invalid request attempts.")
|
||||
public void badConfigData() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).//
|
||||
andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
// bad content type
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("dsafsdf", "sdsds");
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaTypes.HAL_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// non existing target
|
||||
mvc.perform(put("/{tenant}/controller/v1/456456/configData", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData("", attributes, "closed")).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// bad body
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/configData", tenantAware.getCurrentTenant())
|
||||
.content("{\"id\": \"51659181\"}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,984 @@
|
||||
/**
|
||||
* 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.controller;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.RandomUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.Action.ActionType;
|
||||
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.LocalArtifact;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.eclipse.hawkbit.rest.resource.JsonBuilder;
|
||||
import org.fest.assertions.core.Condition;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.hateoas.MediaTypes;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Features("Component Tests - Controller RESTful API")
|
||||
@Stories("Deployment Action Resource")
|
||||
public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB {
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that artifact not found, when softare module not exists ")
|
||||
public void testArtifactsNotFound() throws Exception {
|
||||
final Target target = TestDataUtil.createTarget(targetManagement);
|
||||
final Long softwareModuleIdNotExist = 1l;
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
|
||||
tenantAware.getCurrentTenant(), target.getName(), softwareModuleIdNotExist))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that artifact are found, when softare module exists ")
|
||||
public void testArtifactsExists() throws Exception {
|
||||
final Target target = TestDataUtil.createTarget(targetManagement);
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
deploymentManagement.assignDistributionSet(distributionSet.getId(), new String[] { target.getName() });
|
||||
|
||||
final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId();
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
|
||||
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0)));
|
||||
|
||||
TestDataUtil.generateArtifacts(artifactManagement, softwareModuleId);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/{softwareModuleId}/artifacts",
|
||||
tenantAware.getCurrentTenant(), target.getName(), softwareModuleId)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(3)))
|
||||
.andExpect(jsonPath("$[?(@.filename==filename0)]", hasSize(1)))
|
||||
.andExpect(jsonPath("$[?(@.filename==filename1)]", hasSize(1)))
|
||||
.andExpect(jsonPath("$[?(@.filename==filename2)]", hasSize(1)));
|
||||
|
||||
}
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that software modules are found, when assigned distribution set exists with modules and atrifacts")
|
||||
public void testAvailableSoftwareModulesWithArtifacts() throws Exception {
|
||||
final Target target = TestDataUtil.createTarget(targetManagement);
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
deploymentManagement.assignDistributionSet(distributionSet.getId(), new String[] { target.getName() });
|
||||
final Long softwareModuleId = distributionSet.getModules().stream().findFirst().get().getId();
|
||||
TestDataUtil.generateArtifacts(artifactManagement, softwareModuleId);
|
||||
|
||||
final int modulesSize = distributionSet.getModules().size();
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetExist}/softwaremodules/", tenantAware.getCurrentTenant(),
|
||||
target.getName())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(modulesSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Forced deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.")
|
||||
public void deplomentForceAction() throws Exception {
|
||||
// Prepare test data
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1", false);
|
||||
final LocalArtifact artifactSignature = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1.signature", false);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
|
||||
assertThat(actionRepository.findAll()).isEmpty();
|
||||
assertThat(actionStatusRepository.findAll()).isEmpty();
|
||||
|
||||
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED,
|
||||
Action.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(actionRepository.findAll()).hasSize(1);
|
||||
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
assertThat(actionRepository.findAll()).hasSize(2);
|
||||
|
||||
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
|
||||
// Run test
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href", startsWith("http://localhost/"
|
||||
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(2);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
Thread.sleep(1);
|
||||
|
||||
final DistributionSet findDistributionSetByAction = distributionSetManagement
|
||||
.findDistributionSetByAction(action);
|
||||
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(action.getId()))))
|
||||
.andExpect(jsonPath("$deployment.download", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.update", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(osType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(osType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].filename", equalTo("test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.md5",
|
||||
equalTo(artifact.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1",
|
||||
equalTo(artifact.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].filename",
|
||||
equalTo("test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.md5",
|
||||
equalTo(artifactSignature.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1",
|
||||
equalTo(artifactSignature.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(appType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(appType).getName())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
// Retrieved is reported
|
||||
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
|
||||
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
|
||||
assertThat(actionStatusMessages).hasSize(3);
|
||||
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
|
||||
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Attempt/soft deployment to a controller. Checks if the resource reponse payload for a given deployment is as expected.")
|
||||
public void deplomentAttemptAction() throws Exception {
|
||||
// Prepare test data
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1", false);
|
||||
final LocalArtifact artifactSignature = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1.signature", false);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
|
||||
assertThat(actionRepository.findAll()).isEmpty();
|
||||
assertThat(actionStatusRepository.findAll()).isEmpty();
|
||||
|
||||
List<Target> saved = deploymentManagement
|
||||
.assignDistributionSet(ds.getId(), ActionType.SOFT, Action.NO_FORCE_TIME, savedTarget.getControllerId())
|
||||
.getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(actionRepository.findAll()).hasSize(1);
|
||||
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
assertThat(actionRepository.findAll()).hasSize(2);
|
||||
|
||||
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
|
||||
// Run test
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href", startsWith("http://localhost/"
|
||||
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(2);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
Thread.sleep(1);
|
||||
|
||||
final DistributionSet findDistributionSetByAction = distributionSetManagement
|
||||
.findDistributionSetByAction(action);
|
||||
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/deploymentBase/" + uaction.getId(), tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(action.getId()))))
|
||||
.andExpect(jsonPath("$deployment.download", equalTo("attempt")))
|
||||
.andExpect(jsonPath("$deployment.update", equalTo("attempt")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(osType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(osType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].filename", equalTo("test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.md5",
|
||||
equalTo(artifact.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1",
|
||||
equalTo(artifact.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].filename",
|
||||
equalTo("test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.md5",
|
||||
equalTo(artifactSignature.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1",
|
||||
equalTo(artifactSignature.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(appType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(appType).getName())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
// Retrieved is reported
|
||||
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
|
||||
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
|
||||
assertThat(actionStatusMessages).hasSize(3);
|
||||
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
|
||||
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Attempt/soft deployment to a controller including automated switch to hard. Checks if the resource reponse payload for a given deployment is as expected.")
|
||||
public void deplomentAutoForceAction() throws Exception {
|
||||
// Prepare test data
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
|
||||
final byte random[] = RandomUtils.nextBytes(5 * 1024);
|
||||
final LocalArtifact artifact = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1", false);
|
||||
final LocalArtifact artifactSignature = artifactManagement.createLocalArtifact(new ByteArrayInputStream(random),
|
||||
ds.findFirstModuleByType(osType).getId(), "test1.signature", false);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).isEmpty();
|
||||
assertThat(actionRepository.findAll()).isEmpty();
|
||||
assertThat(actionStatusRepository.findAll()).isEmpty();
|
||||
|
||||
List<Target> saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED,
|
||||
System.currentTimeMillis(), savedTarget.getControllerId()).getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1);
|
||||
|
||||
final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(actionRepository.findAll()).hasSize(1);
|
||||
saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets();
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
assertThat(actionRepository.findAll()).hasSize(2);
|
||||
|
||||
final Action uaction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
assertThat(uaction.getDistributionSet()).isEqualTo(ds);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2);
|
||||
|
||||
// Run test
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href", startsWith("http://localhost/"
|
||||
+ tenantAware.getCurrentTenant() + "/controller/v1/4712/deploymentBase/" + uaction.getId())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(2);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
Thread.sleep(1);
|
||||
|
||||
final DistributionSet findDistributionSetByAction = distributionSetManagement
|
||||
.findDistributionSetByAction(action);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/{actionId}", tenantAware.getCurrentTenant(),
|
||||
uaction.getId()).accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$id", equalTo(String.valueOf(action.getId()))))
|
||||
.andExpect(jsonPath("$deployment.download", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.update", equalTo("forced")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==jvm)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(runtimeType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(osType).getName())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(osType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].filename", equalTo("test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.md5",
|
||||
equalTo(artifact.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0].hashes.sha1",
|
||||
equalTo(artifact.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[0]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].size", equalTo(5 * 1024)))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].filename",
|
||||
equalTo("test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.md5",
|
||||
equalTo(artifactSignature.getMd5Hash())))
|
||||
.andExpect(
|
||||
jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1].hashes.sha1",
|
||||
equalTo(artifactSignature.getSha1Hash())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.download.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==os)][0].artifacts[1]._links.md5sum.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4712/softwaremodules/"
|
||||
+ findDistributionSetByAction.findFirstModuleByType(osType).getId()
|
||||
+ "/artifacts/test1.signature.MD5SUM")))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].version",
|
||||
equalTo(ds.findFirstModuleByType(appType).getVersion())))
|
||||
.andExpect(jsonPath("$deployment.chunks[?(@.part==bApp)][0].name",
|
||||
equalTo(ds.findFirstModuleByType(appType).getName())));
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
// Retrieved is reported
|
||||
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository
|
||||
.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
|
||||
assertThat(actionStatusMessages).hasSize(3);
|
||||
final ActionStatus actionStatusMessage = actionStatusMessages.iterator().next();
|
||||
assertThat(actionStatusMessage.getStatus()).isEqualTo(Status.RETRIEVED);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Test various invalid access attempts to the deployment resource und the expected behaviour of the server.")
|
||||
public void badDeploymentAction() throws Exception {
|
||||
final Target target = targetManagement.createTarget(new Target("4712"));
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
// non existing target
|
||||
mvc.perform(get("/{tenant}/controller/v1/4715/deploymentBase/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// no deployment
|
||||
mvc.perform(get("/controller/v1/4712/deploymentBase/1", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// wrong media type
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(target);
|
||||
final DistributionSet savedSet = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final Action action1 = deploymentManagement.assignDistributionSet(savedSet, toAssign).getActions().get(0);
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
mvc.perform(
|
||||
get("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId(), tenantAware.getCurrentTenant())
|
||||
.accept(MediaType.APPLICATION_ATOM_XML))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotAcceptable());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("The server protects itself against to many feedback upload attempts. The test verfies that "
|
||||
+ "it is not possible to exceed the configured maximum number of feedback uplods.")
|
||||
public void toMuchDeplomentActionFeedback() throws Exception {
|
||||
final Target target = targetManagement.createTarget(new Target("4712"));
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(target);
|
||||
|
||||
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4712" });
|
||||
final Pageable pageReq = new PageRequest(0, 100);
|
||||
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
|
||||
|
||||
final String feedback = JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding");
|
||||
// assign distribution set creates an action status, so only 99 left
|
||||
for (int i = 0; i < 99; i++) {
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk());
|
||||
}
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(feedback).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Multiple uploads of deployment status feedback to the server.")
|
||||
public void multipleDeplomentActionFeedback() throws Exception {
|
||||
final Target target1 = new Target("4712");
|
||||
final Target target2 = new Target("4713");
|
||||
final Target target3 = new Target("4714");
|
||||
final Target savedTarget1 = targetManagement.createTarget(target1);
|
||||
targetManagement.createTarget(target2);
|
||||
targetManagement.createTarget(target3);
|
||||
|
||||
final DistributionSet ds1 = TestDataUtil.generateDistributionSet("1", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
final DistributionSet ds3 = TestDataUtil.generateDistributionSet("3", softwareManagement,
|
||||
distributionSetManagement, true);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget1);
|
||||
|
||||
final Action action1 = deploymentManagement.assignDistributionSet(ds1.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
final Action action2 = deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
final Action action3 = deploymentManagement.assignDistributionSet(ds3.getId(), new String[] { "4712" })
|
||||
.getActions().get(0);
|
||||
|
||||
Target myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(3);
|
||||
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
assertThat(myT.getTargetInfo().getInstalledDistributionSet()).isNull();
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.UNKNOWN))
|
||||
.hasSize(2);
|
||||
|
||||
// action1 done
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
long lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action1.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action1.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
myT = targetManagement.findTargetByControllerIDWithDetails("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
// assertThat( myT.getLastModifiedAt() ).isEqualTo( lastModified );
|
||||
|
||||
final long timeDiff = Math
|
||||
.abs(myT.getTargetInfo().getLastTargetQuery() - myT.getTargetInfo().getInstallationDate());
|
||||
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(2);
|
||||
assertThat(myT.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds1.getId());
|
||||
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
|
||||
Iterable<ActionStatus> actionStatusMessages = actionStatusRepository.findAll(new Sort(Direction.DESC, "id"));
|
||||
assertThat(actionStatusMessages).hasSize(4);
|
||||
assertThat(actionStatusMessages.iterator().next().getStatus()).isEqualTo(Status.FINISHED);
|
||||
|
||||
// action2 done
|
||||
current = System.currentTimeMillis();
|
||||
lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
myT = targetManagement.findTargetByControllerIDWithDetails("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(myT.getTargetInfo().getInstalledDistributionSet().getId()).isEqualTo(ds2.getId());
|
||||
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
actionStatusMessages = actionStatusRepository.findAll(new PageRequest(0, 100, Direction.DESC, "id"));
|
||||
assertThat(actionStatusMessages).hasSize(5);
|
||||
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
|
||||
|
||||
// action3 done
|
||||
current = System.currentTimeMillis();
|
||||
lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action3.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action3.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
|
||||
assertThat(myT.getTargetInfo().getInstalledDistributionSet()).isEqualTo(ds3);
|
||||
assertThat(myT.getAssignedDistributionSet()).isEqualTo(ds3);
|
||||
actionStatusMessages = actionStatusRepository.findAll();
|
||||
assertThat(actionStatusMessages).hasSize(6);
|
||||
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that an update action is correctly set to error if the controller provides error feedback.")
|
||||
public void rootRsSingleDeplomentActionWithErrorFeedback() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.UNKNOWN);
|
||||
deploymentManagement.assignDistributionSet(ds, toAssign);
|
||||
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
long lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed", "failure"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
Target myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.ERROR);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
|
||||
assertThat(deploymentManagement.findActionsByTarget(myT)).hasSize(1);
|
||||
final Iterable<ActionStatus> actionStatusMessages = actionStatusRepository.findAll();
|
||||
assertThat(actionStatusMessages).hasSize(2);
|
||||
assertThat(actionStatusMessages).haveAtLeast(1, new ActionStatusCondition(Status.ERROR));
|
||||
|
||||
// redo
|
||||
toAssign = new ArrayList<Target>();
|
||||
toAssign.add(targetManagement.findTargetByControllerID("4712"));
|
||||
ds = distributionSetManagement.findDistributionSetByIdWithDetails(ds.getId());
|
||||
deploymentManagement.assignDistributionSet(ds, toAssign);
|
||||
final Action action2 = deploymentManagement.findActiveActionsByTarget(myT).get(0);
|
||||
current = System.currentTimeMillis();
|
||||
lastModified = targetManagement.findTargetByControllerID("4712").getLastModifiedAt();
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action2.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action2.getId().toString(), "closed", "success"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(1);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
|
||||
assertThat(deploymentManagement.findInActiveActionsByTarget(myT)).hasSize(2);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(4);
|
||||
assertThat(actionStatusRepository.findByAction(pageReq, action).getContent()).haveAtLeast(1,
|
||||
new ActionStatusCondition(Status.ERROR));
|
||||
assertThat(actionStatusRepository.findByAction(pageReq, action2).getContent()).haveAtLeast(1,
|
||||
new ActionStatusCondition(Status.FINISHED));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the controller can provided as much feedback entries as necessry as long as it is in the configured limites.")
|
||||
public void rootRsSingleDeplomentActionFeedback() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final Target savedTarget = targetManagement.createTarget(target);
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
|
||||
Target myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN);
|
||||
deploymentManagement.assignDistributionSet(ds, toAssign);
|
||||
final Action action = actionRepository.findByDistributionSet(pageReq, ds).getContent().get(0);
|
||||
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(targetRepository.findByTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds)).hasSize(0);
|
||||
assertThat(targetRepository.findByAssignedDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
|
||||
assertThat(targetRepository
|
||||
.findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds, ds))
|
||||
.hasSize(1);
|
||||
|
||||
// Now valid Feedback
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "proceeding"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(5);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(5, new ActionStatusCondition(Status.RUNNING));
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "scheduled"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(6);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(5, new ActionStatusCondition(Status.RUNNING));
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "resumed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(7);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(6, new ActionStatusCondition(Status.RUNNING));
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "canceled"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.PENDING))
|
||||
.hasSize(1);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(0);
|
||||
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(8);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(7, new ActionStatusCondition(Status.RUNNING));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "rejected"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.PENDING);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(1);
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(9);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(6, new ActionStatusCondition(Status.RUNNING));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.WARNING));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/" + action.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(action.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
myT = targetManagement.findTargetByControllerID("4712");
|
||||
assertThat(myT.getTargetInfo().getLastTargetQuery()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(myT.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.IN_SYNC);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(myT)).hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.ERROR))
|
||||
.hasSize(0);
|
||||
assertThat(targetManagement.findTargetByUpdateStatus(new PageRequest(0, 10), TargetUpdateStatus.IN_SYNC))
|
||||
.hasSize(1);
|
||||
|
||||
assertThat(actionStatusRepository.findAll()).hasSize(10);
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(7, new ActionStatusCondition(Status.RUNNING));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.WARNING));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.CANCELED));
|
||||
assertThat(actionStatusRepository.findAll()).haveAtLeast(1, new ActionStatusCondition(Status.FINISHED));
|
||||
|
||||
assertThat(targetRepository.findByTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
|
||||
assertThat(targetRepository.findByAssignedDistributionSet(new PageRequest(0, 10), ds)).hasSize(1);
|
||||
assertThat(targetRepository
|
||||
.findByAssignedDistributionSetOrTargetInfoInstalledDistributionSet(new PageRequest(0, 10), ds, ds))
|
||||
.hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Various forbidden request appempts on the feedback resource. Ensures correct answering behaviour as expected to these kind of errors.")
|
||||
public void badDeplomentActionFeedback() throws Exception {
|
||||
final Target target = new Target("4712");
|
||||
final Target target2 = new Target("4713");
|
||||
final DistributionSet savedSet = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final DistributionSet savedSet2 = TestDataUtil.generateDistributionSet("1", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
// target does not exist
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionInProgressFeedback("1234")).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
Target savedTarget = targetManagement.createTarget(target);
|
||||
final Target savedTarget2 = targetManagement.createTarget(target2);
|
||||
|
||||
// Action does not exists
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/1234/feedback", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionInProgressFeedback("1234")).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
final List<Target> toAssign = new ArrayList<Target>();
|
||||
toAssign.add(savedTarget);
|
||||
final List<Target> toAssign2 = new ArrayList<Target>();
|
||||
toAssign2.add(savedTarget2);
|
||||
|
||||
assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.UNKNOWN);
|
||||
savedTarget = deploymentManagement.assignDistributionSet(savedSet, toAssign).getAssignedTargets().iterator()
|
||||
.next();
|
||||
deploymentManagement.assignDistributionSet(savedSet2, toAssign2);
|
||||
|
||||
// wrong format
|
||||
mvc.perform(post("/{tenant}/controller/v1/4712/deploymentBase/AAAA/feedback", tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionInProgressFeedback("AAAA")).contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
final Action updateAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
|
||||
// action exists but is not assigned to this target
|
||||
mvc.perform(post("/{tenant}/controller/v1/4713/deploymentBase/" + updateAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionInProgressFeedback(updateAction.getId().toString()))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(get("/{tenant}/controller/v1/4712/deploymentBase/2/feedback", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/4712/deploymentBase/2/feedback", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/{tenant}/controller/v1/4712/deploymentBase/2/feedback", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
private class ActionStatusCondition extends Condition<ActionStatus> {
|
||||
private final Status status;
|
||||
|
||||
/**
|
||||
* @param status
|
||||
*/
|
||||
public ActionStatusCondition(final Status status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean matches(final ActionStatus actionStatus) {
|
||||
return actionStatus.getStatus() == status;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
/**
|
||||
* 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.controller;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithSpringAuthorityRule;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
|
||||
import org.eclipse.hawkbit.rest.resource.JsonBuilder;
|
||||
import org.eclipse.hawkbit.util.IpUtil;
|
||||
import org.junit.Test;
|
||||
import org.springframework.hateoas.MediaTypes;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Features("Component Tests - Controller RESTful API")
|
||||
@Stories("Root Poll Resource")
|
||||
// TODO: fully document tests -> @Description for long text and reasonable
|
||||
// method name as short text
|
||||
public class RootControllerTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that software modules are not found, when target does not exists ")
|
||||
public void testSoftwareModulesIfTargetNotExists() throws Exception {
|
||||
final String targetNotExist = "targetNotExist";
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetNotExist}/softwaremodules/", tenantAware.getCurrentTenant(),
|
||||
targetNotExist)).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
}
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that software modules are not found, when assigned distribution set exists with no modules")
|
||||
public void testSoftwareModulesEmptyIfDistributionSetNotExists() throws Exception {
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetExist}/softwaremodules/", tenantAware.getCurrentTenant(),
|
||||
TestDataUtil.createTarget(targetManagement).getName())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$", hasSize(0)));
|
||||
}
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that software modules are found, when assigned distribution set exists with modules")
|
||||
public void testAvailableSoftwareModulesWithNoArtifacts() throws Exception {
|
||||
final Target target = TestDataUtil.createTarget(targetManagement);
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
deploymentManagement.assignDistributionSet(distributionSet.getId(), new String[] { target.getName() });
|
||||
|
||||
final int modulesSize = distributionSet.getModules().size();
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/{targetExist}/softwaremodules/", tenantAware.getCurrentTenant(),
|
||||
target.getName())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$", hasSize(modulesSize)));
|
||||
}
|
||||
|
||||
@Test()
|
||||
@Description("Ensures that targets cannot be created e.g. in plug'n play scenarios when tenant does not exists but can be created if the tenant exists.")
|
||||
@WithUser(tenantId = "tenantDoesNotExists", allSpPermissions = true, authorities = "ROLE_CONTROLLER", autoCreateTenant = false)
|
||||
public void targetCannotBeRegisteredIfTenantDoesNotExistsButWhenExists() throws Exception {
|
||||
|
||||
mvc.perform(get("/default-tenant/", tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// create tenant
|
||||
systemManagement.getTenantMetadata("tenantDoesNotExists");
|
||||
|
||||
mvc.perform(get("/{}/controller/v1/aControllerId", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// delete tenant again
|
||||
systemManagement.deleteTenant("tenantDoesNotExists");
|
||||
|
||||
mvc.perform(get("/{}/controller/v1/aControllerId", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "knownPrincipal", authorities = { SpPermission.READ_TARGET, SpPermission.UPDATE_TARGET,
|
||||
SpPermission.CREATE_TARGET })
|
||||
public void targetPollDoesNotModifyAuditData() throws Exception {
|
||||
// create target first with "knownPrincipal" user and audit data
|
||||
final String knownTargetControllerId = "target1";
|
||||
final String knownCreatedBy = "knownPrincipal";
|
||||
targetManagement.createTarget(new Target(knownTargetControllerId));
|
||||
final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId);
|
||||
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
|
||||
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
|
||||
|
||||
// make a poll, audit information should not be changed, run as
|
||||
// controller principal!
|
||||
securityRule.runAs(
|
||||
WithSpringAuthorityRule.withUser("controller", SpringEvalExpressions.CONTROLLER_ROLE_ANONYMOUS),
|
||||
new Callable<Void>() {
|
||||
@Override
|
||||
public Void call() throws Exception {
|
||||
mvc.perform(get("/{tenant}/controller/v1/" + knownTargetControllerId,
|
||||
tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
// verify that audit information has not changed
|
||||
final Target targetVerify = targetManagement.findTargetByControllerID(knownTargetControllerId);
|
||||
assertThat(targetVerify.getCreatedBy()).isEqualTo(findTargetByControllerID.getCreatedBy());
|
||||
assertThat(targetVerify.getCreatedAt()).isEqualTo(findTargetByControllerID.getCreatedAt());
|
||||
assertThat(targetVerify.getLastModifiedBy()).isEqualTo(findTargetByControllerID.getLastModifiedBy());
|
||||
assertThat(targetVerify.getLastModifiedAt()).isEqualTo(findTargetByControllerID.getLastModifiedAt());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rootRsWithoutId() throws Exception {
|
||||
mvc.perform(get("/controller/v1/")).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rootRsPlugAndPlay() throws Exception {
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")));
|
||||
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.REGISTERED);
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/default-tenant/controller/v1/4711")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rootRsNotModified() throws Exception {
|
||||
final String etag = mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00"))).andReturn().getResponse()
|
||||
.getHeader("ETag");
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
|
||||
|
||||
final Target target = targetRepository.findByControllerId("4711");
|
||||
final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
deploymentManagement.assignDistributionSet(ds.getId(), new String[] { "4711" });
|
||||
|
||||
final Action updateAction = deploymentManagement.findActiveActionsByTarget(target).get(0);
|
||||
final String etagWithFirstUpdate = mvc
|
||||
.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
|
||||
.header("If-None-Match", etag).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href",
|
||||
startsWith("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4711/deploymentBase/" + updateAction.getId())))
|
||||
.andReturn().getResponse().getHeader("ETag");
|
||||
|
||||
assertThat(etagWithFirstUpdate).isNotNull();
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match",
|
||||
etagWithFirstUpdate)).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
|
||||
|
||||
// now lets finish the update
|
||||
mvc.perform(post("/{tenant}/controller/v1/4711/deploymentBase/" + updateAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(updateAction.getId().toString(), "closed"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// we are again at the original state
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()).header("If-None-Match", etag))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotModified());
|
||||
|
||||
// Now another deployment
|
||||
final DistributionSet ds2 = TestDataUtil.generateDistributionSet("2", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
deploymentManagement.assignDistributionSet(ds2.getId(), new String[] { "4711" });
|
||||
|
||||
final Action updateAction2 = deploymentManagement.findActiveActionsByTarget(target).get(0);
|
||||
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
|
||||
.header("If-None-Match", etagWithFirstUpdate).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")))
|
||||
.andExpect(jsonPath("$_links.deploymentBase.href",
|
||||
startsWith("http://localhost/" + tenantAware.getCurrentTenant()
|
||||
+ "/controller/v1/4711/deploymentBase/" + updateAction2.getId())))
|
||||
.andReturn().getResponse().getHeader("ETag");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rootRsPrecommissioned() throws Exception {
|
||||
final Target target = new Target("4711");
|
||||
targetManagement.createTarget(target);
|
||||
|
||||
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.UNKNOWN);
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$config.polling.sleep", equalTo("00:01:00")));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.findTargetByControllerID("4711").getTargetInfo().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
assertThat(targetRepository.findByControllerId("4711").getTargetInfo().getUpdateStatus())
|
||||
.isEqualTo(TargetUpdateStatus.REGISTERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rootRsPlugAndPlayIpAddress() throws Exception {
|
||||
// test
|
||||
final String knownControllerId1 = "0815";
|
||||
mvc.perform(get("/{tenant}/controller/v1/{controllerId}", tenantAware.getCurrentTenant(), knownControllerId1))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// verify
|
||||
final Target target = targetManagement.findTargetByControllerID(knownControllerId1);
|
||||
assertThat(target.getTargetInfo().getAddress()).isEqualTo(IpUtil.createHttpUri("127.0.0.1"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Controller trys to finish an update process after it has been finished by an error action status.")
|
||||
public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
|
||||
|
||||
// mock
|
||||
final Target target = new Target("911");
|
||||
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();
|
||||
final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0);
|
||||
mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.deploymentActionFeedback(savedAction.getId().toString(), "proceeding"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(
|
||||
JsonBuilder.deploymentActionFeedback(savedAction.getId().toString(), "closed", "failure"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback",
|
||||
tenantAware.getCurrentTenant()).content(
|
||||
JsonBuilder.deploymentActionFeedback(savedAction.getId().toString(), "closed", "success"))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isGone());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,916 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
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.DsMetadataCompositeKey;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.Target;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
import org.springframework.context.annotation.Description;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management RESTful API")
|
||||
@Stories("Distribution Set Resource")
|
||||
// TODO: fully document tests -> @Description for long text and reasonable
|
||||
// method name as short text
|
||||
public class DistributionSetResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of all Software Modules that are assiged to a Distribution Set through the RESTful API.")
|
||||
public void getSoftwaremodules() throws Exception {
|
||||
// Create DistributionSet with three software modules
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("SMTest", softwareManagement,
|
||||
distributionSetManagement);
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(set.getModules().size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the deletion of a assigned Software Module of a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
|
||||
public void testDeleteFailureWhenDistributionSetInUse() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Eris", "560a",
|
||||
distributionSetManagement);
|
||||
final List<Long> smIDs = new ArrayList<Long>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Dysnomia ", "15,772", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
final JSONArray smList = new JSONArray();
|
||||
for (final Long smID : smIDs) {
|
||||
smList.put(new JSONObject().put("id", Long.valueOf(smID)));
|
||||
}
|
||||
// post assignment
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(smList.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// create targets and assign DisSet to target
|
||||
final String[] knownTargetIds = new String[] { "1", "2" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
|
||||
// try to delete the Software Module from DisSet that has been assigned
|
||||
// to the target.
|
||||
mvc.perform(
|
||||
delete(
|
||||
RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/"
|
||||
+ smIDs.get(0)).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies that the assignment of a Software Module to a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
|
||||
public void testAssignmentFailureWhenAssigningToUsedDistributionSet() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Mars", "686,980",
|
||||
distributionSetManagement);
|
||||
final List<Long> smIDs = new ArrayList<Long>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Phobos", "0,3189", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
final JSONArray smList = new JSONArray();
|
||||
for (final Long smID : smIDs) {
|
||||
smList.put(new JSONObject().put("id", Long.valueOf(smID)));
|
||||
}
|
||||
// post assignment
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(smList.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// create Targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
// assign DisSet to target and test assignment
|
||||
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
|
||||
// Create another SM and post assignment
|
||||
final List<Long> smID2s = new ArrayList<Long>();
|
||||
SoftwareModule sm2 = new SoftwareModule(appType, "Deimos", "1,262", null, null);
|
||||
sm2 = softwareManagement.createSoftwareModule(sm2);
|
||||
smID2s.add(sm2.getId());
|
||||
final JSONArray smList2 = new JSONArray();
|
||||
for (final Long smID : smID2s) {
|
||||
smList2.put(new JSONObject().put("id", Long.valueOf(smID)));
|
||||
}
|
||||
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(smList2.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the assignment of Software Modules to a Distribution Set through the RESTful API.")
|
||||
public void assignSoftwaremoduleToDistributionSet() throws Exception {
|
||||
|
||||
// create DisSet
|
||||
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Jupiter", "398,88",
|
||||
distributionSetManagement);
|
||||
// Test if size is 0
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
|
||||
// create Software Modules
|
||||
final List<Long> smIDs = new ArrayList<Long>();
|
||||
SoftwareModule sm = new SoftwareModule(osType, "Europa", "3,551", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
smIDs.add(sm.getId());
|
||||
SoftwareModule sm2 = new SoftwareModule(appType, "Ganymed", "7,155", null, null);
|
||||
sm2 = softwareManagement.createSoftwareModule(sm2);
|
||||
smIDs.add(sm2.getId());
|
||||
SoftwareModule sm3 = new SoftwareModule(runtimeType, "Kallisto", "16,689", null, null);
|
||||
sm3 = softwareManagement.createSoftwareModule(sm3);
|
||||
smIDs.add(sm3.getId());
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final Long smID : smIDs) {
|
||||
list.put(new JSONObject().put("id", Long.valueOf(smID)));
|
||||
}
|
||||
// post assignment
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
// Test if size is 3
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(smIDs.size())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the rejection of Software Modules of a Distribution Set through the RESTful API.")
|
||||
public void unassignSoftwaremoduleFromDistributionSet() throws Exception {
|
||||
|
||||
// Create DistributionSet with three software modules
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("Venus", softwareManagement,
|
||||
distributionSetManagement);
|
||||
int amountOfSM = set.getModules().size();
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(amountOfSM)));
|
||||
// test the rejection of all assigned software modules one by one
|
||||
for (final Iterator<SoftwareModule> iter = set.getModules().iterator(); iter.hasNext();) {
|
||||
final Long smId = iter.next().getId();
|
||||
mvc.perform(
|
||||
delete(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.size", equalTo(--amountOfSM)));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assignMultipleTargetsToDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
// prepare targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
// assign already one target to DS
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
|
||||
|
||||
mvc.perform(
|
||||
post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")
|
||||
.contentType(MediaType.APPLICATION_JSON).content(list.toString())).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
|
||||
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
|
||||
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAssignedTargetsOfDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final String knownTargetId = "knownTargetId1";
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
targetManagement.createTarget(new Target(knownTargetId));
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
|
||||
|
||||
mvc.perform(
|
||||
get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
|
||||
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getAssignedTargetsOfDistributionSetIsEmpty() throws Exception {
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
mvc.perform(
|
||||
get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0)))
|
||||
.andExpect(jsonPath("$.total", equalTo(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getInstalledTargetsOfDistributionSet() throws Exception {
|
||||
// prepare distribution set
|
||||
final String knownTargetId = "knownTargetId1";
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
final Target createTarget = targetManagement.createTarget(new Target(knownTargetId));
|
||||
// create some dummy targets which are not assigned or installed
|
||||
targetManagement.createTarget(new Target("dummy1"));
|
||||
targetManagement.createTarget(new Target("dummy2"));
|
||||
// assign knownTargetId to distribution set
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
|
||||
// make it in install state
|
||||
sendUpdateActionStatusToTargets(createdDs, Lists.newArrayList(createTarget), Status.FINISHED, "some message");
|
||||
|
||||
mvc.perform(
|
||||
get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
|
||||
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDistributionSetsWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int modules = 5;
|
||||
createDistributionSetsAlphabetical(modules);
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(modules)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(modules)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDistributionSetsWithPagingLimitRequestParameter() throws Exception {
|
||||
final int modules = 5;
|
||||
final int limitSize = 1;
|
||||
createDistributionSetsAlphabetical(modules);
|
||||
mvc.perform(
|
||||
get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).param(
|
||||
RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int modules = 5;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = modules - offsetParam;
|
||||
createDistributionSetsAlphabetical(modules);
|
||||
mvc.perform(
|
||||
get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING).param(
|
||||
RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)).param(
|
||||
RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
public void testGetDistributionSets() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
DistributionSet set = TestDataUtil
|
||||
.generateDistributionSet("one", softwareManagement, distributionSetManagement);
|
||||
set.setRequiredMigrationStep(set.isRequiredMigrationStep());
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
set.setVersion("anotherVersion");
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
// load also lazy stuff
|
||||
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(get("/rest/v1/distributionsets").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(
|
||||
jsonPath("$content.[0]._links.self.href", equalTo("http://localhost/rest/v1/distributionsets/"
|
||||
+ set.getId())))
|
||||
.andExpect(jsonPath("$content.[0].id", equalTo(set.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[0].name", equalTo(set.getName())))
|
||||
.andExpect(jsonPath("$content.[0].requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("$content.[0].description", equalTo(set.getDescription())))
|
||||
.andExpect(jsonPath("$content.[0].type", equalTo(set.getType().getKey())))
|
||||
.andExpect(jsonPath("$content.[0].createdBy", equalTo(set.getCreatedBy())))
|
||||
.andExpect(jsonPath("$content.[0].createdAt", equalTo(set.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[0].complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo(set.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[0].version", equalTo(set.getVersion())))
|
||||
.andExpect(
|
||||
jsonPath("$content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("$content.[0].modules.[?(@.type==" + appType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("$content.[0].modules.[?(@.type==" + osType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(osType).getId().intValue())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
public void testGetDistributionSet() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
DistributionSet set = TestDataUtil
|
||||
.generateDistributionSet("one", softwareManagement, distributionSetManagement);
|
||||
set.setVersion("anotherVersion");
|
||||
set = distributionSetManagement.updateDistributionSet(set);
|
||||
|
||||
// load also lazy stuff
|
||||
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}", set.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(
|
||||
jsonPath("$_links.self.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
|
||||
.andExpect(jsonPath("$id", equalTo(set.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(set.getName())))
|
||||
.andExpect(jsonPath("$type", equalTo(set.getType().getKey())))
|
||||
.andExpect(jsonPath("$description", equalTo(set.getDescription())))
|
||||
.andExpect(jsonPath("$requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(set.getCreatedBy())))
|
||||
.andExpect(jsonPath("$complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(set.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(set.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(set.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$version", equalTo(set.getVersion())))
|
||||
.andExpect(
|
||||
jsonPath("$modules.[?(@.type==" + runtimeType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("$modules.[?(@.type==" + appType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("$modules.[?(@.type==" + osType.getKey() + ")][0].id", equalTo(set
|
||||
.findFirstModuleByType(osType).getId().intValue())));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
public void testCreateDistributionSets() throws JSONException, Exception {
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
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, ""));
|
||||
|
||||
DistributionSet one = TestDataUtil.buildDistributionSet("one", "one", standardDsType, os, jvm, ah);
|
||||
DistributionSet two = TestDataUtil.buildDistributionSet("two", "two", standardDsType, os, jvm, ah);
|
||||
DistributionSet three = TestDataUtil.buildDistributionSet("three", "three", standardDsType, os, jvm, ah);
|
||||
three.setRequiredMigrationStep(true);
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<>();
|
||||
sets.add(one);
|
||||
sets.add(two);
|
||||
sets.add(three);
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(
|
||||
post("/rest/v1/distributionsets/").content(JsonBuilder.distributionSets(sets))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0]name", equalTo(one.getName())))
|
||||
.andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
|
||||
.andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
|
||||
.andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
|
||||
.andExpect(
|
||||
jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id", equalTo(one
|
||||
.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")][0].id", equalTo(one
|
||||
.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")][0].id", equalTo(one
|
||||
.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1]name", equalTo(two.getName())))
|
||||
.andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
|
||||
.andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
|
||||
.andExpect(
|
||||
jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id", equalTo(two
|
||||
.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")][0].id", equalTo(two
|
||||
.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")][0].id", equalTo(two
|
||||
.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
|
||||
.andExpect(jsonPath("[2]name", equalTo(three.getName())))
|
||||
.andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
|
||||
.andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
|
||||
.andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
|
||||
.andExpect(
|
||||
jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id", equalTo(three
|
||||
.findFirstModuleByType(runtimeType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")][0].id", equalTo(three
|
||||
.findFirstModuleByType(appType).getId().intValue())))
|
||||
.andExpect(
|
||||
jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")][0].id", equalTo(three
|
||||
.findFirstModuleByType(osType).getId().intValue())))
|
||||
.andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
|
||||
|
||||
one = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
|
||||
.findDistributionSetByNameAndVersion("one", "one").getId());
|
||||
two = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
|
||||
.findDistributionSetByNameAndVersion("two", "two").getId());
|
||||
three = distributionSetManagement.findDistributionSetByIdWithDetails(distributionSetManagement
|
||||
.findDistributionSetByNameAndVersion("three", "three").getId());
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + one.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + one.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
String.valueOf(one.getId()));
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + two.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + two.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
String.valueOf(two.getId()));
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsets/" + three.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + three.getType().getId());
|
||||
|
||||
assertThat(JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
String.valueOf(three.getId()));
|
||||
|
||||
// check in database
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(3);
|
||||
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
|
||||
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
|
||||
assertThat(three.isRequiredMigrationStep()).isEqualTo(true);
|
||||
|
||||
assertThat(one.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(two.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteUnassignedistributionSet() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check repository content
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).isEmpty();
|
||||
assertThat(distributionSetRepository.findAll()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteAssignedDistributionSet() throws Exception {
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
targetManagement.createTarget(new Target("test"));
|
||||
deploymentManagement.assignDistributionSet(set.getId(), "test");
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
// perform request
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check repository content
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, true, true)).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateDistributionSet() throws Exception {
|
||||
|
||||
// prepare test data
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
|
||||
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
|
||||
|
||||
final DistributionSet update = new DistributionSet();
|
||||
update.setVersion("anotherVersion");
|
||||
update.setName(null);
|
||||
update.setType(standardDsType);
|
||||
|
||||
mvc.perform(
|
||||
put("/rest/v1/distributionsets/{dsId}", set.getId()).content(JsonBuilder.distributionSet(update))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(
|
||||
distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0)
|
||||
.getVersion()).isEqualTo("anotherVersion");
|
||||
assertThat(
|
||||
distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0).getName())
|
||||
.isEqualTo(set.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidRequestsOnDistributionSetsResource() throws Exception {
|
||||
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final List<DistributionSet> sets = new ArrayList<>();
|
||||
sets.add(set);
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/distributionsets").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(
|
||||
post("/rest/v1/distributionsets").content("sdfjsdlkjfskdjf".getBytes()).contentType(
|
||||
MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// unsupported media type
|
||||
mvc.perform(
|
||||
post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(sets)).contentType(
|
||||
MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createMetadata() throws Exception {
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
final String knownKey1 = "knownKey1";
|
||||
final String knownKey2 = "knownKey2";
|
||||
|
||||
final String knownValue1 = "knownValue1";
|
||||
final String knownValue2 = "knownValue2";
|
||||
|
||||
final JSONArray jsonArray = new JSONArray();
|
||||
jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
|
||||
jsonArray.put(new JSONObject().put("key", knownKey2).put("value", knownValue2));
|
||||
|
||||
mvc.perform(
|
||||
post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId()).contentType(
|
||||
MediaType.APPLICATION_JSON).content(jsonArray.toString())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isCreated()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0]key", equalTo(knownKey1)))
|
||||
.andExpect(jsonPath("[0]value", equalTo(knownValue1)))
|
||||
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
|
||||
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
|
||||
|
||||
final DistributionSetMetadata metaKey1 = distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS,
|
||||
knownKey1));
|
||||
final DistributionSetMetadata metaKey2 = distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS,
|
||||
knownKey2));
|
||||
|
||||
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
|
||||
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateMetadata() throws Exception {
|
||||
// prepare and create metadata for update
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
final String updateValue = "valueForUpdate";
|
||||
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS,
|
||||
knownValue));
|
||||
|
||||
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
|
||||
|
||||
mvc.perform(
|
||||
put("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey).contentType(
|
||||
MediaType.APPLICATION_JSON).content(jsonObject.toString())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
|
||||
|
||||
final DistributionSetMetadata assertDS = distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS,
|
||||
knownKey));
|
||||
assertThat(assertDS.getValue()).isEqualTo(updateValue);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void deleteMetadata() throws Exception {
|
||||
// prepare and create metadata for deletion
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS,
|
||||
knownValue));
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
try {
|
||||
distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS, knownKey));
|
||||
fail("expected EntityNotFoundException but didn't throw");
|
||||
} catch (final EntityNotFoundException e) {
|
||||
// ok as expected
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getSingleMetadata() throws Exception {
|
||||
// prepare and create metadata
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS,
|
||||
knownValue));
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(knownValue)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getPagedListofMetadata() throws Exception {
|
||||
|
||||
final int totalMetadata = 10;
|
||||
final int limitParam = 5;
|
||||
final String offsetParam = "0";
|
||||
final String knownKeyPrefix = "knownKey";
|
||||
final String knownValuePrefix = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
for (int index = 0; index < totalMetadata; index++) {
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
|
||||
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
|
||||
}
|
||||
|
||||
mvc.perform(
|
||||
get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
|
||||
testDS.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("size", equalTo(limitParam))).andExpect(jsonPath("total", equalTo(totalMetadata)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchDistributionSetRsql() throws Exception {
|
||||
final String dsSuffix = "test";
|
||||
final int amount = 10;
|
||||
TestDataUtil.generateDistributionSets(dsSuffix, amount, softwareManagement, distributionSetManagement);
|
||||
TestDataUtil.generateDistributionSet("DS1test", softwareManagement, distributionSetManagement);
|
||||
TestDataUtil.generateDistributionSet("DS2test", softwareManagement, distributionSetManagement);
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==DS1test,name==DS2test";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("DS1test")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("DS2test")));
|
||||
|
||||
}
|
||||
|
||||
@Ignore
|
||||
@Test
|
||||
public void filterDistributionSetComplete() throws Exception {
|
||||
final int amount = 10;
|
||||
TestDataUtil.generateDistributionSets(amount, softwareManagement, distributionSetManagement);
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE;
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(10)))
|
||||
.andExpect(jsonPath("total", equalTo(10)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchDistributionSetAssignedTargetsRsql() throws Exception {
|
||||
// prepare distribution set
|
||||
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
|
||||
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
|
||||
// prepare targets
|
||||
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
|
||||
final JSONArray list = new JSONArray();
|
||||
for (final String targetId : knownTargetIds) {
|
||||
targetManagement.createTarget(new Target(targetId));
|
||||
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
|
||||
}
|
||||
|
||||
// assign already one target to DS
|
||||
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
|
||||
|
||||
final String rsqlFindTargetId1 = "controllerId==1";
|
||||
|
||||
mvc.perform(
|
||||
get(
|
||||
RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
|
||||
+ "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(list.toString())).andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1)))
|
||||
.andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchDistributionSetMetadataRsql() throws Exception {
|
||||
final int totalMetadata = 10;
|
||||
final String knownKeyPrefix = "knownKey";
|
||||
final String knownValuePrefix = "knownValue";
|
||||
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
|
||||
distributionSetManagement);
|
||||
for (int index = 0; index < totalMetadata; index++) {
|
||||
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
|
||||
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
|
||||
}
|
||||
|
||||
final String rsqlSearchValue1 = "value==knownValue1";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?q=" + rsqlSearchValue1, testDS.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(1)))
|
||||
.andExpect(jsonPath("total", equalTo(1))).andExpect(jsonPath("content[0].key", equalTo("knownKey1")))
|
||||
.andExpect(jsonPath("content[0].value", equalTo("knownValue1")));
|
||||
}
|
||||
|
||||
private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
final Set<DistributionSet> created = new HashSet<>();
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
created.add(TestDataUtil.generateDistributionSet(str, softwareManagement, distributionSetManagement));
|
||||
character++;
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
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,551 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
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.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test for {@link DistributionSetTypeResource}.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management RESTful API")
|
||||
@Stories("Distribution Set Type Resource")
|
||||
public class DistributionSetTypeResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
|
||||
public void getDistributionSetTypes() throws Exception {
|
||||
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = distributionSetManagement.updateDistributionSetType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].name",
|
||||
equalTo(standardDsType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].description",
|
||||
equalTo(standardDsType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].key",
|
||||
equalTo(standardDsType.getKey())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
|
||||
equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.self.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.mandatorymodules.href",
|
||||
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId()
|
||||
+ "/mandatorymoduletypes")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.optionalmodules.href", equalTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + testType.getId() + "/optionalmoduletypes")))
|
||||
.andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
|
||||
public void createDistributionSetTypes() throws JSONException, Exception {
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
|
||||
final List<DistributionSetType> types = new ArrayList<>();
|
||||
types.add(new DistributionSetType("test1", "TestName1", "Desc1").addMandatoryModuleType(osType)
|
||||
.addOptionalModuleType(runtimeType));
|
||||
types.add(new DistributionSetType("test2", "TestName2", "Desc2").addOptionalModuleType(osType)
|
||||
.addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
|
||||
types.add(new DistributionSetType("test3", "TestName3", "Desc3").addMandatoryModuleType(osType)
|
||||
.addMandatoryModuleType(runtimeType));
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
|
||||
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
|
||||
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
|
||||
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
|
||||
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
|
||||
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
|
||||
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn();
|
||||
|
||||
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("test1");
|
||||
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("test2");
|
||||
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("test3");
|
||||
|
||||
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
|
||||
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
|
||||
assertThat(created2.getOptionalModuleTypes()).containsOnly(osType, runtimeType, appType);
|
||||
assertThat(created3.getMandatoryModuleTypes()).containsOnly(osType, runtimeType);
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created1.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created2.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created3.getId());
|
||||
|
||||
assertThat(JsonPath.compile("[0]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/mandatorymoduletypes");
|
||||
assertThat(JsonPath.compile("[1]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/mandatorymoduletypes");
|
||||
assertThat(JsonPath.compile("[2]_links.mandatorymodules.href")
|
||||
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/mandatorymoduletypes");
|
||||
|
||||
assertThat(JsonPath.compile("[0]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/optionalmoduletypes");
|
||||
assertThat(JsonPath.compile("[1]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/optionalmoduletypes");
|
||||
assertThat(JsonPath.compile("[2]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).isEqualTo(
|
||||
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/optionalmoduletypes");
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
|
||||
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
|
||||
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
assertThat(testType.getOptionalModuleTypes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
|
||||
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
|
||||
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
|
||||
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("[0].description", equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1))).andExpect(jsonPath("[0].key", equalTo("os")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
|
||||
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("[0].description", equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("[0].key", equalTo("application")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
|
||||
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
|
||||
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(osType.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("$description", equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(osType.getCreatedBy())))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(osType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(osType.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(osType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
|
||||
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
|
||||
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(appType.getId().intValue())))
|
||||
.andExpect(jsonPath("$name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("$description", equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("$createdBy", equalTo(appType.getCreatedBy())))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(appType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo(appType.getLastModifiedBy())))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(appType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
|
||||
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
|
||||
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
|
||||
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
|
||||
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(1);
|
||||
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
|
||||
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
|
||||
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
|
||||
assertThat(testType.getOptLockRevision()).isEqualTo(2);
|
||||
assertThat(testType.getOptionalModuleTypes()).isEmpty();
|
||||
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
|
||||
public void getDistributionSetType() throws Exception {
|
||||
|
||||
DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = distributionSetManagement.updateDistributionSetType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
|
||||
public void deleteDistributionSetTypeUnused() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{dsId}", testType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
|
||||
public void deleteDistributionSetTypeUsed() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
distributionSetManagement
|
||||
.createDistributionSet(new DistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
|
||||
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
|
||||
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/{smId}", testType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
|
||||
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
|
||||
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
|
||||
.put("name", "nameShouldNotBeChanged").toString();
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsettypes/{smId}", testType.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$description", equalTo("foobardesc")))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int types = 3;
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithPagingLimitRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int limitSize = 1;
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
|
||||
public void getDistributionSetTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = types - offsetParam;
|
||||
mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
|
||||
public void invalidRequestsOnDistributionSetTypesResource() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
|
||||
final SoftwareModuleType testSmType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final List<DistributionSetType> types = new ArrayList<>();
|
||||
types.add(testType);
|
||||
|
||||
// DST does not exist
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/12345678/optionalmoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// Module types incorrect
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/565765656"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/565765656"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/"
|
||||
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(get(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + appType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/"
|
||||
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
// Modules types at creation time invalid
|
||||
|
||||
final DistributionSetType testNewType = new DistributionSetType("test123", "TestName123", "Desc123");
|
||||
testNewType.addMandatoryModuleType(new SoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
|
||||
|
||||
mvc.perform(post("/rest/v1/distributionsettypes")
|
||||
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/distributionsettypes").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/distributionsettypes").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(put("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
mvc.perform(put(
|
||||
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Search erquest of software module types.")
|
||||
public void searchDistributionSetTypeRsql() throws Exception {
|
||||
final DistributionSetType testType = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
|
||||
final DistributionSetType testType2 = distributionSetManagement
|
||||
.createDistributionSetType(new DistributionSetType("test1234", "TestName1234", "Desc123"));
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
|
||||
|
||||
mvc.perform(get("/rest/v1/distributionsettypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
|
||||
}
|
||||
|
||||
private void createSoftwareModulesAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
|
||||
|
||||
softwareManagement.createSoftwareModule(softwareModule);
|
||||
character++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.cache.CacheConstants;
|
||||
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
|
||||
import org.eclipse.hawkbit.cache.DownloadType;
|
||||
import org.eclipse.hawkbit.repository.model.Artifact;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.context.annotation.Description;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests- Download Restful API")
|
||||
@Stories("Download Resource")
|
||||
public class DownloadResourceTest extends AbstractIntegrationTestWithMongoDB {
|
||||
|
||||
@Autowired
|
||||
@Qualifier(CacheConstants.DOWNLOAD_ID_CACHE)
|
||||
private Cache downloadIdCache;
|
||||
|
||||
private final String downloadIdSha1 = "downloadIdSha1";
|
||||
|
||||
private final String downloadIdNotAvailable = "downloadIdNotAvailable";
|
||||
|
||||
@Before
|
||||
public void setupCache() {
|
||||
|
||||
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("Test", softwareManagement,
|
||||
distributionSetManagement);
|
||||
final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get();
|
||||
final Artifact artifact = TestDataUtil.generateArtifacts(artifactManagement, softwareModule.getId()).stream()
|
||||
.findFirst().get();
|
||||
|
||||
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of download artifact without a valid download id fails.")
|
||||
public void testNoDownloadIdAvailable() throws Exception {
|
||||
mvc.perform(
|
||||
get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdNotAvailable))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("This test verifies the call of download artifact works and the download id will be removed.")
|
||||
public void testDownload() throws Exception {
|
||||
mvc.perform(
|
||||
get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdSha1))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// because cache is empty
|
||||
mvc.perform(
|
||||
get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
|
||||
downloadIdSha1))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
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.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/**
|
||||
* Builder class for building certain json strings.
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public abstract class JsonBuilder {
|
||||
|
||||
public static String softwareModules(final List<SoftwareModule> modules) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModule module : modules) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("type", module.getType().getKey())
|
||||
.put("id", Long.MAX_VALUE).put("vendor", module.getVendor()).put("version", module.getVersion())
|
||||
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
|
||||
.put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < modules.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String softwareModuleTypes(final List<SoftwareModuleType> types) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final SoftwareModuleType module : types) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
|
||||
.put("key", module.getKey()).put("maxAssignments", module.getMaxAssignments())
|
||||
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
|
||||
.put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a json string for the feedback for the execution "proceeding".
|
||||
*
|
||||
* @param id
|
||||
* of the Action feedback refers to
|
||||
* @return the built string
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static String deploymentActionInProgressFeedback(final String id) throws JSONException {
|
||||
return deploymentActionFeedback(id, "proceeding");
|
||||
}
|
||||
|
||||
/**
|
||||
* builds a certain json string for a action feedback.
|
||||
*
|
||||
* @param id
|
||||
* of the action the feedback refers to
|
||||
* @param execution
|
||||
* see ExecutionStatus
|
||||
* @return the build json string
|
||||
* @throws JSONException
|
||||
*/
|
||||
public static String deploymentActionFeedback(final String id, final String execution) throws JSONException {
|
||||
return deploymentActionFeedback(id, execution, "none");
|
||||
|
||||
}
|
||||
|
||||
public static String deploymentActionFeedback(final String id, final String execution, final String finished)
|
||||
throws JSONException {
|
||||
final List<String> messages = new ArrayList<String>();
|
||||
messages.add(RandomStringUtils.randomAscii(1000));
|
||||
|
||||
return new JSONObject().put("id", id).put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject().put("execution", execution)
|
||||
.put("result",
|
||||
new JSONObject().put("finished", finished).put("progress",
|
||||
new JSONObject().put("cnt", 2).put("of", 5)))
|
||||
.put("details", messages))
|
||||
.toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param types
|
||||
* @return
|
||||
*/
|
||||
public static String distributionSetTypes(final List<DistributionSetType> types) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSetType module : types) {
|
||||
|
||||
try {
|
||||
|
||||
final JSONArray osmTypes = new JSONArray();
|
||||
module.getOptionalModuleTypes().forEach(smt -> osmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
final JSONArray msmTypes = new JSONArray();
|
||||
module.getMandatoryModuleTypes().forEach(smt -> msmTypes.put(new JSONObject().put("id", smt.getId())));
|
||||
|
||||
builder.append(new JSONObject().put("name", module.getName())
|
||||
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
|
||||
.put("key", module.getKey()).put("createdAt", "0").put("updatedAt", "0")
|
||||
.put("createdBy", "fghdfkjghdfkjh").put("optionalmodules", osmTypes)
|
||||
.put("mandatorymodules", msmTypes).put("updatedBy", "fghdfkjghdfkjh").toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < types.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String distributionSets(final List<DistributionSet> sets) throws JSONException {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final DistributionSet set : sets) {
|
||||
try {
|
||||
builder.append(distributionSet(set));
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < sets.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String distributionSet(final DistributionSet set) throws JSONException {
|
||||
|
||||
final List<JSONObject> modules = set.getModules().stream().map(module -> {
|
||||
try {
|
||||
return new JSONObject().put("id", module.getId());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
|
||||
.put("type", set.getType().getKey()).put("id", Long.MAX_VALUE).put("version", set.getVersion())
|
||||
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
|
||||
.put("updatedBy", "fghdfkjghdfkjh").put("requiredMigrationStep", set.isRequiredMigrationStep())
|
||||
.put("modules", modules).toString();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param targets
|
||||
* @return
|
||||
*/
|
||||
public static String targets(final List<Target> targets) {
|
||||
final StringBuilder builder = new StringBuilder();
|
||||
|
||||
builder.append("[");
|
||||
int i = 0;
|
||||
for (final Target target : targets) {
|
||||
try {
|
||||
builder.append(new JSONObject().put("controllerId", target.getControllerId())
|
||||
.put("description", target.getDescription()).put("name", target.getName()).put("createdAt", "0")
|
||||
.put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh")
|
||||
.toString());
|
||||
} catch (final Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (++i < targets.size()) {
|
||||
builder.append(",");
|
||||
}
|
||||
}
|
||||
|
||||
builder.append("]");
|
||||
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public static String cancelActionFeedback(final String id, final String execution) throws JSONException {
|
||||
final List<String> messages = new ArrayList<String>();
|
||||
messages.add(RandomStringUtils.randomAscii(1000));
|
||||
return new JSONObject().put("id", id).put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject().put("execution", execution)
|
||||
.put("result", new JSONObject().put("finished", "success")).put("details", messages))
|
||||
.toString();
|
||||
|
||||
}
|
||||
|
||||
public static String configData(final String id, final Map<String, String> attributes, final String execution)
|
||||
throws JSONException {
|
||||
return new JSONObject().put("id", id).put("time", "20140511T121314")
|
||||
.put("status",
|
||||
new JSONObject().put("execution", execution)
|
||||
.put("result", new JSONObject().put("finished", "success"))
|
||||
.put("details", new ArrayList<String>()))
|
||||
.put("data", attributes).toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.rest.resource;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Matchers.eq;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.reset;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Expression;
|
||||
import javax.persistence.criteria.Path;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import javax.persistence.metamodel.Attribute;
|
||||
import javax.persistence.metamodel.ManagedType;
|
||||
import javax.persistence.metamodel.Metamodel;
|
||||
|
||||
import org.eclipse.hawkbit.repository.FieldNameProvider;
|
||||
import org.eclipse.hawkbit.repository.SoftwareModuleFields;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLParameterSyntaxException;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLParameterUnsupportedFieldException;
|
||||
import org.eclipse.hawkbit.repository.rsql.RSQLUtility;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.runners.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@Features("Component Tests - Management RESTful API")
|
||||
@Stories("RSQL search utility")
|
||||
// TODO: fully document tests -> @Description for long text and reasonable
|
||||
// method name as short text
|
||||
public class RSQLUtilityTest {
|
||||
|
||||
@Mock
|
||||
private Root<Object> baseSoftwareModuleRootMock;
|
||||
|
||||
@Mock
|
||||
private CriteriaQuery<SoftwareModule> criteriaQueryMock;
|
||||
@Mock
|
||||
private CriteriaBuilder criteriaBuilderMock;
|
||||
@Mock
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Mock
|
||||
private Metamodel metamodel;
|
||||
|
||||
@Mock
|
||||
private ManagedType managedType;
|
||||
|
||||
@Mock
|
||||
private Attribute attribute;
|
||||
|
||||
@Test(expected = RSQLParameterSyntaxException.class)
|
||||
public void wrongRsqlSyntaxThrowSyntaxException() {
|
||||
final String wrongRSQL = "name==abc;d";
|
||||
when(entityManager.getMetamodel()).thenReturn(metamodel);
|
||||
RSQLUtility.parse(wrongRSQL, SoftwareModuleFields.class, entityManager).toPredicate(baseSoftwareModuleRootMock,
|
||||
criteriaQueryMock, criteriaBuilderMock);
|
||||
}
|
||||
|
||||
@Test(expected = RSQLParameterUnsupportedFieldException.class)
|
||||
public void wrongFieldThrowUnsupportedFieldException() {
|
||||
final String wrongRSQL = "unknownField==abc";
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
|
||||
doEntitySetup(SoftwareModule.class);
|
||||
RSQLUtility.parse(wrongRSQL, SoftwareModuleFields.class, entityManager).toPredicate(baseSoftwareModuleRootMock,
|
||||
criteriaQueryMock, criteriaBuilderMock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public <T> void correctRsqlBuildsPredicate() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "name==abc;version==1.2";
|
||||
when(baseSoftwareModuleRootMock.get("name")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.get("version")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
when(criteriaBuilderMock.<String> greaterThanOrEqualTo(any(Expression.class), any(String.class))).thenReturn(
|
||||
mock(Predicate.class));
|
||||
|
||||
doEntitySetup(SoftwareModule.class);
|
||||
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, SoftwareModuleFields.class, entityManager).toPredicate(
|
||||
baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
|
||||
// verfication
|
||||
verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void correctRsqlBuildsNotEqualPredicate() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "name!=abc";
|
||||
when(baseSoftwareModuleRootMock.get("name")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
when(criteriaBuilderMock.<String> greaterThanOrEqualTo(any(Expression.class), any(String.class))).thenReturn(
|
||||
mock(Predicate.class));
|
||||
doEntitySetup(SoftwareModule.class);
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, SoftwareModuleFields.class, entityManager).toPredicate(
|
||||
baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
|
||||
// verfication
|
||||
verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
|
||||
verify(criteriaBuilderMock, times(1)).notEqual(eq(baseSoftwareModuleRootMock), eq("abc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void correctRsqlBuildsLessThanPredicate() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "name=lt=abc";
|
||||
when(baseSoftwareModuleRootMock.get("name")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
when(criteriaBuilderMock.<String> greaterThanOrEqualTo(any(Expression.class), any(String.class))).thenReturn(
|
||||
mock(Predicate.class));
|
||||
doEntitySetup(SoftwareModule.class);
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, SoftwareModuleFields.class, entityManager).toPredicate(
|
||||
baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
|
||||
// verfication
|
||||
verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
|
||||
verify(criteriaBuilderMock, times(1)).lessThan(eq(pathOfString(baseSoftwareModuleRootMock)), eq("abc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void correctRsqlBuildsLikePredicate() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "name=li=abc";
|
||||
when(baseSoftwareModuleRootMock.get("name")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) SoftwareModule.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
when(criteriaBuilderMock.<String> greaterThanOrEqualTo(any(Expression.class), any(String.class))).thenReturn(
|
||||
mock(Predicate.class));
|
||||
when(criteriaBuilderMock.upper(eq(pathOfString(baseSoftwareModuleRootMock)))).thenReturn(
|
||||
pathOfString(baseSoftwareModuleRootMock));
|
||||
doEntitySetup(SoftwareModule.class);
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, SoftwareModuleFields.class, entityManager).toPredicate(
|
||||
baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
|
||||
// verfication
|
||||
verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
|
||||
verify(criteriaBuilderMock, times(1)).like(eq(pathOfString(baseSoftwareModuleRootMock)),
|
||||
eq("abc".toUpperCase()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void correctRsqlWithEnumValue() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "testfield==bumlux";
|
||||
when(baseSoftwareModuleRootMock.get("testfield")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) TestValueEnum.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
|
||||
doEntitySetup(TestValueEnum.class);
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, TestFieldEnum.class, entityManager).toPredicate(baseSoftwareModuleRootMock,
|
||||
criteriaQueryMock, criteriaBuilderMock);
|
||||
|
||||
// verfication
|
||||
verify(criteriaBuilderMock, times(1)).and(any(Predicate.class));
|
||||
verify(criteriaBuilderMock, times(1)).equal(eq(baseSoftwareModuleRootMock), eq(TestValueEnum.BUMLUX));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void wrongRsqlWithWrongEnumValue() {
|
||||
reset(baseSoftwareModuleRootMock, criteriaQueryMock, criteriaBuilderMock);
|
||||
final String correctRsql = "testfield==unknownValue";
|
||||
when(baseSoftwareModuleRootMock.get("testfield")).thenReturn(baseSoftwareModuleRootMock);
|
||||
when(baseSoftwareModuleRootMock.getJavaType()).thenReturn((Class) TestValueEnum.class);
|
||||
when(criteriaBuilderMock.equal(any(Root.class), anyString())).thenReturn(mock(Predicate.class));
|
||||
|
||||
doEntitySetup(TestValueEnum.class);
|
||||
|
||||
try {
|
||||
// test
|
||||
RSQLUtility.parse(correctRsql, TestFieldEnum.class, entityManager).toPredicate(baseSoftwareModuleRootMock,
|
||||
criteriaQueryMock, criteriaBuilderMock);
|
||||
fail("missing RSQLParameterUnsupportedFieldException for wrong enum value");
|
||||
} catch (final RSQLParameterUnsupportedFieldException e) {
|
||||
// nope expected
|
||||
}
|
||||
}
|
||||
|
||||
private void doEntitySetup(final Class clasName) {
|
||||
when(entityManager.getMetamodel()).thenReturn(metamodel);
|
||||
when(metamodel.managedType(clasName)).thenReturn(managedType);
|
||||
when(managedType.getJavaType()).thenReturn(clasName);
|
||||
|
||||
doAnswer(new Answer<Attribute>() {
|
||||
@Override
|
||||
public Attribute answer(final InvocationOnMock invocation) throws Throwable {
|
||||
return attribute;
|
||||
}
|
||||
}).when(managedType).getAttribute(anyString());
|
||||
|
||||
when(attribute.isAssociation()).thenReturn(false);
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <Y> Path<Y> pathOfString(final Path<?> path) {
|
||||
return (Path<Y>) path;
|
||||
}
|
||||
|
||||
private enum TestFieldEnum implements FieldNameProvider {
|
||||
TESTFIELD;
|
||||
|
||||
/*
|
||||
* (non-Javadoc)
|
||||
*
|
||||
* @see
|
||||
* org.eclipse.hawkbit.server.rest.resource.model.FieldNameProvider#
|
||||
* getFieldName()
|
||||
*/
|
||||
@Override
|
||||
public String getFieldName() {
|
||||
return "testfield";
|
||||
}
|
||||
}
|
||||
|
||||
private enum TestValueEnum {
|
||||
BUMLUX;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo;
|
||||
import org.eclipse.hawkbit.rest.resource.model.PagedList;
|
||||
import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* Utility additions for the REST API tests.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public final class ResourceUtility {
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static ExceptionInfo convertException(final String jsonExceptionResponse)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(jsonExceptionResponse, ExceptionInfo.class);
|
||||
}
|
||||
|
||||
static ArtifactRest convertArtifactResponse(final String jsonResponse)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(jsonResponse, ArtifactRest.class);
|
||||
|
||||
}
|
||||
|
||||
static <T> PagedList<T> mapResponse(final Class<T> clazz, final String responseBody)
|
||||
throws JsonParseException, JsonMappingException, IOException {
|
||||
return mapper.readValue(responseBody, PagedList.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.mock.web.MockMultipartFile;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
/**
|
||||
* Tests {@link SoftwareModuleResource} in case of missing MongoDB connection.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class SMRessourceMisingMongoDbConnectionTest 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
|
||||
public void testMissingMongoDbConnection() throws Exception {
|
||||
|
||||
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
|
||||
"version 1", null, null);
|
||||
sm = softwareManagement.createSoftwareModule(sm);
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
// create test file
|
||||
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);
|
||||
|
||||
// upload
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()).andReturn();
|
||||
|
||||
// check error result
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
.convertException(mvcResult.getResponse().getContentAsString());
|
||||
assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getKey());
|
||||
assertThat(exceptionInfo.getMessage()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getMessage());
|
||||
|
||||
// ensure that the JPA transaction was rolled back
|
||||
assertThat(artifactRepository.findAll()).hasSize(0);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModule;
|
||||
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
import com.jayway.jsonpath.JsonPath;
|
||||
|
||||
import ru.yandex.qatools.allure.annotations.Description;
|
||||
import ru.yandex.qatools.allure.annotations.Features;
|
||||
import ru.yandex.qatools.allure.annotations.Stories;
|
||||
|
||||
/**
|
||||
* Test for {@link SoftwareModuleTypeResource}.
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*/
|
||||
@Features("Component Tests - Management RESTful API")
|
||||
@Stories("Software Module Type Resource")
|
||||
public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.")
|
||||
public void getSoftwareModuleTypes() throws Exception {
|
||||
SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = softwareManagement.updateSoftwareModuleType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].name", equalTo(osType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].description",
|
||||
equalTo(osType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].key", equalTo("os")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].name",
|
||||
equalTo(runtimeType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].description",
|
||||
equalTo(runtimeType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].key", equalTo("runtime")))
|
||||
.andExpect(
|
||||
jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].name", equalTo(appType.getName())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].description",
|
||||
equalTo(appType.getDescription())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].key", equalTo("application")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
|
||||
equalTo(testType.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
|
||||
.andExpect(jsonPath("$total", equalTo(4)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
|
||||
public void createSoftwareModuleTypes() throws JSONException, Exception {
|
||||
|
||||
final List<SoftwareModuleType> types = new ArrayList<>();
|
||||
types.add(new SoftwareModuleType("test1", "TestName1", "Desc1", 1));
|
||||
types.add(new SoftwareModuleType("test2", "TestName2", "Desc2", 2));
|
||||
types.add(new SoftwareModuleType("test3", "TestName3", "Desc3", 3));
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
|
||||
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
|
||||
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
|
||||
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
|
||||
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
|
||||
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].maxAssignments", equalTo(2)))
|
||||
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
|
||||
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
|
||||
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
|
||||
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
|
||||
|
||||
final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1");
|
||||
final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2");
|
||||
final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3");
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId());
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.")
|
||||
public void getSoftwareModuleType() throws Exception {
|
||||
SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
testType.setDescription("Desc1234");
|
||||
testType = softwareManagement.updateSoftwareModuleType(testType);
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("$description", equalTo("Desc1234")))
|
||||
.andExpect(jsonPath("$maxAssignments", equalTo(5)))
|
||||
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
|
||||
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("$lastModifiedAt", equalTo(testType.getLastModifiedAt())));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).")
|
||||
public void deleteSoftwareModuleTypeUnused() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
|
||||
public void deleteSoftwareModuleTypeUsed() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
softwareManagement
|
||||
.createSoftwareModule(new SoftwareModule(testType, "name", "version", "description", "vendor"));
|
||||
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
|
||||
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
|
||||
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.")
|
||||
public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
|
||||
.put("name", "nameShouldNotBeChanged").toString();
|
||||
|
||||
mvc.perform(put("/rest/v1/softwaremoduletypes/{smId}", testType.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
|
||||
.andExpect(jsonPath("$description", equalTo("foobardesc")))
|
||||
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int types = 3;
|
||||
mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithPagingLimitRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int limitSize = 1;
|
||||
mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
|
||||
public void getSoftwareModuleTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int types = 3;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = types - offsetParam;
|
||||
mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
|
||||
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
|
||||
final List<SoftwareModuleType> types = new ArrayList<>();
|
||||
types.add(testType);
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// unsupported media type
|
||||
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(types))
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isUnsupportedMediaType());
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isMethodNotAllowed());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Search erquest of software module types.")
|
||||
public void searchSoftwareModuleTypeRsql() throws Exception {
|
||||
final SoftwareModuleType testType = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
|
||||
final SoftwareModuleType testType2 = softwareManagement
|
||||
.createSoftwareModuleType(new SoftwareModuleType("test1234", "TestName1234", "Desc123", 5));
|
||||
|
||||
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremoduletypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
|
||||
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
|
||||
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
|
||||
|
||||
}
|
||||
|
||||
private void createSoftwareModulesAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
for (int index = 0; index < amount; index++) {
|
||||
final String str = String.valueOf(character);
|
||||
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
|
||||
|
||||
softwareManagement.createSoftwareModule(softwareModule);
|
||||
character++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.eclipse.hawkbit.repository.TargetFields;
|
||||
import org.junit.Test;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public class SortUtilityTest {
|
||||
private static final String SORT_PARAM_1 = "NAME:ASC";
|
||||
private static final String SORT_PARAM_2 = "NAME:ASC, DESCRIPTION:DESC";
|
||||
private static final String SYNTAX_FAILURE_SORT_PARAM = "NAME:ASC DESCRIPTION:DESC";
|
||||
private static final String WRONG_DIRECTION_PARAM = "NAME:ASDF";
|
||||
private static final String CASE_INSENSITIVE_DIRECTION_PARAM = "NaME:ASC";
|
||||
private static final String CASE_INSENSITIVE_DIRECTION_PARAM_1 = "name:ASC";
|
||||
private static final String WRONG_FIELD_PARAM = "ASDF:ASC";
|
||||
|
||||
@Test
|
||||
public void parseSortParam1() {
|
||||
|
||||
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_1);
|
||||
assertEquals(1, parse.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parseSortParam2() {
|
||||
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_2);
|
||||
assertEquals(2, parse.size());
|
||||
}
|
||||
|
||||
@Test(expected = SortParameterSyntaxErrorException.class)
|
||||
public void parseWrongSyntaxParam() {
|
||||
SortUtility.parse(TargetFields.class, SYNTAX_FAILURE_SORT_PARAM);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void parsingIsNotCaseSensitive() {
|
||||
SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM);
|
||||
SortUtility.parse(TargetFields.class, CASE_INSENSITIVE_DIRECTION_PARAM_1);
|
||||
}
|
||||
|
||||
@Test(expected = SortParameterUnsupportedDirectionException.class)
|
||||
public void parseWrongDirectionParam() {
|
||||
SortUtility.parse(TargetFields.class, WRONG_DIRECTION_PARAM);
|
||||
}
|
||||
|
||||
@Test(expected = SortParameterUnsupportedFieldException.class)
|
||||
public void parseWrongFieldParam() {
|
||||
SortUtility.parse(TargetFields.class, WRONG_FIELD_PARAM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
/**
|
||||
* 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.rest.resource;
|
||||
|
||||
import static org.fest.assertions.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.eclipse.hawkbit.AbstractIntegrationTest;
|
||||
import org.eclipse.hawkbit.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.TestDataUtil;
|
||||
import org.eclipse.hawkbit.WithUser;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
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 - System Management RESTful API")
|
||||
@Stories("System Management Resource")
|
||||
public class SystemManagementResourceTest extends AbstractIntegrationTest {
|
||||
|
||||
@Test
|
||||
@WithUser(tenantId = "mytenant", allSpPermissions = true)
|
||||
@Description("Tests that a tenant can be deletd by API.")
|
||||
public void deleteTenant() throws Exception {
|
||||
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull();
|
||||
|
||||
mvc.perform(delete("/system/admin/tenants/mytenant")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNull();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(tenantId = "mytenant", authorities = { SpPermission.DELETE_TARGET, SpPermission.DELETE_REPOSITORY,
|
||||
SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY })
|
||||
@Description("Tenant deletion is only possible for SYSTEM_ADMINs. Repository or target delete is not sufficient.")
|
||||
public void deleteTenantFailsMissingPermission() throws Exception {
|
||||
|
||||
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
|
||||
distributionSetManagement);
|
||||
assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull();
|
||||
|
||||
mvc.perform(delete("/system/admin/tenants/mytenant")).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getCachesReturnStatus200() throws Exception {
|
||||
mvc.perform(get("/system/admin/caches")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidateCachesReturnStatus200() throws Exception {
|
||||
mvc.perform(delete("/system/admin/caches")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 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.rest.resource.model;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ExceptionInfoTest {
|
||||
|
||||
@Test
|
||||
public void setterAndGetter() {
|
||||
final String knownExceptionClass = "hawkbit.test.exception.Class";
|
||||
final String knownErrorCode = "hawkbit.error.code.Known";
|
||||
final String knownMessage = "a known message";
|
||||
final List<String> knownParameters = new ArrayList<>();
|
||||
knownParameters.add("param1");
|
||||
knownParameters.add("param2");
|
||||
|
||||
final ExceptionInfo underTest = new ExceptionInfo();
|
||||
underTest.setErrorCode(knownErrorCode);
|
||||
underTest.setExceptionClass(knownExceptionClass);
|
||||
underTest.setMessage(knownMessage);
|
||||
underTest.setParameters(knownParameters);
|
||||
|
||||
assertThat(underTest.getErrorCode()).isEqualTo(knownErrorCode);
|
||||
assertThat(underTest.getExceptionClass()).isEqualTo(knownExceptionClass);
|
||||
assertThat(underTest.getMessage()).isEqualTo(knownMessage);
|
||||
assertThat(underTest.getParameters()).isEqualTo(knownParameters);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 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.rest.resource.model;
|
||||
|
||||
import static org.fest.assertions.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class PagedListTest {
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void createListWithNullContentThrowsException() {
|
||||
new PagedList<>(null, 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createListWithContent() {
|
||||
final long knownTotal = 2;
|
||||
final List<String> knownContentList = new ArrayList<>();
|
||||
knownContentList.add("content1");
|
||||
knownContentList.add("content2");
|
||||
|
||||
final PagedList<String> pagedList = new PagedList<>(knownContentList, knownTotal);
|
||||
|
||||
assertThat(pagedList.getTotal()).isEqualTo(knownTotal);
|
||||
assertThat(pagedList.getSize()).isEqualTo(knownContentList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createListWithSmallerTotalThanContentSizeIsOk() {
|
||||
final long knownTotal = 0;
|
||||
final List<String> knownContentList = new ArrayList<>();
|
||||
knownContentList.add("content1");
|
||||
knownContentList.add("content2");
|
||||
|
||||
final PagedList<String> pagedList = new PagedList<>(knownContentList, knownTotal);
|
||||
assertThat(pagedList.getTotal()).isEqualTo(knownTotal);
|
||||
assertThat(pagedList.getSize()).isEqualTo(knownContentList.size());
|
||||
|
||||
}
|
||||
}
|
||||
63
hawkbit-rest-resource/src/test/resources/application-test.properties
Executable file
63
hawkbit-rest-resource/src/test/resources/application-test.properties
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
|
||||
#
|
||||
|
||||
# used if IM profile is disabled
|
||||
security.ignored=true
|
||||
|
||||
# IM required for integration tests
|
||||
spring.profiles.active=im,suiteembedded,artifactrepository,redis
|
||||
|
||||
server.port=12222
|
||||
|
||||
spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value}
|
||||
spring.data.mongodb.port=28017
|
||||
|
||||
|
||||
# supported: H2, MYSQL
|
||||
hawkbit.server.database=H2
|
||||
hawkbit.server.database.env=TEST
|
||||
spring.main.show_banner=false
|
||||
|
||||
hawkbit.server.controller.security.authentication.header=true
|
||||
|
||||
hawkbit.server.artifact.repo.upload.maxFileSize=5MB
|
||||
|
||||
hawkbit.server.security.dos.maxStatusEntriesPerAction=100
|
||||
|
||||
hawkbit.server.security.dos.maxAttributeEntriesPerTarget=10
|
||||
|
||||
spring.jpa.database=${hawkbit.server.database}
|
||||
#spring.jpa.show-sql=true
|
||||
|
||||
|
||||
flyway.sqlMigrationSuffix=${spring.jpa.database}.sql
|
||||
|
||||
# effective DB setting
|
||||
spring.datasource.url=${${hawkbit.server.database}.spring.datasource.url}
|
||||
spring.datasource.driverClassName=${${hawkbit.server.database}.spring.datasource.driverClassName}
|
||||
spring.datasource.username=${${hawkbit.server.database}.spring.datasource.username}
|
||||
spring.datasource.password=${${hawkbit.server.database}.spring.datasource.password}
|
||||
|
||||
# H2
|
||||
##;AUTOCOMMIT=ON
|
||||
H2.spring.datasource.url=jdbc:h2:mem:sp-db;DB_CLOSE_ON_EXIT=FALSE
|
||||
#H2.spring.datasource.url=jdbc:h2:./db/sp-db;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE
|
||||
H2.spring.datasource.driverClassName=org.h2.Driver
|
||||
H2.spring.datasource.username=sa
|
||||
H2.spring.datasource.password=sa
|
||||
|
||||
# MYSQL
|
||||
MYSQL.spring.datasource.url=jdbc:mysql://localhost:3306/sp_test
|
||||
MYSQL.spring.datasource.driverClassName=org.mariadb.jdbc.Driver
|
||||
MYSQL.spring.datasource.username=root
|
||||
MYSQL.spring.datasource.password=
|
||||
|
||||
# SP Controller configuration
|
||||
hawkbit.controller.pollingTime=00:01:00
|
||||
hawkbit.controller.pollingOverdueTime=00:01:00
|
||||
Reference in New Issue
Block a user