Feature/fix sonar warnings (#1226)
* Fixed sonar warnings - "Cognitive Complexity" - "Do not use replaceAll when not using a regex" - java:S5869 - Character classes in regular expressions should not contain the same character twice - Improved bad name - Typos - reduced code duplications - Replaced hand-made wait-utility with Awaitility - Log messages - Duplicate code - Typos - Removed Thread.sleep, instead relaxed check condition - Removed use of deprecated API - Removed use of deprecated API - Added supress-warnings as I do not see a better way to write the tests - Removed Thread.sleep / redundant functionality to Awaitility - Fixed other warnings (use isZero, isEmpty, hasToString) - Removed/Reduced duplicate code - Added generics - Fixed asserts - removed: field.setAccessible(true) actually should not be needed for public static fields! - Too long constructor passes arguments in wrong order - how surprisingly... - Clean-up use of varargs arguments - Fixed regex - Fixed typos and other minor stuff - Making public constructors protected in abstract classes - Swapped expected and asserted argument - volatile not enough for syncing threads - volatile not enough for syncing threads - out-commented code - Made regex not-greedy, added tests for verification - Avoid exposure of thread-local member var Signed-off-by: Peter Vigier <Peter.Vigier@bosch.io> * Fixed Sonar warnings * License header fix Signed-off-by: Peter Vigier <Peter.Vigier@bosch.io> * License header fix #2 Signed-off-by: Peter Vigier <Peter.Vigier@bosch.io> * Fixing review findings Signed-off-by: Peter Vigier <Peter.Vigier@bosch.io> * Fixing tests - Fixed '&' usage in javadoc and typos - Fixing some warnings Signed-off-by: Peter Vigier <Peter.Vigier@bosch.io>
This commit is contained in:
@@ -12,6 +12,7 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.validation.Valid;
|
||||
@@ -130,7 +131,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("softwareModuleId") final Long softwareModuleId) {
|
||||
LOG.debug("getSoftwareModulesArtifacts({})", controllerId);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Target target = findTarget(controllerId);
|
||||
|
||||
final SoftwareModule softwareModule = controllerManagement.getSoftwareModule(softwareModuleId)
|
||||
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
|
||||
@@ -169,20 +170,16 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("fileName") final String fileName) {
|
||||
final ResponseEntity<InputStream> result;
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Target target = findTarget(controllerId);
|
||||
final SoftwareModule module = controllerManagement.getSoftwareModule(softwareModuleId)
|
||||
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
|
||||
|
||||
if (checkModule(fileName, module)) {
|
||||
LOG.warn("Softare module with id {} could not be found.", softwareModuleId);
|
||||
LOG.warn("Software module with id {} could not be found.", softwareModuleId);
|
||||
result = ResponseEntity.notFound().build();
|
||||
} else {
|
||||
|
||||
// Exception squid:S3655 - Optional access is checked in checkModule
|
||||
// subroutine
|
||||
@SuppressWarnings("squid:S3655")
|
||||
final Artifact artifact = module.getArtifactByFilename(fileName).get();
|
||||
|
||||
// Artifact presence is ensured in 'checkModule'
|
||||
final Artifact artifact = module.getArtifactByFilename(fileName).orElseThrow(NoSuchElementException::new);
|
||||
final DbArtifact file = artifactManagement
|
||||
.loadArtifactBinary(artifact.getSha1Hash(), module.getId(), module.isEncrypted())
|
||||
.orElseThrow(() -> new ArtifactBinaryNotFoundException(artifact.getSha1Hash()));
|
||||
@@ -239,7 +236,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("controllerId") final String controllerId,
|
||||
@PathVariable("softwareModuleId") final Long softwareModuleId,
|
||||
@PathVariable("fileName") final String fileName) {
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Target target = findTarget(controllerId);
|
||||
|
||||
final SoftwareModule module = controllerManagement.getSoftwareModule(softwareModuleId)
|
||||
.orElseThrow(() -> new EntityNotFoundException(SoftwareModule.class, softwareModuleId));
|
||||
@@ -274,9 +271,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) {
|
||||
LOG.debug("getControllerBasedeploymentAction({},{})", controllerId, resource);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
verifyActionAssignedToTarget(target, action);
|
||||
final Target target = findTarget(controllerId);
|
||||
final Action action = findActionForTarget(actionId, target);
|
||||
|
||||
checkAndCancelExpiredAction(action);
|
||||
|
||||
@@ -296,7 +292,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
}
|
||||
|
||||
private static HandlingType calculateDownloadType(final Action action) {
|
||||
if (action.isDownloadOnly() || action.isForce()) {
|
||||
if (action.isDownloadOnly() || action.isForcedOrTimeForced()) {
|
||||
return HandlingType.FORCED;
|
||||
}
|
||||
return HandlingType.ATTEMPT;
|
||||
@@ -325,9 +321,9 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("actionId") @NotEmpty final Long actionId) {
|
||||
LOG.debug("provideBasedeploymentActionFeedback for target [{},{}]: {}", controllerId, actionId, feedback);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
verifyActionAssignedToTarget(target, action);
|
||||
final Target target = findTarget(controllerId);
|
||||
final Action action = findActionForTarget(actionId, target);
|
||||
|
||||
|
||||
if (!action.isActive()) {
|
||||
LOG.warn("Updating action {} with feedback {} not possible since action not active anymore.",
|
||||
@@ -342,7 +338,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
}
|
||||
|
||||
private ActionStatusCreate generateUpdateStatus(final DdiActionFeedback feedback, final String controllerId,
|
||||
final Long actionid) {
|
||||
final Long actionId) {
|
||||
|
||||
final List<String> messages = new ArrayList<>();
|
||||
|
||||
@@ -353,38 +349,38 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
Status status;
|
||||
switch (feedback.getStatus().getExecution()) {
|
||||
case CANCELED:
|
||||
LOG.debug("Controller confirmed cancel (actionid: {}, controllerId: {}) as we got {} report.", actionid,
|
||||
LOG.debug("Controller confirmed cancel (actionId: {}, controllerId: {}) as we got {} report.", actionId,
|
||||
controllerId, feedback.getStatus().getExecution());
|
||||
status = Status.CANCELED;
|
||||
addMessageIfEmpty("Target confirmed cancelation.", messages);
|
||||
addMessageIfEmpty("Target confirmed cancellation.", messages);
|
||||
break;
|
||||
case REJECTED:
|
||||
LOG.info("Controller reported internal error (actionid: {}, controllerId: {}) as we got {} report.",
|
||||
actionid, controllerId, feedback.getStatus().getExecution());
|
||||
LOG.info("Controller reported internal error (actionId: {}, controllerId: {}) as we got {} report.",
|
||||
actionId, controllerId, feedback.getStatus().getExecution());
|
||||
status = Status.WARNING;
|
||||
addMessageIfEmpty("Target REJECTED update", messages);
|
||||
break;
|
||||
case CLOSED:
|
||||
status = handleClosedCase(feedback, controllerId, actionid, messages);
|
||||
status = handleClosedCase(feedback, controllerId, actionId, messages);
|
||||
break;
|
||||
case DOWNLOAD:
|
||||
LOG.debug("Controller confirmed status of download (actionId: {}, controllerId: {}) as we got {} report.",
|
||||
actionid, controllerId, feedback.getStatus().getExecution());
|
||||
actionId, controllerId, feedback.getStatus().getExecution());
|
||||
status = Status.DOWNLOAD;
|
||||
addMessageIfEmpty("Target confirmed download start", messages);
|
||||
break;
|
||||
case DOWNLOADED:
|
||||
LOG.debug("Controller confirmed download (actionId: {}, controllerId: {}) as we got {} report.", actionid,
|
||||
LOG.debug("Controller confirmed download (actionId: {}, controllerId: {}) as we got {} report.", actionId,
|
||||
controllerId, feedback.getStatus().getExecution());
|
||||
status = Status.DOWNLOADED;
|
||||
addMessageIfEmpty("Target confirmed download finished", messages);
|
||||
break;
|
||||
default:
|
||||
status = handleDefaultCase(feedback, controllerId, actionid, messages);
|
||||
status = handleDefaultCase(feedback, controllerId, actionId, messages);
|
||||
break;
|
||||
}
|
||||
|
||||
return entityFactory.actionStatus().create(actionid).status(status).messages(messages);
|
||||
return entityFactory.actionStatus().create(actionId).status(status).messages(messages);
|
||||
}
|
||||
|
||||
private static void addMessageIfEmpty(final String text, final List<String> messages) {
|
||||
@@ -393,20 +389,20 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
}
|
||||
}
|
||||
|
||||
private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid,
|
||||
private Status handleDefaultCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId,
|
||||
final List<String> messages) {
|
||||
Status status;
|
||||
LOG.debug("Controller reported intermediate status (actionid: {}, controllerId: {}) as we got {} report.",
|
||||
actionid, controllerId, feedback.getStatus().getExecution());
|
||||
LOG.debug("Controller reported intermediate status (actionId: {}, controllerId: {}) as we got {} report.",
|
||||
actionId, controllerId, feedback.getStatus().getExecution());
|
||||
status = Status.RUNNING;
|
||||
addMessageIfEmpty("Target reported " + feedback.getStatus().getExecution(), messages);
|
||||
return status;
|
||||
}
|
||||
|
||||
private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionid,
|
||||
private Status handleClosedCase(final DdiActionFeedback feedback, final String controllerId, final Long actionId,
|
||||
final List<String> messages) {
|
||||
Status status;
|
||||
LOG.debug("Controller reported closed (actionid: {}, controllerId: {}) as we got {} report.", actionid,
|
||||
LOG.debug("Controller reported closed (actionId: {}, controllerId: {}) as we got {} report.", actionId,
|
||||
controllerId, feedback.getStatus().getExecution());
|
||||
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) {
|
||||
status = Status.ERROR;
|
||||
@@ -432,9 +428,9 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("actionId") @NotEmpty final Long actionId) {
|
||||
LOG.debug("getControllerCancelAction({})", controllerId);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
verifyActionAssignedToTarget(target, action);
|
||||
final Target target = findTarget(controllerId);
|
||||
final Action action = findActionForTarget(actionId, target);
|
||||
|
||||
|
||||
if (action.isCancelingOrCanceled()) {
|
||||
final DdiCancel cancel = new DdiCancel(String.valueOf(action.getId()),
|
||||
@@ -443,7 +439,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
LOG.debug("Found an active CancelAction for target {}. returning cancel: {}", controllerId, cancel);
|
||||
|
||||
controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX
|
||||
+ "Target retrieved cancel action and should start now the cancelation.");
|
||||
+ "Target retrieved cancel action and should start now the cancellation.");
|
||||
|
||||
return new ResponseEntity<>(cancel, HttpStatus.OK);
|
||||
}
|
||||
@@ -458,12 +454,11 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@PathVariable("actionId") @NotEmpty final Long actionId) {
|
||||
LOG.debug("provideCancelActionFeedback for target [{}]: {}", controllerId, feedback);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
verifyActionAssignedToTarget(target, action);
|
||||
final Target target = findTarget(controllerId);
|
||||
final Action action = findActionForTarget(actionId, target);
|
||||
|
||||
controllerManagement
|
||||
.addCancelActionStatus(generateActionCancelStatus(feedback, target, actionId, entityFactory));
|
||||
.addCancelActionStatus(generateActionCancelStatus(feedback, target, action.getId(), entityFactory));
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@@ -473,9 +468,8 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
@RequestParam(value = "actionHistory", defaultValue = DdiRestConstants.NO_ACTION_HISTORY) final Integer actionHistoryMessageCount) {
|
||||
LOG.debug("getControllerInstalledAction({})", controllerId);
|
||||
|
||||
final Target target = findTargetWithExceptionIfNotFound(controllerId);
|
||||
final Action action = findActionWithExceptionIfNotFound(actionId);
|
||||
verifyActionAssignedToTarget(target, action);
|
||||
final Target target = findTarget(controllerId);
|
||||
final Action action = findActionForTarget(actionId, target);
|
||||
|
||||
if (action.isActive() || action.isCancelingOrCanceled()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
@@ -511,19 +505,19 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
}
|
||||
|
||||
private static ActionStatusCreate generateActionCancelStatus(final DdiActionFeedback feedback, final Target target,
|
||||
final Long actionid, final EntityFactory entityFactory) {
|
||||
final Long actionId, final EntityFactory entityFactory) {
|
||||
|
||||
final List<String> messages = new ArrayList<>();
|
||||
Status status;
|
||||
switch (feedback.getStatus().getExecution()) {
|
||||
case CANCELED:
|
||||
status = handleCaseCancelCanceled(feedback, target, actionid, messages);
|
||||
status = handleCaseCancelCanceled(feedback, target, actionId, messages);
|
||||
break;
|
||||
case REJECTED:
|
||||
LOG.info("Target rejected the cancelation request (actionid: {}, controllerId: {}).", actionid,
|
||||
LOG.info("Target rejected the cancellation request (actionId: {}, controllerId: {}).", actionId,
|
||||
target.getControllerId());
|
||||
status = Status.CANCEL_REJECTED;
|
||||
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancelation request.");
|
||||
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target rejected the cancellation request.");
|
||||
break;
|
||||
case CLOSED:
|
||||
status = handleCancelClosedCase(feedback, messages);
|
||||
@@ -537,7 +531,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
messages.addAll(feedback.getStatus().getDetails());
|
||||
}
|
||||
|
||||
return entityFactory.actionStatus().create(actionid).status(status).messages(messages);
|
||||
return entityFactory.actionStatus().create(actionId).status(status).messages(messages);
|
||||
|
||||
}
|
||||
|
||||
@@ -545,41 +539,44 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
Status status;
|
||||
if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) {
|
||||
status = Status.ERROR;
|
||||
addMessageIfEmpty("Target was not able to complete cancelation", messages);
|
||||
addMessageIfEmpty("Target was not able to complete cancellation", messages);
|
||||
} else {
|
||||
status = Status.CANCELED;
|
||||
addMessageIfEmpty("Cancelation confirmed", messages);
|
||||
addMessageIfEmpty("Cancellation confirmed", messages);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
private static Status handleCaseCancelCanceled(final DdiActionFeedback feedback, final Target target,
|
||||
final Long actionid, final List<String> messages) {
|
||||
final Long actionId, final List<String> messages) {
|
||||
Status status;
|
||||
LOG.error(
|
||||
"Target reported cancel for a cancel which is not supported by the server (actionid: {}, controllerId: {}) as we got {} report.",
|
||||
actionid, target.getControllerId(), feedback.getStatus().getExecution());
|
||||
"Target reported cancel for a cancel which is not supported by the server (actionId: {}, controllerId: {}) as we got {} report.",
|
||||
actionId, target.getControllerId(), feedback.getStatus().getExecution());
|
||||
status = Status.WARNING;
|
||||
messages.add(RepositoryConstants.SERVER_MESSAGE_PREFIX
|
||||
+ "Target reported cancel for a cancel which is not supported by the server.");
|
||||
return status;
|
||||
}
|
||||
|
||||
private Target findTargetWithExceptionIfNotFound(final String controllerId) {
|
||||
private Target findTarget(final String controllerId) {
|
||||
return controllerManagement.getByControllerId(controllerId)
|
||||
.orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId));
|
||||
}
|
||||
|
||||
private Action findActionWithExceptionIfNotFound(final Long actionId) {
|
||||
return controllerManagement.findActionWithDetails(actionId)
|
||||
private Action findActionForTarget(final Long actionId, final Target target) {
|
||||
final Action action = controllerManagement.findActionWithDetails(actionId)
|
||||
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
|
||||
return verifyActionBelongsToTarget(action, target);
|
||||
}
|
||||
|
||||
private void verifyActionAssignedToTarget(final Target target, final Action action) {
|
||||
private Action verifyActionBelongsToTarget(Action action, Target target) {
|
||||
if (!action.getTarget().getId().equals(target.getId())) {
|
||||
LOG.warn(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId());
|
||||
throw new EntityNotFoundException(Action.class, action.getId());
|
||||
LOG.debug(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId());
|
||||
throw new EntityNotFoundException(
|
||||
"Not a valid action (" + action.getId() + ") for target: " + target.getControllerId(), null);
|
||||
}
|
||||
return action;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -594,7 +591,7 @@ public class DdiRootController implements DdiRootControllerRestApi {
|
||||
try {
|
||||
controllerManagement.cancelAction(action.getId());
|
||||
} catch (final CancelActionNotAllowedException e) {
|
||||
LOG.info("Cancel action not allowed exception :{}", e);
|
||||
LOG.info("Cancel action not allowed: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,11 +45,11 @@ import io.qameta.allure.Story;
|
||||
*/
|
||||
@Feature("Component Tests - Direct Device Integration API")
|
||||
@Story("Cancel Action Resource")
|
||||
public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests that the cancel action resource can be used with CBOR.")
|
||||
public void cancelActionCbor() throws Exception {
|
||||
void cancelActionCbor() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
testdataFactory.createTarget();
|
||||
final Long actionId = getFirstAssignedActionId(
|
||||
@@ -75,7 +75,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@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 {
|
||||
void rootRsCancelActionButContinueAnyway() throws Exception {
|
||||
// prepare test data
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
final Target savedTarget = testdataFactory.createTarget();
|
||||
@@ -130,14 +130,14 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test for cancel operation of a update action.")
|
||||
public void rootRsCancelAction() throws Exception {
|
||||
void rootRsCancelAction() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
final Target savedTarget = testdataFactory.createTarget();
|
||||
|
||||
final Long actionId = getFirstAssignedActionId(
|
||||
assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
|
||||
|
||||
long current = System.currentTimeMillis();
|
||||
final long timeBeforeFirstPoll = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
|
||||
TestdataFactory.DEFAULT_CONTROLLER_ID).accept(MediaTypes.HAL_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
@@ -146,13 +146,9 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
.andExpect(jsonPath("$._links.deploymentBase.href",
|
||||
startsWith("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
|
||||
+ TestdataFactory.DEFAULT_CONTROLLER_ID + "/deploymentBase/" + actionId)));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
final long timeAfterFirstPoll = System.currentTimeMillis() + 1;
|
||||
assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
.isBetween(timeBeforeFirstPoll, timeAfterFirstPoll);
|
||||
|
||||
// Retrieved is reported
|
||||
|
||||
@@ -171,7 +167,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
assertThat(activeActionsByTarget).hasSize(1);
|
||||
assertThat(activeActionsByTarget.get(0).getStatus()).isEqualTo(Status.CANCELING);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
final long timeBefore2ndPoll = System.currentTimeMillis();
|
||||
mvc.perform(get("/{tenant}/controller/v1/{controller}", tenantAware.getCurrentTenant(),
|
||||
TestdataFactory.DEFAULT_CONTROLLER_ID)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
@@ -179,17 +175,10 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
.andExpect(jsonPath("$._links.cancelAction.href",
|
||||
equalTo("http://localhost/" + tenantAware.getCurrentTenant() + "/controller/v1/"
|
||||
+ TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/" + cancelAction.getId())));
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
final long timeAfter2ndPoll = System.currentTimeMillis() + 1;
|
||||
assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
.isBetween(timeBefore2ndPoll, timeAfter2ndPoll);
|
||||
|
||||
current = System.currentTimeMillis();
|
||||
assertThat(targetManagement.getByControllerID(TestdataFactory.DEFAULT_CONTROLLER_ID).get().getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
mvc.perform(get("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
|
||||
+ cancelAction.getId(), tenantAware.getCurrentTenant()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
@@ -208,7 +197,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
activeActionsByTarget = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())
|
||||
.getContent();
|
||||
assertThat(activeActionsByTarget).hasSize(0);
|
||||
assertThat(activeActionsByTarget).isEmpty();
|
||||
final Action canceledAction = deploymentManagement.findAction(cancelAction.getId()).get();
|
||||
assertThat(canceledAction.isActive()).isFalse();
|
||||
assertThat(canceledAction.getStatus()).isEqualTo(Status.CANCELED);
|
||||
@@ -217,7 +206,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests various bad requests and if the server handles them as expected.")
|
||||
public void badCancelAction() throws Exception {
|
||||
void badCancelAction() throws Exception {
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/1",
|
||||
@@ -258,7 +247,7 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Tests the feedback channel of the cancel operation.")
|
||||
public void rootRsCancelActionFeedback() throws Exception {
|
||||
void rootRsCancelActionFeedback() throws Exception {
|
||||
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
|
||||
@@ -327,12 +316,12 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(8);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the feeback chanel of for multiple open cancel operations on the same target.")
|
||||
public void multipleCancelActionFeedback() throws Exception {
|
||||
void multipleCancelActionFeedback() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("", true);
|
||||
final DistributionSet ds2 = testdataFactory.createDistributionSet("2", true);
|
||||
final DistributionSet ds3 = testdataFactory.createDistributionSet("3", true);
|
||||
@@ -443,13 +432,13 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
assertThat(deploymentManagement.countActionStatusAll()).isEqualTo(13);
|
||||
|
||||
// final status
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).hasSize(0);
|
||||
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId())).isEmpty();
|
||||
assertThat(deploymentManagement.countActionsByTarget(savedTarget.getControllerId())).isEqualTo(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the feeback channel closing for too many feedbacks, i.e. denial of service prevention.")
|
||||
public void tooMuchCancelActionFeedback() throws Exception {
|
||||
void tooMuchCancelActionFeedback() throws Exception {
|
||||
testdataFactory.createTarget();
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
|
||||
@@ -477,9 +466,9 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("test the correct rejection of various invalid feedback requests")
|
||||
public void badCancelActionFeedback() throws Exception {
|
||||
void badCancelActionFeedback() throws Exception {
|
||||
final Action cancelAction = createCancelAction(TestdataFactory.DEFAULT_CONTROLLER_ID);
|
||||
final Action cancelAction2 = createCancelAction("4715");
|
||||
createCancelAction("4715");
|
||||
|
||||
// not allowed methods
|
||||
mvc.perform(put("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/cancelAction/"
|
||||
@@ -524,12 +513,11 @@ public class DdiCancelActionTest extends AbstractDDiApiIntegrationTest {
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
|
||||
// finally get it right :)
|
||||
// finaly, get it right :)
|
||||
mvc.perform(post("/{tenant}/controller/v1/" + TestdataFactory.DEFAULT_CONTROLLER_ID + "/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());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
package org.eclipse.hawkbit.ddi.rest.resource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.eclipse.hawkbit.repository.test.util.TargetTestData.ATTRIBUTE_KEY_TOO_LONG;
|
||||
import static org.eclipse.hawkbit.repository.test.util.TargetTestData.ATTRIBUTE_KEY_VALID;
|
||||
import static org.eclipse.hawkbit.repository.test.util.TargetTestData.ATTRIBUTE_VALUE_TOO_LONG;
|
||||
import static org.eclipse.hawkbit.repository.test.util.TargetTestData.ATTRIBUTE_VALUE_VALID;
|
||||
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;
|
||||
@@ -21,6 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import org.eclipse.hawkbit.ddi.rest.api.DdiRestConstants;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
@@ -40,41 +45,39 @@ import io.qameta.allure.Description;
|
||||
import io.qameta.allure.Feature;
|
||||
import io.qameta.allure.Step;
|
||||
import io.qameta.allure.Story;
|
||||
|
||||
/**
|
||||
* Test config data from the controller.
|
||||
*/
|
||||
@ActiveProfiles({ "im", "test" })
|
||||
@Feature("Component Tests - Direct Device Integration API")
|
||||
@Story("Config Data Resource")
|
||||
public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
private static final String KEY_TOO_LONG = generateRandomStringWithLength(Target.CONTROLLER_ATTRIBUTE_KEY_SIZE + 1);
|
||||
private static final String KEY_VALID = generateRandomStringWithLength(Target.CONTROLLER_ATTRIBUTE_KEY_SIZE);
|
||||
private static final String VALUE_TOO_LONG = generateRandomStringWithLength(
|
||||
Target.CONTROLLER_ATTRIBUTE_VALUE_SIZE + 1);
|
||||
private static final String VALUE_VALID = generateRandomStringWithLength(Target.CONTROLLER_ATTRIBUTE_VALUE_SIZE);
|
||||
public static final String TARGET1_ID = "4717";
|
||||
public static final String TARGET1_CONFIGDATA_PATH = "/{tenant}/controller/v1/" + TARGET1_ID + "/configData";
|
||||
public static final String TARGET2_ID = "4718";
|
||||
public static final String TARGET2_CONFIGDATA_PATH = "/{tenant}/controller/v1/" + TARGET2_ID + "/configData";
|
||||
|
||||
@Test
|
||||
@Description("Verify that config data can be uploaded as CBOR")
|
||||
public void putConfigDataAsCbor() throws Exception {
|
||||
testdataFactory.createTarget("4717");
|
||||
void putConfigDataAsCbor() throws Exception {
|
||||
testdataFactory.createTarget(TARGET1_ID);
|
||||
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put(KEY_VALID, VALUE_VALID);
|
||||
attributes.put(ATTRIBUTE_KEY_VALID, ATTRIBUTE_VALUE_VALID);
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(jsonToCbor(JsonBuilder.configData(attributes).toString()))
|
||||
.contentType(DdiRestConstants.MEDIA_TYPE_CBOR)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
assertThat(targetManagement.getControllerAttributes("4717")).isEqualTo(attributes);
|
||||
assertThat(targetManagement.getControllerAttributes(TARGET1_ID)).isEqualTo(attributes);
|
||||
}
|
||||
|
||||
@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.")
|
||||
@SuppressWarnings("squid:S2925")
|
||||
public void requestConfigDataIfEmpty() throws Exception {
|
||||
void requestConfigDataIfEmpty() throws Exception {
|
||||
final Target savedTarget = testdataFactory.createTarget("4712");
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
@@ -88,9 +91,11 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
Thread.sleep(1); // is required: otherwise processing the next line is
|
||||
// often too fast and
|
||||
// the following assert will fail
|
||||
assertThat(targetManagement.getByControllerID("4712").get().getLastTargetQuery())
|
||||
assertThat(targetManagement.getByControllerID("4712").orElseThrow(NoSuchElementException::new)
|
||||
.getLastTargetQuery())
|
||||
.isLessThanOrEqualTo(System.currentTimeMillis());
|
||||
assertThat(targetManagement.getByControllerID("4712").get().getLastTargetQuery())
|
||||
assertThat(targetManagement.getByControllerID("4712").orElseThrow(NoSuchElementException::new)
|
||||
.getLastTargetQuery())
|
||||
.isGreaterThanOrEqualTo(current);
|
||||
|
||||
final Map<String, String> attributes = Maps.newHashMapWithExpectedSize(1);
|
||||
@@ -113,44 +118,44 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
@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 {
|
||||
testdataFactory.createTarget("4717");
|
||||
void putConfigData() throws Exception {
|
||||
testdataFactory.createTarget(TARGET1_ID);
|
||||
|
||||
// initial
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put(KEY_VALID, VALUE_VALID);
|
||||
attributes.put(ATTRIBUTE_KEY_VALID, ATTRIBUTE_VALUE_VALID);
|
||||
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.getControllerAttributes("4717")).isEqualTo(attributes);
|
||||
assertThat(targetManagement.getControllerAttributes(TARGET1_ID)).isEqualTo(attributes);
|
||||
|
||||
// update
|
||||
attributes.put("sdsds", "123412");
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
assertThat(targetManagement.getControllerAttributes("4717")).isEqualTo(attributes);
|
||||
assertThat(targetManagement.getControllerAttributes(TARGET1_ID)).isEqualTo(attributes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "upload quota is enforced to protect the server from malicious attempts.")
|
||||
public void putTooMuchConfigData() throws Exception {
|
||||
testdataFactory.createTarget("4717");
|
||||
void putTooMuchConfigData() throws Exception {
|
||||
testdataFactory.createTarget(TARGET1_ID);
|
||||
|
||||
// initial
|
||||
Map<String, String> attributes = new HashMap<>();
|
||||
for (int i = 0; i < quotaManagement.getMaxAttributeEntriesPerTarget(); i++) {
|
||||
attributes.put("dsafsdf" + i, "sdsds" + i);
|
||||
}
|
||||
mvc.perform(put("/{tenant}/controller/v1/4717/configData", tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).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())
|
||||
mvc.perform(put(TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(AssignmentQuotaExceededException.class.getName())))
|
||||
@@ -161,7 +166,7 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
@Test
|
||||
@Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) "
|
||||
+ "resource behaves as expected in case of invalid request attempts.")
|
||||
public void badConfigData() throws Exception {
|
||||
void badConfigData() throws Exception {
|
||||
testdataFactory.createTarget("4712");
|
||||
|
||||
// not allowed methods
|
||||
@@ -195,23 +200,17 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Verifies that invalid config data attributes are handled correctly.")
|
||||
public void putConfigDataWithInvalidAttributes() throws Exception {
|
||||
void putConfigDataWithInvalidAttributes() throws Exception {
|
||||
// create a target
|
||||
final String controllerId = "4718";
|
||||
testdataFactory.createTarget(controllerId);
|
||||
final String configDataPath = "/{tenant}/controller/v1/" + controllerId + "/configData";
|
||||
|
||||
putAndVerifyConfigDataWithKeyTooLong(configDataPath);
|
||||
|
||||
putAndVerifyConfigDataWithValueTooLong(configDataPath);
|
||||
testdataFactory.createTarget(TARGET2_ID);
|
||||
putAndVerifyConfigDataWithKeyTooLong();
|
||||
putAndVerifyConfigDataWithValueTooLong();
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putAndVerifyConfigDataWithKeyTooLong(final String configDataPath) throws Exception {
|
||||
|
||||
final Map<String, String> attributes = Collections.singletonMap(KEY_TOO_LONG, VALUE_VALID);
|
||||
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
private void putAndVerifyConfigDataWithKeyTooLong() throws Exception {
|
||||
final Map<String, String> attributes = Collections.singletonMap(ATTRIBUTE_KEY_TOO_LONG, ATTRIBUTE_VALUE_VALID);
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET2_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(InvalidTargetAttributeException.class.getName())))
|
||||
@@ -219,11 +218,9 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putAndVerifyConfigDataWithValueTooLong(final String configDataPath) throws Exception {
|
||||
|
||||
final Map<String, String> attributes = Collections.singletonMap(KEY_VALID, VALUE_TOO_LONG);
|
||||
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
private void putAndVerifyConfigDataWithValueTooLong() throws Exception {
|
||||
final Map<String, String> attributes = Collections.singletonMap(ATTRIBUTE_KEY_VALID, ATTRIBUTE_VALUE_TOO_LONG);
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET2_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(InvalidTargetAttributeException.class.getName())))
|
||||
@@ -232,139 +229,133 @@ public class DdiConfigDataTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Verify that config data (device attributes) can be updated by the controller using different update modes (merge, replace, remove).")
|
||||
public void putConfigDataWithDifferentUpdateModes() throws Exception {
|
||||
void putConfigDataWithDifferentUpdateModes() throws Exception {
|
||||
|
||||
// create a target
|
||||
final String controllerId = "4717";
|
||||
testdataFactory.createTarget(controllerId);
|
||||
final String configDataPath = "/{tenant}/controller/v1/" + controllerId + "/configData";
|
||||
testdataFactory.createTarget(TARGET1_ID);
|
||||
|
||||
// no update mode
|
||||
putConfigDataWithoutUpdateMode(controllerId, configDataPath);
|
||||
putConfigDataWithoutUpdateMode();
|
||||
|
||||
// update mode REPLACE
|
||||
putConfigDataWithUpdateModeReplace(controllerId, configDataPath);
|
||||
putConfigDataWithUpdateModeReplace();
|
||||
|
||||
// update mode MERGE
|
||||
putConfigDataWithUpdateModeMerge(controllerId, configDataPath);
|
||||
putConfigDataWithUpdateModeMerge();
|
||||
|
||||
// update mode REMOVE
|
||||
putConfigDataWithUpdateModeRemove(controllerId, configDataPath);
|
||||
putConfigDataWithUpdateModeRemove();
|
||||
|
||||
// invalid update mode
|
||||
putConfigDataWithInvalidUpdateMode(configDataPath);
|
||||
|
||||
putConfigDataWithInvalidUpdateMode();
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putConfigDataWithInvalidUpdateMode(final String configDataPath) throws Exception {
|
||||
|
||||
private void putConfigDataWithInvalidUpdateMode() throws Exception {
|
||||
// create some attriutes
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("k0", "v0");
|
||||
attributes.put("k1", "v1");
|
||||
|
||||
// use an invalid update mode
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes, "KJHGKJHGKJHG").toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putConfigDataWithUpdateModeRemove(final String controllerId, final String configDataPath)
|
||||
throws Exception {
|
||||
|
||||
private void putConfigDataWithUpdateModeRemove() throws Exception {
|
||||
// get the current attributes
|
||||
final int previousSize = targetManagement.getControllerAttributes(controllerId).size();
|
||||
final int previousSize = targetManagement.getControllerAttributes(DdiConfigDataTest.TARGET1_ID).size();
|
||||
|
||||
// update the attributes using update mode REMOVE
|
||||
final Map<String, String> removeAttributes = new HashMap<>();
|
||||
removeAttributes.put("k1", "foo");
|
||||
removeAttributes.put("k3", "bar");
|
||||
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(removeAttributes, "remove").toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// verify attribute removal
|
||||
final Map<String, String> updatedAttributes = targetManagement.getControllerAttributes(controllerId);
|
||||
assertThat(updatedAttributes.size()).isEqualTo(previousSize - 2);
|
||||
final Map<String, String> updatedAttributes = targetManagement
|
||||
.getControllerAttributes(DdiConfigDataTest.TARGET1_ID);
|
||||
assertThat(updatedAttributes).hasSize(previousSize - 2);
|
||||
assertThat(updatedAttributes).doesNotContainKeys("k1", "k3");
|
||||
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putConfigDataWithUpdateModeMerge(final String controllerId, final String configDataPath)
|
||||
private void putConfigDataWithUpdateModeMerge()
|
||||
throws Exception {
|
||||
|
||||
// get the current attributes
|
||||
final Map<String, String> attributes = new HashMap<>(targetManagement.getControllerAttributes(controllerId));
|
||||
final Map<String, String> attributes = new HashMap<>(
|
||||
targetManagement.getControllerAttributes(DdiConfigDataTest.TARGET1_ID));
|
||||
|
||||
// update the attributes using update mode MERGE
|
||||
final Map<String, String> mergeAttributes = new HashMap<>();
|
||||
mergeAttributes.put("k1", "v1_modified_again");
|
||||
mergeAttributes.put("k4", "v4");
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(mergeAttributes, "merge").toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// verify attribute merge
|
||||
final Map<String, String> updatedAttributes = targetManagement.getControllerAttributes(controllerId);
|
||||
assertThat(updatedAttributes.size()).isEqualTo(4);
|
||||
final Map<String, String> updatedAttributes = targetManagement
|
||||
.getControllerAttributes(DdiConfigDataTest.TARGET1_ID);
|
||||
assertThat(updatedAttributes).hasSize(4);
|
||||
assertThat(updatedAttributes).containsAllEntriesOf(mergeAttributes);
|
||||
assertThat(updatedAttributes.get("k1")).isEqualTo("v1_modified_again");
|
||||
assertThat(updatedAttributes).containsEntry("k1", "v1_modified_again");
|
||||
attributes.keySet().forEach(assertThat(updatedAttributes)::containsKey);
|
||||
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putConfigDataWithUpdateModeReplace(final String controllerId, final String configDataPath)
|
||||
private void putConfigDataWithUpdateModeReplace()
|
||||
throws Exception {
|
||||
|
||||
// get the current attributes
|
||||
final Map<String, String> attributes = new HashMap<>(targetManagement.getControllerAttributes(controllerId));
|
||||
final Map<String, String> attributes = new HashMap<>(
|
||||
targetManagement.getControllerAttributes(DdiConfigDataTest.TARGET1_ID));
|
||||
|
||||
// update the attributes using update mode REPLACE
|
||||
final Map<String, String> replacementAttributes = new HashMap<>();
|
||||
replacementAttributes.put("k1", "v1_modified");
|
||||
replacementAttributes.put("k2", "v2");
|
||||
replacementAttributes.put("k3", "v3");
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(replacementAttributes, "replace").toString())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// verify attribute replacement
|
||||
final Map<String, String> updatedAttributes = targetManagement.getControllerAttributes(controllerId);
|
||||
assertThat(updatedAttributes.size()).isEqualTo(replacementAttributes.size());
|
||||
final Map<String, String> updatedAttributes = targetManagement
|
||||
.getControllerAttributes(DdiConfigDataTest.TARGET1_ID);
|
||||
assertThat(updatedAttributes).hasSize(replacementAttributes.size());
|
||||
assertThat(updatedAttributes).containsAllEntriesOf(replacementAttributes);
|
||||
assertThat(updatedAttributes.get("k1")).isEqualTo("v1_modified");
|
||||
assertThat(updatedAttributes).containsEntry("k1", "v1_modified");
|
||||
attributes.entrySet().forEach(assertThat(updatedAttributes)::doesNotContain);
|
||||
|
||||
}
|
||||
|
||||
@Step
|
||||
private void putConfigDataWithoutUpdateMode(final String controllerId, final String configDataPath)
|
||||
private void putConfigDataWithoutUpdateMode()
|
||||
throws Exception {
|
||||
|
||||
// create some attriutes
|
||||
final Map<String, String> attributes = new HashMap<>();
|
||||
attributes.put("k0", "v0");
|
||||
attributes.put("k1", "v1");
|
||||
|
||||
// set the initial attributes
|
||||
mvc.perform(put(configDataPath, tenantAware.getCurrentTenant())
|
||||
mvc.perform(put(DdiConfigDataTest.TARGET1_CONFIGDATA_PATH, tenantAware.getCurrentTenant())
|
||||
.content(JsonBuilder.configData(attributes).toString()).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
|
||||
// verify the initial parameters
|
||||
final Map<String, String> updatedAttributes = targetManagement.getControllerAttributes(controllerId);
|
||||
assertThat(updatedAttributes.size()).isEqualTo(attributes.size());
|
||||
assertThat(updatedAttributes).containsAllEntriesOf(attributes);
|
||||
|
||||
final Map<String, String> updatedAttributes = targetManagement
|
||||
.getControllerAttributes(DdiConfigDataTest.TARGET1_ID);
|
||||
assertThat(updatedAttributes).containsExactlyEntriesOf(attributes);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ import io.qameta.allure.Story;
|
||||
*/
|
||||
@Feature("Component Tests - Direct Device Integration API")
|
||||
@Story("Root Poll Resource")
|
||||
public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
private static final String TARGET_COMPLETED_INSTALLATION_MSG = "Target completed installation.";
|
||||
private static final String TARGET_PROCEEDING_INSTALLATION_MSG = "Target proceeding installation.";
|
||||
@@ -87,7 +87,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensure that the root poll resource is available as CBOR")
|
||||
public void rootPollResourceCbor() throws Exception {
|
||||
void rootPollResourceCbor() throws Exception {
|
||||
mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), 4711)
|
||||
.accept(DdiRestConstants.MEDIA_TYPE_CBOR)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(content().contentType(DdiRestConstants.MEDIA_TYPE_CBOR)).andExpect(status().isOk());
|
||||
@@ -95,7 +95,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the API returns JSON when no Accept header is specified by the client.")
|
||||
public void apiReturnsJSONByDefault() throws Exception {
|
||||
void apiReturnsJSONByDefault() throws Exception {
|
||||
final MvcResult result = mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), 4711))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON)).andReturn();
|
||||
@@ -113,7 +113,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = TargetPollEvent.class, count = 1),
|
||||
@Expect(type = DistributionSetTypeCreatedEvent.class, count = 3),
|
||||
@Expect(type = SoftwareModuleTypeCreatedEvent.class, count = 2) })
|
||||
public void targetCannotBeRegisteredIfTenantDoesNotExistsButWhenExists() throws Exception {
|
||||
void targetCannotBeRegisteredIfTenantDoesNotExistsButWhenExists() throws Exception {
|
||||
|
||||
mvc.perform(get("/default-tenant/", tenantAware.getCurrentTenant())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
@@ -137,14 +137,13 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
SpPermission.CREATE_TARGET }, allSpPermissions = false)
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
|
||||
public void targetPollDoesNotModifyAuditData() throws Exception {
|
||||
void targetPollDoesNotModifyAuditData() throws Exception {
|
||||
// create target first with "knownPrincipal" user and audit data
|
||||
final String knownTargetControllerId = "target1";
|
||||
final String knownCreatedBy = "knownPrincipal";
|
||||
testdataFactory.createTarget(knownTargetControllerId);
|
||||
final Target findTargetByControllerID = targetManagement.getByControllerID(knownTargetControllerId).get();
|
||||
assertThat(findTargetByControllerID.getCreatedBy()).isEqualTo(knownCreatedBy);
|
||||
assertThat(findTargetByControllerID.getCreatedAt()).isNotNull();
|
||||
|
||||
// make a poll, audit information should not be changed, run as
|
||||
// controller principal!
|
||||
@@ -165,7 +164,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Test
|
||||
@Description("Ensures that server returns a not found response in case of empty controller ID.")
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
|
||||
public void rootRsWithoutId() throws Exception {
|
||||
void rootRsWithoutId() throws Exception {
|
||||
mvc.perform(get("/controller/v1/")).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@@ -173,7 +172,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Description("Ensures that the system creates a new target in plug and play manner, i.e. target is authenticated but does not exist yet.")
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetPollEvent.class, count = 1) })
|
||||
public void rootRsPlugAndPlay() throws Exception {
|
||||
void rootRsPlugAndPlay() throws Exception {
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
String controllerId = "4711";
|
||||
@@ -204,7 +203,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetPollEvent.class, count = 1),
|
||||
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
|
||||
public void pollWithModifiedGlobalPollingTime() throws Exception {
|
||||
void pollWithModifiedGlobalPollingTime() throws Exception {
|
||||
WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), () -> {
|
||||
tenantConfigurationManagement.addOrUpdateConfiguration(TenantConfigurationKey.POLLING_TIME_INTERVAL,
|
||||
"00:02:00");
|
||||
@@ -230,7 +229,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = ActionCreatedEvent.class, count = 2),
|
||||
@Expect(type = TargetAttributesRequestedEvent.class, count = 1),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6) })
|
||||
public void rootRsNotModified() throws Exception {
|
||||
void rootRsNotModified() throws Exception {
|
||||
String controllerId = "4711";
|
||||
final String etag = mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), controllerId))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
@@ -308,7 +307,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
+ "UNKNOWN to REGISTERED when the target polls for the first time.")
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 1), @Expect(type = TargetPollEvent.class, count = 1) })
|
||||
public void rootRsPrecommissioned() throws Exception {
|
||||
void rootRsPrecommissioned() throws Exception {
|
||||
String controllerId = "4711";
|
||||
testdataFactory.createTarget(controllerId);
|
||||
|
||||
@@ -334,7 +333,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Description("Ensures that the source IP address of the polling target is correctly stored in repository")
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetPollEvent.class, count = 1) })
|
||||
public void rootRsPlugAndPlayIpAddress() throws Exception {
|
||||
void rootRsPlugAndPlayIpAddress() throws Exception {
|
||||
// test
|
||||
final String knownControllerId1 = "0815";
|
||||
final long create = System.currentTimeMillis();
|
||||
@@ -361,7 +360,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Description("Ensures that the source IP address of the polling target is not stored in repository if disabled")
|
||||
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
|
||||
@Expect(type = TargetPollEvent.class, count = 1) })
|
||||
public void rootRsIpAddressNotStoredIfDisabled() throws Exception {
|
||||
void rootRsIpAddressNotStoredIfDisabled() throws Exception {
|
||||
securityProperties.getClients().setTrackRemoteIp(false);
|
||||
|
||||
// test
|
||||
@@ -384,7 +383,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = ActionCreatedEvent.class, count = 1), @Expect(type = ActionUpdatedEvent.class, count = 1),
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 2),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
|
||||
public void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
|
||||
void tryToFinishAnUpdateProcessAfterItHasBeenFinished() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
Target savedTarget = testdataFactory.createTarget("911");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
|
||||
@@ -409,7 +408,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 6), @Expect(type = TargetPollEvent.class, count = 4),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
|
||||
@Expect(type = TargetAttributesRequestedEvent.class, count = 1) })
|
||||
public void attributeUpdateRequestSendingAfterSuccessfulDeployment() throws Exception {
|
||||
void attributeUpdateRequestSendingAfterSuccessfulDeployment() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("1");
|
||||
final Target savedTarget = testdataFactory.createTarget("922");
|
||||
final Map<String, String> attributes = Collections.singletonMap("AttributeKey", "AttributeValue");
|
||||
@@ -487,7 +486,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 2),
|
||||
@Expect(type = TargetAttributesRequestedEvent.class, count = 1),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
|
||||
public void testActionHistoryCount() throws Exception {
|
||||
void testActionHistoryCount() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
Target savedTarget = testdataFactory.createTarget("911");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
|
||||
@@ -524,7 +523,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 2),
|
||||
@Expect(type = TargetAttributesRequestedEvent.class, count = 1),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
|
||||
public void testActionHistoryZeroInput() throws Exception {
|
||||
void testActionHistoryZeroInput() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
Target savedTarget = testdataFactory.createTarget("911");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
|
||||
@@ -561,7 +560,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
@Expect(type = TargetUpdatedEvent.class, count = 2),
|
||||
@Expect(type = TargetAttributesRequestedEvent.class, count = 1),
|
||||
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
|
||||
public void testActionHistoryNegativeInput() throws Exception {
|
||||
void testActionHistoryNegativeInput() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
Target savedTarget = testdataFactory.createTarget("911");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSet(ds.getId(), savedTarget.getControllerId()));
|
||||
@@ -591,7 +590,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test the polling time based on different maintenance window start and end time.")
|
||||
public void sleepTimeResponseForDifferentMaintenanceWindowParameters() throws Exception {
|
||||
void sleepTimeResponseForDifferentMaintenanceWindowParameters() throws Exception {
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
|
||||
WithSpringAuthorityRule.runAs(WithSpringAuthorityRule.withUser("tenantadmin", HAS_AUTH_TENANT_CONFIGURATION), () -> {
|
||||
@@ -638,7 +637,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test download and update values before maintenance window start time.")
|
||||
public void downloadAndUpdateStatusBeforeMaintenanceWindowStartTime() throws Exception {
|
||||
void downloadAndUpdateStatusBeforeMaintenanceWindowStartTime() throws Exception {
|
||||
Target savedTarget = testdataFactory.createTarget("1911");
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSetWithMaintenanceWindow(ds.getId(),
|
||||
@@ -658,7 +657,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Test download and update values after maintenance window start time.")
|
||||
public void downloadAndUpdateStatusDuringMaintenanceWindow() throws Exception {
|
||||
void downloadAndUpdateStatusDuringMaintenanceWindow() throws Exception {
|
||||
Target savedTarget = testdataFactory.createTarget("1911");
|
||||
final DistributionSet ds = testdataFactory.createDistributionSet("");
|
||||
savedTarget = getFirstAssignedTarget(assignDistributionSetWithMaintenanceWindow(ds.getId(),
|
||||
@@ -678,7 +677,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Assign multiple DS in multi-assignment mode. The earliest active Action is exposed to the controller.")
|
||||
public void earliestActionIsExposedToControllerInMultiAssignMode() throws Exception {
|
||||
void earliestActionIsExposedToControllerInMultiAssignMode() throws Exception {
|
||||
enableMultiAssignments();
|
||||
final Target target = testdataFactory.createTarget();
|
||||
final DistributionSet ds1 = testdataFactory.createDistributionSet(UUID.randomUUID().toString());
|
||||
@@ -695,7 +694,7 @@ public class DdiRootControllerTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("The system should not create a new target because of a too long controller id.")
|
||||
public void rootRsWithInvalidControllerId() throws Exception {
|
||||
void rootRsWithInvalidControllerId() throws Exception {
|
||||
final String invalidControllerId = RandomStringUtils.randomAlphabetic(Target.CONTROLLER_ID_MAX_SIZE + 1);
|
||||
mvc.perform(get(CONTROLLER_BASE, tenantAware.getCurrentTenant(), invalidControllerId))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
@@ -42,7 +42,7 @@ import io.qameta.allure.Story;
|
||||
@ActiveProfiles({ "test" })
|
||||
@Feature("Component Tests - REST Security")
|
||||
@Story("Denial of Service protection filter")
|
||||
public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Override
|
||||
protected DefaultMockMvcBuilder createMvcWebAppContext(final WebApplicationContext context) {
|
||||
@@ -52,14 +52,14 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that clients that are on the blacklist are forbidded ")
|
||||
public void blackListedClientIsForbidden() throws Exception {
|
||||
void blackListedClientIsForbidden() throws Exception {
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "192.168.0.4 , 10.0.0.1 ")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a READ DoS attempt is blocked ")
|
||||
public void getFloddingAttackThatisPrevented() throws Exception {
|
||||
void getFloddingAttackThatisPrevented() throws Exception {
|
||||
|
||||
MvcResult result = null;
|
||||
|
||||
@@ -79,7 +79,7 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that an assumed READ DoS attempt is not blocked as the client (with IPv4 address) is on a whitelist")
|
||||
public void unacceptableGetLoadButOnWhitelistIPv4() throws Exception {
|
||||
void unacceptableGetLoadButOnWhitelistIPv4() throws Exception {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "127.0.0.1")).andExpect(status().isOk());
|
||||
@@ -88,7 +88,7 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that an assumed READ DoS attempt is not blocked as the client (with IPv6 address) is on a whitelist")
|
||||
public void unacceptableGetLoadButOnWhitelistIPv6() throws Exception {
|
||||
void unacceptableGetLoadButOnWhitelistIPv6() throws Exception {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
mvc.perform(get("/{tenant}/controller/v1/4711", tenantAware.getCurrentTenant())
|
||||
.header(HttpHeaders.X_FORWARDED_FOR, "0:0:0:0:0:0:0:1")).andExpect(status().isOk());
|
||||
@@ -97,7 +97,8 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a relatively high number of READ requests is allowed if it is below the DoS detection threshold")
|
||||
public void acceptableGetLoad() throws Exception {
|
||||
@SuppressWarnings("squid:S2925") // No idea how to get rid of the Thread.sleep here
|
||||
void acceptableGetLoad() throws Exception {
|
||||
|
||||
for (int x = 0; x < 3; x++) {
|
||||
// sleep for one second
|
||||
@@ -111,7 +112,7 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a WRITE DoS attempt is blocked ")
|
||||
public void putPostFloddingAttackThatisPrevented() throws Exception {
|
||||
void putPostFloddingAttackThatisPrevented() throws Exception {
|
||||
final Long actionId = prepareDeploymentBase();
|
||||
final String feedback = JsonBuilder.deploymentActionFeedback(actionId.toString(), "proceeding");
|
||||
|
||||
@@ -135,7 +136,8 @@ public class DosFilterTest extends AbstractDDiApiIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a relatively high number of WRITE requests is allowed if it is below the DoS detection threshold")
|
||||
public void acceptablePutPostLoad() throws Exception {
|
||||
@SuppressWarnings("squid:S2925") // No idea how to get rid of the Thread.sleep here
|
||||
void acceptablePutPostLoad() throws Exception {
|
||||
final Long actionId = prepareDeploymentBase();
|
||||
final String feedback = JsonBuilder.deploymentActionFeedback(actionId.toString(), "proceeding");
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ package org.eclipse.hawkbit.mgmt.rest.resource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.validation.ValidationException;
|
||||
|
||||
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
|
||||
@@ -29,6 +28,7 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryManagement;
|
||||
import org.eclipse.hawkbit.repository.builder.RolloutCreate;
|
||||
import org.eclipse.hawkbit.repository.builder.RolloutGroupCreate;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
|
||||
import org.eclipse.hawkbit.repository.exception.RSQLParameterSyntaxException;
|
||||
import org.eclipse.hawkbit.repository.model.DistributionSet;
|
||||
import org.eclipse.hawkbit.repository.model.Rollout;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup;
|
||||
@@ -108,17 +108,22 @@ public class MgmtRolloutResource implements MgmtRolloutRestApi {
|
||||
|
||||
// first check the given RSQL query if it's well formed, otherwise and
|
||||
// exception is thrown
|
||||
targetFilterQueryManagement.verifyTargetFilterQuerySyntax(rolloutRequestBody.getTargetFilterQuery());
|
||||
|
||||
final DistributionSet distributionSet = distributionSetManagement
|
||||
.getValidAndComplete(rolloutRequestBody.getDistributionSetId());
|
||||
final String targetFilterQuery = rolloutRequestBody.getTargetFilterQuery();
|
||||
if (targetFilterQuery == null) {
|
||||
// Use RSQLParameterSyntaxException due to backwards compatibility
|
||||
throw new RSQLParameterSyntaxException("Cannot create a Rollout with an empty target query filter!");
|
||||
}
|
||||
targetFilterQueryManagement.verifyTargetFilterQuerySyntax(targetFilterQuery);
|
||||
final DistributionSet distributionSet = distributionSetManagement.getValidAndComplete(
|
||||
rolloutRequestBody.getDistributionSetId());
|
||||
final RolloutGroupConditions rolloutGroupConditions = MgmtRolloutMapper.fromRequest(rolloutRequestBody, true);
|
||||
|
||||
final RolloutCreate create = MgmtRolloutMapper.fromRequest(entityFactory, rolloutRequestBody, distributionSet);
|
||||
|
||||
Rollout rollout;
|
||||
if (rolloutRequestBody.getGroups() != null) {
|
||||
final List<RolloutGroupCreate> rolloutGroups = rolloutRequestBody.getGroups().stream()
|
||||
final List<RolloutGroupCreate> rolloutGroups = rolloutRequestBody.getGroups()
|
||||
.stream()
|
||||
.map(mgmtRolloutGroup -> MgmtRolloutMapper.fromRequest(entityFactory, mgmtRolloutGroup))
|
||||
.collect(Collectors.toList());
|
||||
rollout = rolloutManagement.create(create, rolloutGroups, rolloutGroupConditions);
|
||||
|
||||
@@ -25,8 +25,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.Duration;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
|
||||
@@ -40,10 +43,10 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroupConditionBuilder;
|
||||
import org.eclipse.hawkbit.repository.model.RolloutGroupConditions;
|
||||
import org.eclipse.hawkbit.repository.test.util.WithSpringAuthorityRule;
|
||||
import org.eclipse.hawkbit.repository.test.util.WithUser;
|
||||
import org.eclipse.hawkbit.rest.util.JsonBuilder;
|
||||
import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter;
|
||||
import org.eclipse.hawkbit.rest.util.SuccessCondition;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
@@ -60,21 +63,21 @@ import io.qameta.allure.Story;
|
||||
*/
|
||||
@Feature("Component Tests - Management API")
|
||||
@Story("Rollout Resource")
|
||||
public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
|
||||
private static final String HREF_ROLLOUT_PREFIX = "http://localhost/rest/v1/rollouts/";
|
||||
|
||||
@Autowired
|
||||
private RolloutManagement rolloutManagement;
|
||||
@Autowired private RolloutManagement rolloutManagement;
|
||||
|
||||
@Autowired
|
||||
private RolloutGroupManagement rolloutGroupManagement;
|
||||
@Autowired private RolloutGroupManagement rolloutGroupManagement;
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with wrong body returns bad request")
|
||||
public void createRolloutWithInvalidBodyReturnsBadRequest() throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts").content("invalid body").contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
void createRolloutWithInvalidBodyReturnsBadRequest() throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts").content("invalid body")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.body.notReadable")));
|
||||
}
|
||||
@@ -82,36 +85,45 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
@Test
|
||||
@Description("Testing that creating rollout with insufficient permission returns forbidden")
|
||||
@WithUser(allSpPermissions = true, removeFromAllPermission = "CREATE_ROLLOUT")
|
||||
public void createRolloutWithInsufficientPermissionReturnsForbidden() throws Exception {
|
||||
void createRolloutWithInsufficientPermissionReturnsForbidden() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name==test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().is(403)).andReturn();
|
||||
mvc.perform(post("/rest/v1/rollouts").content(
|
||||
JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name==test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().is(403))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with not exisiting distribution set returns not found")
|
||||
public void createRolloutWithNotExistingDistributionSetReturnsNotFound() throws Exception {
|
||||
@Description("Testing that creating rollout with not existing distribution set returns not found")
|
||||
void createRolloutWithNotExistingDistributionSetReturnsNotFound() throws Exception {
|
||||
mvc.perform(post("/rest/v1/rollouts").content(JsonBuilder.rollout("name", "desc", 10, 1234, "name==test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()).andReturn();
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound())
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that creating rollout with not valid formed target filter query returns bad request")
|
||||
public void createRolloutWithNotWellFormedFilterReturnsBadRequest() throws Exception {
|
||||
void createRolloutWithNotWellFormedFilterReturnsBadRequest() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name=test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest())
|
||||
mvc.perform(post("/rest/v1/rollouts").content(
|
||||
JsonBuilder.rollout("name", "desc", 10, dsA.getId(), "name=test", null))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.param.rsqlParamSyntax")))
|
||||
.andReturn();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the repository refuses to create rollout without a defined target filter set.")
|
||||
public void missingTargetFilterQueryInRollout() throws Exception {
|
||||
void missingTargetFilterQueryInRollout() throws Exception {
|
||||
|
||||
final String targetFilterQuery = null;
|
||||
|
||||
@@ -127,7 +139,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout can be created")
|
||||
public void createRollout() throws Exception {
|
||||
void createRollout() throws Exception {
|
||||
testdataFactory.createTargets(20, "target", "rollout");
|
||||
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
@@ -136,17 +148,18 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Verifies that rollout cannot be created if too many rollout groups are specified.")
|
||||
public void createRolloutWithTooManyRolloutGroups() throws Exception {
|
||||
void createRolloutWithTooManyRolloutGroups() throws Exception {
|
||||
|
||||
final int maxGroups = quotaManagement.getMaxRolloutGroupsPerRollout();
|
||||
testdataFactory.createTargets(20, "target", "rollout");
|
||||
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("rollout1", "rollout1Desc", maxGroups + 1,
|
||||
testdataFactory.createDistributionSet("ds").getId(), "id==target*",
|
||||
new RolloutGroupConditionBuilder().withDefaults().build()))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden())
|
||||
mvc.perform(post("/rest/v1/rollouts").content(JsonBuilder.rollout("rollout1", "rollout1Desc", maxGroups + 1,
|
||||
testdataFactory.createDistributionSet("ds").getId(), "id==target*",
|
||||
new RolloutGroupConditionBuilder().withDefaults().build()))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(AssignmentQuotaExceededException.class.getName())))
|
||||
.andExpect(jsonPath("$.errorCode", equalTo(SpServerError.SP_QUOTA_EXCEEDED.getKey())));
|
||||
|
||||
@@ -154,17 +167,18 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Verifies that rollout cannot be created if the 'max targets per rollout group' quota would be violated for one of the groups.")
|
||||
public void createRolloutFailsIfRolloutGroupQuotaIsViolated() throws Exception {
|
||||
void createRolloutFailsIfRolloutGroupQuotaIsViolated() throws Exception {
|
||||
|
||||
final int maxTargets = quotaManagement.getMaxTargetsPerRolloutGroup();
|
||||
testdataFactory.createTargets(maxTargets + 1, "target", "rollout");
|
||||
|
||||
mvc.perform(post("/rest/v1/rollouts")
|
||||
.content(JsonBuilder.rollout("rollout1", "rollout1Desc", 1,
|
||||
testdataFactory.createDistributionSet("ds").getId(), "id==target*",
|
||||
new RolloutGroupConditionBuilder().withDefaults().build()))
|
||||
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isForbidden())
|
||||
mvc.perform(post("/rest/v1/rollouts").content(
|
||||
JsonBuilder.rollout("rollout1", "rollout1Desc", 1, testdataFactory.createDistributionSet("ds").getId(),
|
||||
"id==target*", new RolloutGroupConditionBuilder().withDefaults().build()))
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(AssignmentQuotaExceededException.class.getName())))
|
||||
.andExpect(jsonPath("$.errorCode", equalTo(SpServerError.SP_QUOTA_EXCEEDED.getKey())));
|
||||
|
||||
@@ -172,7 +186,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout can be created with groups")
|
||||
public void createRolloutWithGroupDefinitions() throws Exception {
|
||||
void createRolloutWithGroupDefinitions() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("ro");
|
||||
|
||||
final int amountTargets = 10;
|
||||
@@ -199,17 +213,23 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that no rollout with groups that have illegal percentages can be created")
|
||||
public void createRolloutWithTooLowPercentage() throws Exception {
|
||||
void createRolloutWithTooLowPercentage() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("ro2");
|
||||
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
|
||||
|
||||
final List<RolloutGroup> rolloutGroups = Arrays.asList(
|
||||
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(0F)
|
||||
.build(),
|
||||
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(100F)
|
||||
.build());
|
||||
final List<RolloutGroup> rolloutGroups = Arrays.asList(entityFactory.rolloutGroup()
|
||||
.create()
|
||||
.name("Group1")
|
||||
.description("Group1desc")
|
||||
.targetPercentage(0F)
|
||||
.build(), entityFactory.rolloutGroup()
|
||||
.create()
|
||||
.name("Group2")
|
||||
.description("Group2desc")
|
||||
.targetPercentage(100F)
|
||||
.build());
|
||||
|
||||
final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build();
|
||||
|
||||
@@ -224,17 +244,23 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that no rollout with groups that have illegal percentages can be created")
|
||||
public void createRolloutWithTooHighPercentage() throws Exception {
|
||||
void createRolloutWithTooHighPercentage() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("ro2");
|
||||
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "ro-target", "rollout");
|
||||
|
||||
final List<RolloutGroup> rolloutGroups = Arrays.asList(
|
||||
entityFactory.rolloutGroup().create().name("Group1").description("Group1desc").targetPercentage(1F)
|
||||
.build(),
|
||||
entityFactory.rolloutGroup().create().name("Group2").description("Group2desc").targetPercentage(101F)
|
||||
.build());
|
||||
final List<RolloutGroup> rolloutGroups = Arrays.asList(entityFactory.rolloutGroup()
|
||||
.create()
|
||||
.name("Group1")
|
||||
.description("Group1desc")
|
||||
.targetPercentage(1F)
|
||||
.build(), entityFactory.rolloutGroup()
|
||||
.create()
|
||||
.name("Group2")
|
||||
.description("Group2desc")
|
||||
.targetPercentage(101F)
|
||||
.build());
|
||||
|
||||
final RolloutGroupConditions rolloutGroupConditions = new RolloutGroupConditionBuilder().withDefaults().build();
|
||||
|
||||
@@ -249,24 +275,29 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing the empty list is returned if no rollout exists")
|
||||
public void noRolloutReturnsEmptyList() throws Exception {
|
||||
mvc.perform(get("/rest/v1/rollouts").accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.content", hasSize(0))).andExpect(jsonPath("$.total", equalTo(0)));
|
||||
void noRolloutReturnsEmptyList() throws Exception {
|
||||
mvc.perform(get("/rest/v1/rollouts").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.content", hasSize(0)))
|
||||
.andExpect(jsonPath("$.total", equalTo(0)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Retrieves single rollout from management API including extra data that is delivered only for single rollout access.")
|
||||
public void retrieveSingleRollout() throws Exception {
|
||||
void retrieveSingleRollout() throws Exception {
|
||||
testdataFactory.createTargets(20, "rollout", "rollout");
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = rolloutManagement.create(
|
||||
entityFactory.rollout().create().name("rollout1").set(dsA.getId())
|
||||
.targetFilterQuery("controllerId==rollout*"),
|
||||
4, new RolloutGroupConditionBuilder().withDefaults()
|
||||
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
|
||||
final Rollout rollout = rolloutManagement.create(entityFactory.rollout()
|
||||
.create()
|
||||
.name("rollout1")
|
||||
.set(dsA.getId())
|
||||
.targetFilterQuery("controllerId==rollout*"), 4, new RolloutGroupConditionBuilder().withDefaults()
|
||||
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100")
|
||||
.build());
|
||||
|
||||
retrieveAndVerifyRolloutInCreating(dsA, rollout);
|
||||
retrieveAndVerifyRolloutInReady(rollout);
|
||||
@@ -362,7 +393,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list contains rollouts")
|
||||
public void rolloutPagedListContainsAllRollouts() throws Exception {
|
||||
void rolloutPagedListContainsAllRollouts() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
|
||||
testdataFactory.createTargets(20, "target", "rollout");
|
||||
@@ -403,7 +434,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list is limited by the query param limit")
|
||||
public void rolloutPagedListIsLimitedToQueryParam() throws Exception {
|
||||
void rolloutPagedListIsLimitedToQueryParam() throws Exception {
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
|
||||
testdataFactory.createTargets(20, "target", "rollout");
|
||||
@@ -423,7 +454,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list is limited by the query param limit")
|
||||
public void retrieveRolloutGroupsForSpecificRollout() throws Exception {
|
||||
void retrieveRolloutGroupsForSpecificRollout() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -446,7 +477,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that starting the rollout switches the state to starting and then to running")
|
||||
public void startingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
void startingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -479,7 +510,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that pausing the rollout switches the state to paused")
|
||||
public void pausingRolloutSwitchesIntoPausedState() throws Exception {
|
||||
void pausingRolloutSwitchesIntoPausedState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -509,7 +540,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that resuming the rollout switches the state to running")
|
||||
public void resumingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
void resumingRolloutSwitchesIntoRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -543,7 +574,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that an already started rollout cannot be started again and returns bad request")
|
||||
public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
|
||||
void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -567,7 +598,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that resuming a rollout which is not started leads to bad request")
|
||||
public void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
|
||||
void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -584,7 +615,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that starting rollout the first rollout group is in running state")
|
||||
public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
|
||||
void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -612,17 +643,18 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that a single rollout group can be retrieved")
|
||||
public void retrieveSingleRolloutGroup() throws Exception {
|
||||
void retrieveSingleRolloutGroup() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = rolloutManagement.create(
|
||||
entityFactory.rollout().create().name("rollout1").set(dsA.getId())
|
||||
.targetFilterQuery("controllerId==rollout*"),
|
||||
4, new RolloutGroupConditionBuilder().withDefaults()
|
||||
final Rollout rollout = rolloutManagement.create(entityFactory.rollout()
|
||||
.create()
|
||||
.name("rollout1")
|
||||
.set(dsA.getId())
|
||||
.targetFilterQuery("controllerId==rollout*"), 4, new RolloutGroupConditionBuilder().withDefaults()
|
||||
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
@@ -711,7 +743,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved")
|
||||
public void retrieveTargetsFromRolloutGroup() throws Exception {
|
||||
void retrieveTargetsFromRolloutGroup() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -720,8 +752,8 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findByRollout(PageRequest.of(0, 1, Direction.ASC, "id"), rollout.getId()).getContent().get(0);
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement.findByRollout(PageRequest.of(0, 1, Direction.ASC, "id"),
|
||||
rollout.getId()).getContent().get(0);
|
||||
|
||||
// retrieve targets from the first rollout group with known ID
|
||||
mvc.perform(
|
||||
@@ -734,7 +766,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved with rsql query param")
|
||||
public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception {
|
||||
void retrieveTargetsFromRolloutGroupWithQuery() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -743,8 +775,8 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement
|
||||
.findByRollout(PageRequest.of(0, 1, Direction.ASC, "id"), rollout.getId()).getContent().get(0);
|
||||
final RolloutGroup firstGroup = rolloutGroupManagement.findByRollout(PageRequest.of(0, 1, Direction.ASC, "id"),
|
||||
rollout.getId()).getContent().get(0);
|
||||
|
||||
final String targetInGroup = rolloutGroupManagement.findTargetsOfRolloutGroup(PAGE, firstGroup.getId())
|
||||
.getContent().get(0).getControllerId();
|
||||
@@ -760,7 +792,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that the targets of rollout group can be retrieved after the rollout has been started")
|
||||
public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
|
||||
void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -788,7 +820,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Start the rollout in async mode")
|
||||
public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
|
||||
void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
|
||||
|
||||
final int amountTargets = 1000;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -798,19 +830,31 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
|
||||
|
||||
// starting rollout
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId()))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// Run here, because scheduler is disabled during tests
|
||||
rolloutManagement.handleRollouts();
|
||||
|
||||
// check if running
|
||||
assertThat(doWithTimeout(() -> getRollout(rollout.getId()), this::success, 60_000, 100)).isNotNull();
|
||||
awaitRunningState(rollout.getId());
|
||||
}
|
||||
|
||||
private void awaitRunningState(final Long rolloutId) {
|
||||
Awaitility.await()
|
||||
.atMost(Duration.ONE_MINUTE)
|
||||
.pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
|
||||
.with()
|
||||
.until(() -> WithSpringAuthorityRule.runAsPrivileged(
|
||||
() -> rolloutManagement.get(rolloutId).orElseThrow(NoSuchElementException::new))
|
||||
.getStatus()
|
||||
.equals(RolloutStatus.RUNNING));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Deletion of a rollout")
|
||||
public void deleteRollout() throws Exception {
|
||||
void deleteRollout() throws Exception {
|
||||
final int amountTargets = 10;
|
||||
testdataFactory.createTargets(amountTargets, "rolloutDelete", "rolloutDelete");
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
@@ -818,26 +862,34 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
// create rollout including the created targets with prefix 'rollout'
|
||||
final Rollout rollout = createRollout("rolloutDelete", 4, dsA.getId(), "controllerId==rolloutDelete*");
|
||||
|
||||
// delete rollout
|
||||
mvc.perform(delete("/rest/v1/rollouts/{rolloutid}", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(delete("/rest/v1/rollouts/{rolloutid}", rollout.getId()))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(getRollout(rollout.getId()).getStatus()).isEqualTo(RolloutStatus.DELETING);
|
||||
assertStatusIs(rollout, RolloutStatus.DELETING);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Soft deletion of a rollout: soft deletion appears when already running rollout is being deleted")
|
||||
public void deleteRunningRollout() throws Exception {
|
||||
void deleteRunningRollout() throws Exception {
|
||||
final Rollout rollout = testdataFactory.createSoftDeletedRollout("softDeletedRollout");
|
||||
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutid}", rollout.getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.deleted", equalTo(true)));
|
||||
assertThat(getRollout(rollout.getId()).getStatus()).isEqualTo(RolloutStatus.DELETED);
|
||||
mvc.perform(get("/rest/v1/rollouts/{rolloutid}", rollout.getId()))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.deleted", equalTo(true)));
|
||||
|
||||
assertStatusIs(rollout, RolloutStatus.DELETED);
|
||||
}
|
||||
|
||||
private void assertStatusIs(final Rollout rollout, RolloutStatus expected) {
|
||||
final Optional<Rollout> updatedRollout = rolloutManagement.get(rollout.getId());
|
||||
assertThat(updatedRollout).get().extracting(Rollout::getStatus).isEqualTo(expected);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Testing that rollout paged list with rsql parameter")
|
||||
public void getRolloutWithRSQLParam() throws Exception {
|
||||
void getRolloutWithRSQLParam() throws Exception {
|
||||
|
||||
final int amountTargetsRollout1 = 25;
|
||||
final int amountTargetsRollout2 = 25;
|
||||
@@ -875,7 +927,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Testing that rolloutgroup paged list with rsql parameter")
|
||||
public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
|
||||
void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
|
||||
// setup
|
||||
final int amountTargets = 20;
|
||||
testdataFactory.createTargets(amountTargets, "rollout", "rollout");
|
||||
@@ -909,7 +961,7 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
|
||||
@Test
|
||||
@Description("Verifies that a DOWNLOAD_ONLY rollout is possible")
|
||||
public void createDownloadOnlyRollout() throws Exception {
|
||||
void createDownloadOnlyRollout() throws Exception {
|
||||
testdataFactory.createTargets(20, "target", "rollout");
|
||||
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
@@ -917,8 +969,8 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("A rollout create request containing a weight is only accepted when weight is valide and multi assignment is on.")
|
||||
public void weightValidation() throws Exception {
|
||||
@Description("A rollout create request containing a weight is only accepted when weight is valid and multi assignment is on.")
|
||||
void weightValidation() throws Exception {
|
||||
testdataFactory.createTargets(4, "rollout", "description");
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
final int weight = 66;
|
||||
@@ -946,43 +998,6 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
assertThat(rollouts.get(0).getWeight()).get().isEqualTo(weight);
|
||||
}
|
||||
|
||||
protected <T> T doWithTimeout(final Callable<T> callable, final SuccessCondition<T> successCondition,
|
||||
final long timeout, final long pollInterval) throws Exception // NOPMD
|
||||
{
|
||||
|
||||
if (pollInterval < 0) {
|
||||
throw new IllegalArgumentException("pollInterval must non negative");
|
||||
}
|
||||
|
||||
long duration = 0;
|
||||
Exception exception = null;
|
||||
T returnValue = null;
|
||||
while (untilTimeoutReached(timeout, duration)) {
|
||||
try {
|
||||
returnValue = callable.call();
|
||||
// clear exception
|
||||
exception = null;
|
||||
} catch (final Exception ex) {
|
||||
exception = ex;
|
||||
}
|
||||
Thread.sleep(pollInterval);
|
||||
duration += pollInterval > 0 ? pollInterval : 1;
|
||||
if (exception == null && successCondition.success(returnValue)) {
|
||||
return returnValue;
|
||||
} else {
|
||||
returnValue = null;
|
||||
}
|
||||
}
|
||||
if (exception != null) {
|
||||
throw exception;
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
protected boolean untilTimeoutReached(final long timeout, final long duration) {
|
||||
return duration <= timeout || timeout < 0;
|
||||
}
|
||||
|
||||
private void postRollout(final String name, final int groupSize, final Long distributionSetId,
|
||||
final String targetFilterQuery, final int targets, final Action.ActionType type) throws Exception {
|
||||
final String actionType = MgmtRestModelMapper.convertActionType(type).getName();
|
||||
@@ -1026,15 +1041,6 @@ public class MgmtRolloutResourceTest extends AbstractManagementApiIntegrationTes
|
||||
// Run here, because Scheduler is disabled during tests
|
||||
rolloutManagement.handleRollouts();
|
||||
|
||||
return rolloutManagement.get(rollout.getId()).get();
|
||||
return rolloutManagement.get(rollout.getId()).orElseThrow(NoSuchElementException::new);
|
||||
}
|
||||
|
||||
protected boolean success(final Rollout result) {
|
||||
return result != null && result.getStatus() == RolloutStatus.RUNNING;
|
||||
}
|
||||
|
||||
public Rollout getRollout(final Long rolloutId) throws Exception {
|
||||
return rolloutManagement.get(rolloutId).get();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -31,9 +31,12 @@ import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.Duration;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
@@ -72,23 +75,22 @@ import io.qameta.allure.Story;
|
||||
|
||||
/**
|
||||
* Tests for {@link MgmtSoftwareModuleResource} {@link RestController}.
|
||||
*
|
||||
*/
|
||||
@Feature("Component Tests - Management API")
|
||||
@Story("Software Module Resource")
|
||||
@TestPropertySource(properties = { "hawkbit.server.security.dos.maxArtifactSize=100000",
|
||||
"hawkbit.server.security.dos.maxArtifactStorage=500000" })
|
||||
public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
|
||||
@BeforeEach
|
||||
public void assertPreparationOfRepo() {
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("no softwaremodule should be founded").hasSize(0);
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("no softwaremodule should be founded").isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the update of software module metadata. It is verfied that only the selected fields for the update are really updated and the modification values are filled (i.e. updated by and at).")
|
||||
@WithUser(principal = "smUpdateTester", allSpPermissions = true)
|
||||
public void updateSoftwareModuleOnlyDescriptionAndVendorNameUntouched() throws Exception {
|
||||
void updateSoftwareModuleOnlyDescriptionAndVendorNameUntouched() throws Exception {
|
||||
final String knownSWName = "name1";
|
||||
final String knownSWVersion = "version1";
|
||||
final String knownSWDescription = "description1";
|
||||
@@ -97,101 +99,122 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
final String updateVendor = "newVendor1";
|
||||
final String updateDescription = "newDescription1";
|
||||
|
||||
SoftwareModule sm = softwareModuleManagement.create(entityFactory.softwareModule().create().type(osType)
|
||||
.name(knownSWName).version(knownSWVersion).description(knownSWDescription).vendor(knownSWVendor));
|
||||
final SoftwareModule sm = softwareModuleManagement.create(entityFactory.softwareModule()
|
||||
.create()
|
||||
.type(osType)
|
||||
.name(knownSWName)
|
||||
.version(knownSWVersion)
|
||||
.description(knownSWDescription)
|
||||
.vendor(knownSWVendor));
|
||||
|
||||
assertThat(sm.getName()).as("Wrong name of the software module").isEqualTo(knownSWName);
|
||||
|
||||
final String body = new JSONObject().put("vendor", updateVendor).put("description", updateDescription)
|
||||
.put("name", "nameShouldNotBeChanged").toString();
|
||||
final String body = new JSONObject().put("vendor", updateVendor)
|
||||
.put("description", updateDescription)
|
||||
.put("name", "nameShouldNotBeChanged")
|
||||
.toString();
|
||||
|
||||
// ensures that we are not to fast so that last modified is not set
|
||||
// correctly
|
||||
Thread.sleep(1);
|
||||
// ensures that we are not to fast so that last modified is not set correctly
|
||||
Awaitility.await()
|
||||
.atMost(Duration.ONE_HUNDRED_MILLISECONDS)
|
||||
.pollInterval(10L, TimeUnit.MILLISECONDS)
|
||||
.until(() -> sm.getLastModifiedAt() > 0L && sm.getLastModifiedBy() != null);
|
||||
|
||||
mvc.perform(put("/rest/v1/softwaremodules/{smId}", sm.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", equalTo(sm.getId().intValue())))
|
||||
.andExpect(jsonPath("$.vendor", equalTo(updateVendor)))
|
||||
.andExpect(jsonPath("$.lastModifiedBy", equalTo("smUpdateTester")))
|
||||
.andExpect(jsonPath("$.lastModifiedAt", not(equalTo(sm.getLastModifiedAt()))))
|
||||
.andExpect(jsonPath("$.description", equalTo(updateDescription)))
|
||||
.andExpect(jsonPath("$.name", equalTo(knownSWName))).andReturn();
|
||||
.andExpect(jsonPath("$.name", equalTo(knownSWName)))
|
||||
.andReturn();
|
||||
|
||||
sm = softwareModuleManagement.get(sm.getId()).get();
|
||||
assertThat(sm.getName()).isEqualTo(knownSWName);
|
||||
assertThat(sm.getVendor()).isEqualTo(updateVendor);
|
||||
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
|
||||
assertThat(sm.getDescription()).isEqualTo(updateDescription);
|
||||
final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get();
|
||||
assertThat(updatedSm.getName()).isEqualTo(knownSWName);
|
||||
assertThat(updatedSm.getVendor()).isEqualTo(updateVendor);
|
||||
assertThat(updatedSm.getLastModifiedBy()).isEqualTo("smUpdateTester");
|
||||
assertThat(updatedSm.getDescription()).isEqualTo(updateDescription);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the update of the deletion flag. It is verfied that the software module can't be marked as deleted through update operation.")
|
||||
@WithUser(principal = "smUpdateTester", allSpPermissions = true)
|
||||
public void updateSoftwareModuleDeletedFlag() throws Exception {
|
||||
void updateSoftwareModuleDeletedFlag() throws Exception {
|
||||
final String knownSWName = "name1";
|
||||
final String knownSWVersion = "version1";
|
||||
|
||||
SoftwareModule sm = softwareModuleManagement
|
||||
.create(entityFactory.softwareModule().create().type(osType).name(knownSWName).version(knownSWVersion));
|
||||
final SoftwareModule sm = softwareModuleManagement.create(
|
||||
entityFactory.softwareModule().create().type(osType).name(knownSWName).version(knownSWVersion));
|
||||
|
||||
assertThat(sm.isDeleted()).as("Created software module should not be deleted").isEqualTo(false);
|
||||
assertThat(sm.isDeleted()).as("Created software module should not be deleted").isFalse();
|
||||
|
||||
final String body = new JSONObject().put("deleted", true).toString();
|
||||
|
||||
// ensures that we are not to fast so that last modified is not set
|
||||
// correctly
|
||||
Thread.sleep(1);
|
||||
// ensures that we are not to fast so that last modified is not set correctly
|
||||
Awaitility.await()
|
||||
.atMost(Duration.ONE_HUNDRED_MILLISECONDS)
|
||||
.pollInterval(10L, TimeUnit.MILLISECONDS)
|
||||
.until(() -> sm.getLastModifiedAt() > 0L && sm.getLastModifiedBy() != null);
|
||||
|
||||
mvc.perform(put("/rest/v1/softwaremodules/{smId}", sm.getId()).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.id", equalTo(sm.getId().intValue())))
|
||||
.andExpect(jsonPath("$.lastModifiedBy", equalTo("smUpdateTester")))
|
||||
.andExpect(jsonPath("$.lastModifiedAt", equalTo(sm.getLastModifiedAt())))
|
||||
.andExpect(jsonPath("$.deleted", equalTo(false)));
|
||||
|
||||
sm = softwareModuleManagement.get(sm.getId()).get();
|
||||
final SoftwareModule updatedSm = softwareModuleManagement.get(sm.getId()).get();
|
||||
assertThat(sm.getLastModifiedBy()).isEqualTo("smUpdateTester");
|
||||
assertThat(sm.getLastModifiedAt()).isEqualTo(sm.getLastModifiedAt());
|
||||
assertThat(sm.isDeleted()).isEqualTo(false);
|
||||
assertThat(sm.isDeleted()).isFalse();
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the upload of an artifact binary. The upload is executed and the content checked in the repository for completeness.")
|
||||
public void uploadArtifact() throws Exception {
|
||||
void uploadArtifact() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
// create test file
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final String md5sum = HashGeneratorUtils.generateMD5(random);
|
||||
final String sha1sum = HashGeneratorUtils.generateSHA1(random);
|
||||
final String sha256sum = HashGeneratorUtils.generateSHA256(random);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);
|
||||
|
||||
// upload
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
final MvcResult mvcResult = mvc.perform(
|
||||
multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
|
||||
.andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
|
||||
.andExpect(jsonPath("$.hashes.sha256", equalTo(sha256sum)))
|
||||
.andExpect(jsonPath("$.size", equalTo(random.length)))
|
||||
.andExpect(jsonPath("$.providedFilename", equalTo("origFilename"))).andReturn();
|
||||
.andExpect(jsonPath("$.providedFilename", equalTo("origFilename")))
|
||||
.andReturn();
|
||||
|
||||
// check rest of response compared to DB
|
||||
final MgmtArtifact artResult = ResourceUtility
|
||||
.convertArtifactResponse(mvcResult.getResponse().getContentAsString());
|
||||
final MgmtArtifact artResult = ResourceUtility.convertArtifactResponse(
|
||||
mvcResult.getResponse().getContentAsString());
|
||||
final Long artId = softwareModuleManagement.get(sm.getId()).get().getArtifacts().get(0).getId();
|
||||
assertThat(artResult.getArtifactId()).as("Wrong artifact id").isEqualTo(artId);
|
||||
assertThat(JsonPath.compile("$._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.as("Link contains no self url")
|
||||
assertThat(JsonPath.compile("$._links.self.href")
|
||||
.read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).as("Link contains no self url")
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId);
|
||||
assertThat(JsonPath.compile("$._links.download.href").read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).as("response contains no download url ").isEqualTo(
|
||||
assertThat(JsonPath.compile("$._links.download.href")
|
||||
.read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).as("response contains no download url ")
|
||||
.isEqualTo(
|
||||
"http://localhost/rest/v1/softwaremodules/" + sm.getId() + "/artifacts/" + artId + "/download");
|
||||
|
||||
assertArtifact(sm, random);
|
||||
@@ -199,7 +222,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies that artifacts which exceed the configured maximum size cannot be uploaded.")
|
||||
public void uploadArtifactFailsIfTooLarge() throws Exception {
|
||||
void uploadArtifactFailsIfTooLarge() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModule("quota", "quota", false);
|
||||
final long maxSize = quotaManagement.getMaxArtifactSize();
|
||||
|
||||
@@ -210,7 +233,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
// try to upload
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(jsonPath("$.exceptionClass", equalTo(FileSizeQuotaExceededException.class.getName())))
|
||||
.andExpect(jsonPath("$.errorCode", equalTo(SpServerError.SP_FILE_SIZE_QUOTA_EXCEEDED.getKey())));
|
||||
@@ -218,7 +241,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies that artifact with invalid filename cannot be uploaded to prevent cross site scripting.")
|
||||
public void uploadArtifactFailsIfFilenameInvalide() throws Exception {
|
||||
void uploadArtifactFailsIfFilenameInvalide() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModule("quota", "quota", false);
|
||||
final String illegalFilename = "<img src=ernw onerror=alert(1)>.xml";
|
||||
|
||||
@@ -226,7 +249,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
final MockMultipartFile file = new MockMultipartFile("file", illegalFilename, null, randomBytes);
|
||||
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.message", containsString("Invalid characters in string")));
|
||||
}
|
||||
@@ -261,33 +285,34 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
|
||||
public void emptyUploadArtifact() throws Exception {
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).hasSize(0);
|
||||
assertThat(artifactManagement.count()).isEqualTo(0);
|
||||
@Description("Verifies that the system does not accept empty artifact uploads. Expected response: BAD REQUEST")
|
||||
void emptyUploadArtifact() throws Exception {
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).isEmpty();
|
||||
assertThat(artifactManagement.count()).isZero();
|
||||
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, new byte[0]);
|
||||
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT")
|
||||
public void duplicateUploadArtifact() throws Exception {
|
||||
@Description("Verifies that the system does not accept identical artifacts uploads for the same software module. Expected response: CONFLICT")
|
||||
void duplicateUploadArtifact() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final String md5sum = HashGeneratorUtils.generateMD5(random);
|
||||
final String sha1sum = HashGeneratorUtils.generateSHA1(random);
|
||||
final String sha256sum = HashGeneratorUtils.generateSHA256(random);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);
|
||||
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.hashes.md5", equalTo(md5sum)))
|
||||
.andExpect(jsonPath("$.hashes.sha1", equalTo(sha1sum)))
|
||||
@@ -299,20 +324,23 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("verfies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.")
|
||||
public void uploadArtifactWithCustomName() throws Exception {
|
||||
@Description("verifies that option to upload artifacts with a custom defined by metadata, i.e. not the file name of the binary itself.")
|
||||
void uploadArtifactWithCustomName() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
assertThat(artifactManagement.count()).isEqualTo(0);
|
||||
assertThat(artifactManagement.count()).isZero();
|
||||
|
||||
// create test file
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);
|
||||
|
||||
// upload
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file).param("filename",
|
||||
"customFilename")).andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
mvc.perform(multipart("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file)
|
||||
.param("filename", "customFilename"))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaTypes.HAL_JSON))
|
||||
.andExpect(jsonPath("$.providedFilename", equalTo("customFilename"))).andExpect(status().isCreated());
|
||||
.andExpect(jsonPath("$.providedFilename", equalTo("customFilename")))
|
||||
.andExpect(status().isCreated());
|
||||
|
||||
// check result in db...
|
||||
// repo
|
||||
@@ -323,13 +351,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST")
|
||||
public void uploadArtifactWithHashCheck() throws Exception {
|
||||
@Description("Verifies that the system refuses upload of an artifact where the provided hash sums do not match. Expected result: BAD REQUEST")
|
||||
void uploadArtifactWithHashCheck() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
assertThat(artifactManagement.count()).isEqualTo(0);
|
||||
assertThat(artifactManagement.count()).isZero();
|
||||
|
||||
// create test file
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final String md5sum = HashGeneratorUtils.generateMD5(random);
|
||||
final String sha1sum = HashGeneratorUtils.generateSHA1(random);
|
||||
final String sha256sum = HashGeneratorUtils.generateSHA256(random);
|
||||
@@ -379,13 +407,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies that only a limited number of artifacts can be uploaded for one software module.")
|
||||
public void uploadArtifactsUntilQuotaExceeded() throws Exception {
|
||||
void uploadArtifactsUntilQuotaExceeded() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
final long maxArtifacts = quotaManagement.getMaxArtifactsPerSoftwareModule();
|
||||
|
||||
for (int i = 0; i < maxArtifacts; ++i) {
|
||||
// create test file
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final String md5sum = HashGeneratorUtils.generateMD5(random);
|
||||
final String sha1sum = HashGeneratorUtils.generateSHA1(random);
|
||||
final String sha256sum = HashGeneratorUtils.generateSHA256(random);
|
||||
@@ -403,7 +431,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
// upload one more file to cause the quota to be exceeded
|
||||
final byte random[] = randomBytes(5 * 1024);
|
||||
final byte[] random = randomBytes(5 * 1024);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename_final", null, random);
|
||||
|
||||
// upload
|
||||
@@ -417,7 +445,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies that artifacts can only be added as long as the artifact storage quota is not exceeded.")
|
||||
public void uploadArtifactsUntilStorageQuotaExceeded() throws Exception {
|
||||
void uploadArtifactsUntilStorageQuotaExceeded() throws Exception {
|
||||
|
||||
final long storageLimit = quotaManagement.getMaxArtifactStorage();
|
||||
|
||||
@@ -427,7 +455,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
for (int i = 0; i < numArtifacts; ++i) {
|
||||
// create test file
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
final byte[] random = randomBytes(artifactSize);
|
||||
final String md5sum = HashGeneratorUtils.generateMD5(random);
|
||||
final String sha1sum = HashGeneratorUtils.generateSHA1(random);
|
||||
final String sha256sum = HashGeneratorUtils.generateSHA256(random);
|
||||
@@ -446,7 +474,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
// upload one more file to cause the quota to be exceeded
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
final byte[] random = randomBytes(artifactSize);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "origFilename_final", null, random);
|
||||
|
||||
// upload
|
||||
@@ -461,16 +489,16 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Tests binary download of an artifact including verfication that the downloaded binary is consistent and that the etag header is as expected identical to the SHA1 hash of the file.")
|
||||
public void downloadArtifact() throws Exception {
|
||||
void downloadArtifact() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
final byte[] random = randomBytes(artifactSize);
|
||||
|
||||
final Artifact artifact = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
final Artifact artifact2 = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
final Artifact artifact = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
final Artifact artifact2 = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
|
||||
downloadAndVerify(sm, random, artifact);
|
||||
downloadAndVerify(sm, random, artifact2);
|
||||
@@ -492,19 +520,21 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies the listing of one defined artifact assigned to a given software module. That includes the artifact metadata and download links.")
|
||||
public void getArtifact() throws Exception {
|
||||
void getArtifact() throws Exception {
|
||||
// prepare data for test
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
|
||||
final Artifact artifact = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
final Artifact artifact = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
|
||||
// perform test
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId()).accept(
|
||||
MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.id", equalTo(artifact.getId().intValue())))
|
||||
.andExpect(jsonPath("$.size", equalTo(random.length)))
|
||||
@@ -521,16 +551,18 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies the listing of an artifact that belongs to a soft deleted software module.")
|
||||
public void getArtifactSoftDeleted() throws Exception {
|
||||
void getArtifactSoftDeleted() throws Exception {
|
||||
// prepare data for test
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs("softDeleted");
|
||||
final Artifact artifact = testdataFactory.createArtifacts(sm.getId()).get(0);
|
||||
testdataFactory.createDistributionSet(Arrays.asList(sm));
|
||||
testdataFactory.createDistributionSet(Collections.singletonList(sm));
|
||||
softwareModuleManagement.delete(sm.getId());
|
||||
|
||||
// perform test
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId())
|
||||
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId()).accept(
|
||||
MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.id", equalTo(artifact.getId().intValue())))
|
||||
.andExpect(jsonPath("$.size", equalTo((int) artifact.getSize())))
|
||||
@@ -546,19 +578,20 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Verifies the listing of all artifacts assigned to a software module. That includes the artifact metadata and download links.")
|
||||
public void getArtifacts() throws Exception {
|
||||
void getArtifacts() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
final byte[] random = randomBytes(artifactSize);
|
||||
|
||||
final Artifact artifact = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
final Artifact artifact2 = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
final Artifact artifact = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
final Artifact artifact2 = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.[0].id", equalTo(artifact.getId().intValue())))
|
||||
.andExpect(jsonPath("$.[0].size", equalTo(random.length)))
|
||||
@@ -579,11 +612,11 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
|
||||
public void invalidRequestsOnArtifactResource() throws Exception {
|
||||
@Description("Verifies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
|
||||
void invalidRequestsOnArtifactResource() throws Exception {
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
final byte random[] = randomBytes(artifactSize);
|
||||
final byte[] random = randomBytes(artifactSize);
|
||||
final MockMultipartFile file = new MockMultipartFile("file", "orig", null, random);
|
||||
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
@@ -626,26 +659,29 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
|
||||
public void invalidRequestsOnSoftwaremodulesResource() throws Exception {
|
||||
@Description("Verifies that the system refuses unsupported request types and answers as defined to them, e.g. NOT FOUND on a non existing resource. Or a HTTP POST for updating a resource results in METHOD NOT ALLOWED etc.")
|
||||
void invalidRequestsOnSoftwaremodulesResource() throws Exception {
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final List<SoftwareModule> modules = Arrays.asList(sm);
|
||||
|
||||
// SM does not exist
|
||||
mvc.perform(get("/rest/v1/softwaremodules/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(get("/rest/v1/softwaremodules/12345678"))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/12345678")).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/12345678"))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
// bad request - no content
|
||||
mvc.perform(post("/rest/v1/softwaremodules").contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
// bad request - bad content
|
||||
mvc.perform(post("/rest/v1/softwaremodules").content("sdfjsdlkjfskdjf".getBytes())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
mvc.perform(post("/rest/v1/softwaremodules")
|
||||
@@ -683,10 +719,11 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Test of modules retrieval without any parameters. Will return all modules in the system as defined by standard page size.")
|
||||
public void getSoftwareModulesWithoutAddtionalRequestParameters() throws Exception {
|
||||
void getSoftwareModulesWithoutAddtionalRequestParameters() throws Exception {
|
||||
final int modules = 5;
|
||||
createSoftwareModulesAlphabetical(modules);
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(modules)))
|
||||
@@ -695,13 +732,14 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Test of modules retrieval with paging limit parameter. Will return all modules in the system as defined by given page size.")
|
||||
public void detSoftwareModulesWithPagingLimitRequestParameter() throws Exception {
|
||||
void detSoftwareModulesWithPagingLimitRequestParameter() throws Exception {
|
||||
final int modules = 5;
|
||||
final int limitSize = 1;
|
||||
createSoftwareModulesAlphabetical(modules);
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING).param(
|
||||
MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
|
||||
@@ -709,15 +747,16 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Test of modules retrieval with paging limit offset parameters. Will return all modules in the system as defined by given page size starting from given offset.")
|
||||
public void getSoftwareModulesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
void getSoftwareModulesWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int modules = 5;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = modules - offsetParam;
|
||||
createSoftwareModulesAlphabetical(modules);
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING)
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules)))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING).param(
|
||||
MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
|
||||
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules)))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
|
||||
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
|
||||
@@ -726,12 +765,13 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Test retrieval of all software modules the user has access to.")
|
||||
public void getSoftwareModules() throws Exception {
|
||||
void getSoftwareModules() throws Exception {
|
||||
final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
|
||||
final SoftwareModule app = testdataFactory.createSoftwareModuleApp();
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremodules").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].name", contains(os.getName())))
|
||||
.andExpect(jsonPath("$.content.[?(@.id==" + os.getId() + ")].version", contains(os.getVersion())))
|
||||
@@ -759,7 +799,7 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Test the various filter parameters, e.g. filter by name or type of the module.")
|
||||
public void getSoftwareModulesWithFilterParameters() throws Exception {
|
||||
void getSoftwareModulesWithFilterParameters() throws Exception {
|
||||
final SoftwareModule os1 = testdataFactory.createSoftwareModuleOs("1");
|
||||
final SoftwareModule app1 = testdataFactory.createSoftwareModuleApp("1");
|
||||
testdataFactory.createSoftwareModuleOs("2");
|
||||
@@ -769,7 +809,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
// only by name, only one exists per name
|
||||
mvc.perform(get("/rest/v1/softwaremodules?q=name==" + os1.getName()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].name", contains(os1.getName())))
|
||||
.andExpect(jsonPath("$.content.[?(@.id==" + os1.getId() + ")].version", contains(os1.getVersion())))
|
||||
@@ -816,29 +857,32 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system answers as defined in case of a wrong filter parameter syntax. Expected result: BAD REQUEST with error description.")
|
||||
public void getSoftwareModulesWithSyntaxErrorFilterParameter() throws Exception {
|
||||
@Description("Verifies that the system answers as defined in case of a wrong filter parameter syntax. Expected result: BAD REQUEST with error description.")
|
||||
void getSoftwareModulesWithSyntaxErrorFilterParameter() throws Exception {
|
||||
mvc.perform(get("/rest/v1/softwaremodules?q=wrongFIQLSyntax").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.rest.param.rsqlParamSyntax")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that the system answers as defined in case of a non existing field used in filter. Expected result: BAD REQUEST with error description.")
|
||||
public void getSoftwareModulesWithUnknownFieldErrorFilterParameter() throws Exception {
|
||||
@Description("Verifies that the system answers as defined in case of a non existing field used in filter. Expected result: BAD REQUEST with error description.")
|
||||
void getSoftwareModulesWithUnknownFieldErrorFilterParameter() throws Exception {
|
||||
mvc.perform(get("/rest/v1/softwaremodules?q=wrongField==abc").accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.rest.param.rsqlInvalidField")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Tests GET request on /rest/v1/softwaremodules/{smId}.")
|
||||
public void getSoftwareModule() throws Exception {
|
||||
void getSoftwareModule() throws Exception {
|
||||
final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
mvc.perform(get("/rest/v1/softwaremodules/{smId}", os.getId()).accept(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("$.name", equalTo(os.getName())))
|
||||
.andExpect(jsonPath("$.version", equalTo(os.getVersion())))
|
||||
@@ -861,26 +905,41 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@WithUser(principal = "uploadTester", allSpPermissions = true)
|
||||
@Description("Verfies that the create request actually results in the creation of the modules in the repository.")
|
||||
public void createSoftwareModules() throws Exception {
|
||||
final SoftwareModule os = entityFactory.softwareModule().create().name("name1").type(osType).version("version1")
|
||||
.vendor("vendor1").description("description1").build();
|
||||
final SoftwareModule ah = entityFactory.softwareModule().create().name("name3").type(appType)
|
||||
.version("version3").vendor("vendor3").description("description3").build();
|
||||
@Description("Verifies that the create request actually results in the creation of the modules in the repository.")
|
||||
void createSoftwareModules() throws Exception {
|
||||
final SoftwareModule os = entityFactory.softwareModule()
|
||||
.create()
|
||||
.name("name1")
|
||||
.type(osType)
|
||||
.version("version1")
|
||||
.vendor("vendor1")
|
||||
.description("description1")
|
||||
.build();
|
||||
final SoftwareModule ah = entityFactory.softwareModule()
|
||||
.create()
|
||||
.name("name3")
|
||||
.type(appType)
|
||||
.version("version3")
|
||||
.vendor("vendor3")
|
||||
.description("description3")
|
||||
.build();
|
||||
|
||||
final List<SoftwareModule> modules = Arrays.asList(os, ah);
|
||||
|
||||
final long current = System.currentTimeMillis();
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post("/rest/v1/softwaremodules/").accept(MediaType.APPLICATION_JSON_VALUE)
|
||||
.content(JsonBuilder.softwareModules(modules)).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
final MvcResult mvcResult = mvc.perform(
|
||||
post("/rest/v1/softwaremodules/").accept(MediaType.APPLICATION_JSON_VALUE)
|
||||
.content(JsonBuilder.softwareModules(modules))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("[0].name", equalTo("name1")))
|
||||
.andExpect(jsonPath("[0].version", equalTo("version1")))
|
||||
.andExpect(jsonPath("[0].description", equalTo("description1")))
|
||||
.andExpect(jsonPath("[0].vendor", equalTo("vendor1"))).andExpect(jsonPath("[0].type", equalTo("os")))
|
||||
.andExpect(jsonPath("[0].vendor", equalTo("vendor1")))
|
||||
.andExpect(jsonPath("[0].type", equalTo("os")))
|
||||
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].name", equalTo("name3")))
|
||||
.andExpect(jsonPath("[1].version", equalTo("version3")))
|
||||
@@ -888,60 +947,62 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
.andExpect(jsonPath("[1].vendor", equalTo("vendor3")))
|
||||
.andExpect(jsonPath("[1].type", equalTo("application")))
|
||||
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
|
||||
.andExpect(jsonPath("[1].createdAt", not(equalTo(0)))).andReturn();
|
||||
.andExpect(jsonPath("[1].createdAt", not(equalTo(0))))
|
||||
.andReturn();
|
||||
|
||||
final SoftwareModule osCreated = softwareModuleManagement
|
||||
.getByNameAndVersionAndType("name1", "version1", osType.getId()).get();
|
||||
final SoftwareModule appCreated = softwareModuleManagement
|
||||
.getByNameAndVersionAndType("name3", "version3", appType.getId()).get();
|
||||
final SoftwareModule osCreated = softwareModuleManagement.getByNameAndVersionAndType("name1", "version1",
|
||||
osType.getId()).get();
|
||||
final SoftwareModule appCreated = softwareModuleManagement.getByNameAndVersionAndType("name3", "version3",
|
||||
appType.getId()).get();
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.as("Response contains invalid self href")
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId());
|
||||
assertThat(JsonPath.compile("[0]._links.self.href")
|
||||
.read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).as("Response contains invalid self href")
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + osCreated.getId());
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.as("Response contains links self href")
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId());
|
||||
assertThat(JsonPath.compile("[1]._links.self.href")
|
||||
.read(mvcResult.getResponse().getContentAsString())
|
||||
.toString()).as("Response contains links self href")
|
||||
.isEqualTo("http://localhost/rest/v1/softwaremodules/" + appCreated.getId());
|
||||
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("Wrong softwaremodule size").hasSize(2);
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getName())
|
||||
.as("Softwaremoudle name is wrong").isEqualTo(os.getName());
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getCreatedBy())
|
||||
.as("Softwaremoudle created by is wrong").isEqualTo("uploadTester");
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getCreatedAt())
|
||||
.as("Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, appType.getId()).getContent().get(0).getName())
|
||||
.as("Softwaremoudle name is wrong").isEqualTo(ah.getName());
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getName()).as(
|
||||
"Softwaremoudle name is wrong").isEqualTo(os.getName());
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getCreatedBy()).as(
|
||||
"Softwaremoudle created by is wrong").isEqualTo("uploadTester");
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, osType.getId()).getContent().get(0).getCreatedAt()).as(
|
||||
"Softwaremoudle created at is wrong").isGreaterThanOrEqualTo(current);
|
||||
assertThat(softwareModuleManagement.findByType(PAGE, appType.getId()).getContent().get(0).getName()).as(
|
||||
"Softwaremoudle name is wrong").isEqualTo(ah.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verifies successfull deletion of software modules that are not in use, i.e. assigned to a DS.")
|
||||
public void deleteUnassignedSoftwareModule() throws Exception {
|
||||
void deleteUnassignedSoftwareModule() throws Exception {
|
||||
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
final byte random[] = RandomStringUtils.random(artifactSize).getBytes();
|
||||
|
||||
artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("Softwaremoudle size is wrong").hasSize(1);
|
||||
assertThat(artifactManagement.count()).isEqualTo(1);
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId())).andDo(MockMvcResultPrinter.print())
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/{smId}", sm.getId()))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("After delete no softwarmodule should be available")
|
||||
.isEmpty();
|
||||
assertThat(artifactManagement.count()).isEqualTo(0);
|
||||
assertThat(artifactManagement.count()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verifies successfull deletion of a software module that is in use, i.e. assigned to a DS which should result in movinf the module to the archive.")
|
||||
public void deleteAssignedSoftwareModule() throws Exception {
|
||||
void deleteAssignedSoftwareModule() throws Exception {
|
||||
final DistributionSet ds1 = testdataFactory.createDistributionSet("a");
|
||||
|
||||
final int artifactSize = 5 * 1024;
|
||||
@@ -969,8 +1030,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Tests the deletion of an artifact including verfication that the artifact is actually erased in the repository and removed from the software module.")
|
||||
public void deleteArtifact() throws Exception {
|
||||
@Description("Tests the deletion of an artifact including verification that the artifact is actually erased in the repository and removed from the software module.")
|
||||
void deleteArtifact() throws Exception {
|
||||
// Create 1 SM
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
@@ -978,10 +1039,10 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
final byte random[] = RandomStringUtils.random(artifactSize).getBytes();
|
||||
|
||||
// Create 2 artifacts
|
||||
final Artifact artifact = artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
artifactManagement
|
||||
.create(new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
final Artifact artifact = artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file1", false, artifactSize));
|
||||
artifactManagement.create(
|
||||
new ArtifactUpload(new ByteArrayInputStream(random), sm.getId(), "file2", false, artifactSize));
|
||||
|
||||
// check repo before delete
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).hasSize(1);
|
||||
@@ -991,7 +1052,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
// delete
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/{smId}/artifacts/{artId}", sm.getId(), artifact.getId()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
// check that only one artifact is still alive and still assigned
|
||||
assertThat(softwareModuleManagement.findAll(PAGE)).as("After the sm should be marked as deleted").hasSize(1);
|
||||
@@ -1002,8 +1064,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies the successful creation of metadata and the enforcement of the meta data quota.")
|
||||
public void createMetadata() throws Exception {
|
||||
@Description("Verifies the successful creation of metadata and the enforcement of the meta data quota.")
|
||||
void createMetadata() throws Exception {
|
||||
|
||||
final String knownKey1 = "knownKey1";
|
||||
final String knownValue1 = "knownValue1";
|
||||
@@ -1020,18 +1082,17 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
.contentType(MediaType.APPLICATION_JSON).content(metaData1.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("[0]key", equalTo(knownKey1))).andExpect(jsonPath("[0]value", equalTo(knownValue1)))
|
||||
.andExpect(jsonPath("[0]targetVisible", equalTo(false)))
|
||||
.andExpect(jsonPath("[1]key", equalTo(knownKey2))).andExpect(jsonPath("[1]value", equalTo(knownValue2)))
|
||||
.andExpect(jsonPath("[1]targetVisible", equalTo(true)));
|
||||
.andExpect(jsonPath("[0].key", equalTo(knownKey1)))
|
||||
.andExpect(jsonPath("[0].value", equalTo(knownValue1)))
|
||||
.andExpect(jsonPath("[0].targetVisible", equalTo(false)))
|
||||
.andExpect(jsonPath("[1].key", equalTo(knownKey2)))
|
||||
.andExpect(jsonPath("[1].value", equalTo(knownValue2)))
|
||||
.andExpect(jsonPath("[1].targetVisible", equalTo(true)));
|
||||
|
||||
final SoftwareModuleMetadata metaKey1 = softwareModuleManagement
|
||||
.getMetaDataBySoftwareModuleId(sm.getId(), knownKey1).get();
|
||||
final SoftwareModuleMetadata metaKey2 = softwareModuleManagement
|
||||
.getMetaDataBySoftwareModuleId(sm.getId(), knownKey2).get();
|
||||
|
||||
assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1);
|
||||
assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2);
|
||||
assertThat(softwareModuleManagement.getMetaDataBySoftwareModuleId(sm.getId(), knownKey1))
|
||||
.as("Metadata key is wrong").get().extracting(SoftwareModuleMetadata::getValue).isEqualTo(knownValue1);
|
||||
assertThat(softwareModuleManagement.getMetaDataBySoftwareModuleId(sm.getId(), knownKey2))
|
||||
.as("Metadata key is wrong").get().extracting(SoftwareModuleMetadata::getValue).isEqualTo(knownValue2);
|
||||
|
||||
// verify quota enforcement
|
||||
final int maxMetaData = quotaManagement.getMaxMetaDataEntriesPerSoftwareModule();
|
||||
@@ -1054,8 +1115,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies the successfull update of metadata based on given key.")
|
||||
public void updateMetadata() throws Exception {
|
||||
@Description("Verifies the successful update of metadata based on given key.")
|
||||
void updateMetadata() throws Exception {
|
||||
// prepare and create metadata for update
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
@@ -1065,24 +1126,27 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
softwareModuleManagement.createMetaData(
|
||||
entityFactory.softwareModuleMetadata().create(sm.getId()).key(knownKey).value(knownValue));
|
||||
|
||||
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue)
|
||||
final JSONObject jsonObject = new JSONObject().put("key", knownKey)
|
||||
.put("value", updateValue)
|
||||
.put("targetVisible", true);
|
||||
|
||||
mvc.perform(put("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey)
|
||||
.accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)
|
||||
.content(jsonObject.toString())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
mvc.perform(put("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey).accept(
|
||||
MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).content(jsonObject.toString()))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
|
||||
.andExpect(jsonPath("key", equalTo(knownKey)))
|
||||
.andExpect(jsonPath("value", equalTo(updateValue)));
|
||||
|
||||
final SoftwareModuleMetadata assertDS = softwareModuleManagement
|
||||
.getMetaDataBySoftwareModuleId(sm.getId(), knownKey).get();
|
||||
final SoftwareModuleMetadata assertDS = softwareModuleManagement.getMetaDataBySoftwareModuleId(sm.getId(),
|
||||
knownKey).get();
|
||||
assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue);
|
||||
assertThat(assertDS.isTargetVisible()).as("target visible is wrong").isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies the successfull deletion of metadata entry.")
|
||||
public void deleteMetadata() throws Exception {
|
||||
@Description("Verifies the successful deletion of metadata entry.")
|
||||
void deleteMetadata() throws Exception {
|
||||
// prepare and create metadata for deletion
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
@@ -1092,14 +1156,15 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
entityFactory.softwareModuleMetadata().create(sm.getId()).key(knownKey).value(knownValue));
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/{key}", sm.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isOk());
|
||||
|
||||
assertThat(softwareModuleManagement.getMetaDataBySoftwareModuleId(sm.getId(), knownKey)).isNotPresent();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that module metadta deletion request to API on an entity that does not exist results in NOT_FOUND.")
|
||||
public void deleteModuleMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
@Description("Ensures that module metadata deletion request to API on an entity that does not exist results in NOT_FOUND.")
|
||||
void deleteModuleMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
// prepare and create metadata for deletion
|
||||
final String knownKey = "knownKey";
|
||||
final String knownValue = "knownValue";
|
||||
@@ -1109,7 +1174,8 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
entityFactory.softwareModuleMetadata().create(sm.getId()).key(knownKey).value(knownValue));
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/{swId}/metadata/XXX", sm.getId(), knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/1234/metadata/{key}", knownKey))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
|
||||
@@ -1119,22 +1185,25 @@ public class MgmtSoftwareModuleResourceTest extends AbstractManagementApiIntegra
|
||||
|
||||
@Test
|
||||
@Description("Ensures that module deletion request to API on an entity that does not exist results in NOT_FOUND.")
|
||||
public void deleteSoftwareModuleThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/1234")).andDo(MockMvcResultPrinter.print())
|
||||
void deleteSoftwareModuleThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
mvc.perform(delete("/rest/v1/softwaremodules/1234"))
|
||||
.andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies the successfull search of a metadata entry based on value.")
|
||||
public void searchSoftwareModuleMetadataRsql() throws Exception {
|
||||
@Description("Verifies the successful search of a metadata entry based on value.")
|
||||
void searchSoftwareModuleMetadataRsql() throws Exception {
|
||||
final int totalMetadata = 10;
|
||||
final String knownKeyPrefix = "knownKey";
|
||||
final String knownValuePrefix = "knownValue";
|
||||
final SoftwareModule sm = testdataFactory.createSoftwareModuleOs();
|
||||
|
||||
for (int index = 0; index < totalMetadata; index++) {
|
||||
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata().create(sm.getId())
|
||||
.key(knownKeyPrefix + index).value(knownValuePrefix + index));
|
||||
softwareModuleManagement.createMetaData(entityFactory.softwareModuleMetadata()
|
||||
.create(sm.getId())
|
||||
.key(knownKeyPrefix + index)
|
||||
.value(knownValuePrefix + index));
|
||||
}
|
||||
|
||||
final String rsqlSearchValue1 = "value==knownValue1";
|
||||
|
||||
@@ -25,25 +25,29 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
import org.awaitility.Awaitility;
|
||||
import org.awaitility.Duration;
|
||||
import org.eclipse.hawkbit.exception.SpServerError;
|
||||
import org.eclipse.hawkbit.im.authentication.SpPermission;
|
||||
import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType;
|
||||
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
|
||||
import org.eclipse.hawkbit.repository.ActionFields;
|
||||
import org.eclipse.hawkbit.repository.Identifiable;
|
||||
import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException;
|
||||
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
|
||||
import org.eclipse.hawkbit.repository.model.Action;
|
||||
@@ -93,7 +97,7 @@ import io.qameta.allure.Story;
|
||||
*/
|
||||
@Feature("Component Tests - Management API")
|
||||
@Story("Target Resource")
|
||||
public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest {
|
||||
|
||||
private static final String TARGET_DESCRIPTION_TEST = "created in test";
|
||||
|
||||
@@ -127,8 +131,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
private JpaProperties jpaProperties;
|
||||
|
||||
@Test
|
||||
@Description("Ensures that actions list is in exptected order.")
|
||||
public void getActionStatusReturnsCorrectType() throws Exception {
|
||||
@Description("Ensures that actions list is in expected order.")
|
||||
void getActionStatusReturnsCorrectType() throws Exception {
|
||||
final int limitSize = 2;
|
||||
final String knownTargetId = "targetId";
|
||||
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
|
||||
@@ -159,7 +163,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
@Test
|
||||
@Description("Ensures that security token is not returned if user does not have READ_TARGET_SEC_TOKEN permission.")
|
||||
@WithUser(allSpPermissions = false, authorities = { SpPermission.READ_TARGET, SpPermission.CREATE_TARGET })
|
||||
public void securityTokenIsNotInResponseIfMissingPermission() throws Exception {
|
||||
void securityTokenIsNotInResponseIfMissingPermission() throws Exception {
|
||||
|
||||
final String knownControllerId = "knownControllerId";
|
||||
testdataFactory.createTarget(knownControllerId);
|
||||
@@ -172,7 +176,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
@Description("Ensures that security token is returned if user does have READ_TARGET_SEC_TOKEN permission.")
|
||||
@WithUser(allSpPermissions = false, authorities = { SpPermission.READ_TARGET, SpPermission.CREATE_TARGET,
|
||||
SpPermission.READ_TARGET_SEC_TOKEN })
|
||||
public void securityTokenIsInResponseWithCorrectPermission() throws Exception {
|
||||
void securityTokenIsInResponseWithCorrectPermission() throws Exception {
|
||||
|
||||
final String knownControllerId = "knownControllerId";
|
||||
final Target createTarget = testdataFactory.createTarget(knownControllerId);
|
||||
@@ -183,7 +187,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that that IP address is in result as stored in the repository.")
|
||||
public void addressAndIpAddressInTargetResult() throws Exception {
|
||||
void addressAndIpAddressInTargetResult() throws Exception {
|
||||
// prepare targets with IP
|
||||
final String knownControllerId1 = "0815";
|
||||
final String knownControllerId2 = "4711";
|
||||
@@ -212,13 +216,13 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that actions history is returned as defined by filter status==pending,status==finished.")
|
||||
public void searchActionsRsql() throws Exception {
|
||||
void searchActionsRsql() throws Exception {
|
||||
|
||||
// prepare test
|
||||
final DistributionSet dsA = testdataFactory.createDistributionSet("");
|
||||
final Target createTarget = testdataFactory.createTarget("knownTargetId");
|
||||
|
||||
assignDistributionSet(dsA, Arrays.asList(createTarget));
|
||||
assignDistributionSet(dsA, Collections.singletonList(createTarget));
|
||||
|
||||
final String rsqlPendingStatus = "status==pending";
|
||||
final String rsqlFinishedStatus = "status==finished";
|
||||
@@ -243,8 +247,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a deletion of an active action results in cancelation triggered.")
|
||||
public void cancelActionOK() throws Exception {
|
||||
@Description("Ensures that a deletion of an active action results in cancellation triggered.")
|
||||
void cancelActionOK() throws Exception {
|
||||
// prepare test
|
||||
final Target tA = createTargetAndStartAction();
|
||||
|
||||
@@ -269,8 +273,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that method not allowed is returned if cancelation is triggered on already canceled action.")
|
||||
public void cancelAndCancelActionIsNotAllowed() throws Exception {
|
||||
@Description("Ensures that method not allowed is returned if cancellation is triggered on already canceled action.")
|
||||
void cancelAndCancelActionIsNotAllowed() throws Exception {
|
||||
// prepare test
|
||||
final Target tA = createTargetAndStartAction();
|
||||
|
||||
@@ -291,7 +295,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Force Quit an Action, which is already canceled. Expected Result is an HTTP response code 204.")
|
||||
public void forceQuitAnCanceledActionReturnsOk() throws Exception {
|
||||
void forceQuitAnCanceledActionReturnsOk() throws Exception {
|
||||
|
||||
final Target tA = createTargetAndStartAction();
|
||||
|
||||
@@ -305,7 +309,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
assertThat(cancelActions).hasSize(1);
|
||||
assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue();
|
||||
|
||||
// test - force quit an canceled action should return 204
|
||||
// test - force quit: Canceled actions should return 204
|
||||
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true",
|
||||
tA.getControllerId(), cancelActions.get(0).getId())).andDo(MockMvcResultPrinter.print())
|
||||
.andExpect(status().isNoContent());
|
||||
@@ -313,7 +317,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Force Quit an Action, which is not canceled. Expected Result is an HTTP response code 405.")
|
||||
public void forceQuitAnNotCanceledActionReturnsMethodNotAllowed() throws Exception {
|
||||
void forceQuitAnNotCanceledActionReturnsMethodNotAllowed() throws Exception {
|
||||
|
||||
final Target tA = createTargetAndStartAction();
|
||||
|
||||
@@ -327,7 +331,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that deletion is executed if permitted.")
|
||||
public void deleteTargetReturnsOK() throws Exception {
|
||||
void deleteTargetReturnsOK() throws Exception {
|
||||
final String knownControllerId = "knownControllerIdDelete";
|
||||
testdataFactory.createTarget(knownControllerId);
|
||||
|
||||
@@ -339,7 +343,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that deletion is refused with not found if target does not exist.")
|
||||
public void deleteTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
|
||||
void deleteTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
|
||||
final String knownControllerId = "knownControllerIdDelete";
|
||||
|
||||
mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId))
|
||||
@@ -348,7 +352,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that update is refused with not found if target does not exist.")
|
||||
public void updateTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
|
||||
void updateTargetWhichDoesNotExistsLeadsToNotFound() throws Exception {
|
||||
final String knownControllerId = "knownControllerIdUpdate";
|
||||
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}")
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
|
||||
@@ -357,37 +361,37 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target update request is reflected by repository.")
|
||||
public void updateTargetDescription() throws Exception {
|
||||
void updateTargetDescription() throws Exception {
|
||||
final String knownControllerId = "123";
|
||||
final String knownNewDescription = "a new desc updated over rest";
|
||||
final String knownNameNotModiy = "nameNotModiy";
|
||||
final String knownNameNotModify = "nameNotModify";
|
||||
final String body = new JSONObject().put("description", knownNewDescription).toString();
|
||||
|
||||
// prepare
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy)
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModify)
|
||||
.description("old description"));
|
||||
|
||||
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.controllerId", equalTo(knownControllerId)))
|
||||
.andExpect(jsonPath("$.description", equalTo(knownNewDescription)))
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModify)));
|
||||
|
||||
final Target findTargetByControllerID = targetManagement.getByControllerID(knownControllerId).get();
|
||||
assertThat(findTargetByControllerID.getDescription()).isEqualTo(knownNewDescription);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModify);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target update request fails is updated value fails against a constraint.")
|
||||
public void updateTargetDescriptionFailsIfInvalidLength() throws Exception {
|
||||
void updateTargetDescriptionFailsIfInvalidLength() throws Exception {
|
||||
final String knownControllerId = "123";
|
||||
final String knownNewDescription = RandomStringUtils.randomAlphabetic(513);
|
||||
final String knownNameNotModiy = "nameNotModiy";
|
||||
final String knownNameNotModify = "nameNotModify";
|
||||
final String body = new JSONObject().put("description", knownNewDescription).toString();
|
||||
|
||||
// prepare
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy)
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModify)
|
||||
.description("old description"));
|
||||
|
||||
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
|
||||
@@ -400,53 +404,53 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target update request is reflected by repository.")
|
||||
public void updateTargetSecurityToken() throws Exception {
|
||||
void updateTargetSecurityToken() throws Exception {
|
||||
final String knownControllerId = "123";
|
||||
final String knownNewToken = "6567576565";
|
||||
final String knownNameNotModiy = "nameNotModiy";
|
||||
final String knownNameNotModify = "nameNotModify";
|
||||
final String body = new JSONObject().put("securityToken", knownNewToken).toString();
|
||||
|
||||
// prepare
|
||||
targetManagement
|
||||
.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy));
|
||||
.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModify));
|
||||
|
||||
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.controllerId", equalTo(knownControllerId)))
|
||||
.andExpect(jsonPath("$.securityToken", equalTo(knownNewToken)))
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModify)));
|
||||
|
||||
final Target findTargetByControllerID = targetManagement.getByControllerID(knownControllerId).get();
|
||||
assertThat(findTargetByControllerID.getSecurityToken()).isEqualTo(knownNewToken);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModify);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target update request is reflected by repository.")
|
||||
public void updateTargetAddress() throws Exception {
|
||||
void updateTargetAddress() throws Exception {
|
||||
final String knownControllerId = "123";
|
||||
final String knownNewAddress = "amqp://test123/foobar";
|
||||
final String knownNameNotModiy = "nameNotModiy";
|
||||
final String knownNameNotModify = "nameNotModify";
|
||||
final String body = new JSONObject().put("address", knownNewAddress).toString();
|
||||
|
||||
// prepare
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModiy)
|
||||
targetManagement.create(entityFactory.target().create().controllerId(knownControllerId).name(knownNameNotModify)
|
||||
.address(knownNewAddress));
|
||||
|
||||
mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body)
|
||||
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.controllerId", equalTo(knownControllerId)))
|
||||
.andExpect(jsonPath("$.address", equalTo(knownNewAddress)))
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModiy)));
|
||||
.andExpect(jsonPath("$.name", equalTo(knownNameNotModify)));
|
||||
|
||||
final Target findTargetByControllerID = targetManagement.getByControllerID(knownControllerId).get();
|
||||
assertThat(findTargetByControllerID.getAddress().toString()).isEqualTo(knownNewAddress);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModiy);
|
||||
assertThat(findTargetByControllerID.getAddress()).hasToString(knownNewAddress);
|
||||
assertThat(findTargetByControllerID.getName()).isEqualTo(knownNameNotModify);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target query returns list of targets in defined format.")
|
||||
public void getTargetWithoutAddtionalRequestParameters() throws Exception {
|
||||
void getTargetWithoutAdditionalRequestParameters() throws Exception {
|
||||
final int knownTargetAmount = 3;
|
||||
final String idA = "a";
|
||||
final String idB = "b";
|
||||
@@ -489,7 +493,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target query returns list of targets in defined format in size reduced by given limit parameter.")
|
||||
public void getTargetWithPagingLimitRequestParameter() throws Exception {
|
||||
void getTargetWithPagingLimitRequestParameter() throws Exception {
|
||||
final int knownTargetAmount = 3;
|
||||
final int limitSize = 1;
|
||||
createTargetsAlphabetical(knownTargetAmount);
|
||||
@@ -514,7 +518,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target query returns list of targets in defined format in size reduced by given limit and offset parameter.")
|
||||
public void getTargetWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
void getTargetWithPagingLimitAndOffsetRequestParameter() throws Exception {
|
||||
final int knownTargetAmount = 5;
|
||||
final int offsetParam = 2;
|
||||
final int expectedSize = knownTargetAmount - offsetParam;
|
||||
@@ -559,7 +563,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the get request for a target works.")
|
||||
public void getSingleTarget() throws Exception {
|
||||
void getSingleTarget() throws Exception {
|
||||
// create first a target which can be retrieved by rest interface
|
||||
final String knownControllerId = "1";
|
||||
final String knownName = "someName";
|
||||
@@ -583,7 +587,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target get request returns a not found if the target does not exits.")
|
||||
public void getSingleTargetNoExistsResponseNotFound() throws Exception {
|
||||
void getSingleTargetNoExistsResponseNotFound() throws Exception {
|
||||
|
||||
final String targetIdNotExists = "bubu";
|
||||
|
||||
@@ -600,7 +604,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that get request for asigned distribution sets returns no count if no distribution set has been assigned.")
|
||||
public void getAssignedDistributionSetOfTargetIsEmpty() throws Exception {
|
||||
void getAssignedDistributionSetOfTargetIsEmpty() throws Exception {
|
||||
// create first a target which can be retrieved by rest interface
|
||||
final String knownControllerId = "1";
|
||||
final String knownName = "someName";
|
||||
@@ -614,7 +618,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the get request for asigned distribution sets works.")
|
||||
public void getAssignedDistributionSetOfTarget() throws Exception {
|
||||
void getAssignedDistributionSetOfTarget() throws Exception {
|
||||
// create first a target which can be retrieved by rest interface
|
||||
final String knownControllerId = "1";
|
||||
final String knownName = "someName";
|
||||
@@ -671,7 +675,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that get request for installed distribution sets returns no count if no distribution set has been installed.")
|
||||
public void getInstalledDistributionSetOfTargetIsEmpty() throws Exception {
|
||||
void getInstalledDistributionSetOfTargetIsEmpty() throws Exception {
|
||||
// create first a target which can be retrieved by rest interface
|
||||
final String knownControllerId = "1";
|
||||
final String knownName = "someName";
|
||||
@@ -683,12 +687,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a target creation with empty name and a controllerId that exceeds the name length limitation is successful and the name gets truncated.")
|
||||
public void createTargetWithEmptyNameAndLongControllerId() throws Exception {
|
||||
void createTargetWithEmptyNameAndLongControllerId() throws Exception {
|
||||
final String randomString = RandomStringUtils.randomAlphanumeric(JpaTarget.CONTROLLER_ID_MAX_SIZE);
|
||||
|
||||
final Target target = entityFactory.target().create().controllerId(randomString).build();
|
||||
|
||||
final String targetList = JsonBuilder.targets(Arrays.asList(target), false);
|
||||
final String targetList = JsonBuilder.targets(Collections.singletonList(target), false);
|
||||
|
||||
final String expectedTargetName = randomString.substring(0,
|
||||
Math.min(JpaTarget.CONTROLLER_ID_MAX_SIZE, NamedEntity.NAME_MAX_SIZE));
|
||||
@@ -703,13 +707,13 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that post request for creating a target with no payload returns a bad request.")
|
||||
public void createTargetWithoutPayloadBadRequest() throws Exception {
|
||||
void createTargetWithoutPayloadBadRequest() throws Exception {
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
|
||||
|
||||
assertThat(targetManagement.count()).isEqualTo(0);
|
||||
assertThat(targetManagement.count()).isZero();
|
||||
|
||||
// verify response json exception message
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
@@ -720,7 +724,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that post request for creating a target with invalid payload returns a bad request.")
|
||||
public void createTargetWithBadPayloadBadRequest() throws Exception {
|
||||
void createTargetWithBadPayloadBadRequest() throws Exception {
|
||||
final String notJson = "abc";
|
||||
|
||||
final MvcResult mvcResult = mvc
|
||||
@@ -728,7 +732,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
|
||||
|
||||
assertThat(targetManagement.count()).isEqualTo(0);
|
||||
assertThat(targetManagement.count()).isZero();
|
||||
|
||||
// verify response json exception message
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
@@ -738,14 +742,14 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that a mandatory properties of new targets are validated as not null.")
|
||||
public void createTargetWithMissingMandatoryPropertyBadRequest() throws Exception {
|
||||
@Description("Verifies that a mandatory properties of new targets are validated as not null.")
|
||||
void createTargetWithMissingMandatoryPropertyBadRequest() throws Exception {
|
||||
final MvcResult mvcResult = mvc
|
||||
.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content("[{\"name\":\"id1\"}]")
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
|
||||
|
||||
assertThat(targetManagement.count()).isEqualTo(0);
|
||||
assertThat(targetManagement.count()).isZero();
|
||||
|
||||
// verify response json exception message
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
@@ -756,15 +760,16 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verfies that a properties of new targets are validated as in allowed size range.")
|
||||
public void createTargetWithInvalidPropertyBadRequest() throws Exception {
|
||||
void createTargetWithInvalidPropertyBadRequest() throws Exception {
|
||||
final Target test1 = entityFactory.target().create().controllerId("id1")
|
||||
.name(RandomStringUtils.randomAlphanumeric(NamedEntity.NAME_MAX_SIZE + 1)).build();
|
||||
|
||||
final MvcResult mvcResult = mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING)
|
||||
.content(JsonBuilder.targets(Arrays.asList(test1), true)).contentType(MediaType.APPLICATION_JSON))
|
||||
.content(JsonBuilder.targets(Collections.singletonList(test1), true))
|
||||
.contentType(MediaType.APPLICATION_JSON))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn();
|
||||
|
||||
assertThat(targetManagement.count()).isEqualTo(0);
|
||||
assertThat(targetManagement.count()).isZero();
|
||||
|
||||
// verify response json exception message
|
||||
final ExceptionInfo exceptionInfo = ResourceUtility
|
||||
@@ -775,7 +780,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating multiple targets works.")
|
||||
public void createTargetsListReturnsSuccessful() throws Exception {
|
||||
void createTargetsListReturnsSuccessful() throws Exception {
|
||||
final Target test1 = entityFactory.target().create().controllerId("id1").name("testname1")
|
||||
.securityToken("token").address("amqp://test123/foobar").description("testid1").build();
|
||||
final Target test2 = entityFactory.target().create().controllerId("id2").name("testname2")
|
||||
@@ -810,32 +815,35 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
.andExpect(jsonPath("[2].createdBy", equalTo("bumlux"))).andReturn();
|
||||
|
||||
assertThat(
|
||||
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
JsonPath.compile("[0]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/targets/id1");
|
||||
assertThat(
|
||||
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
JsonPath.compile("[1]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/targets/id2");
|
||||
assertThat(
|
||||
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
JsonPath.compile("[2]._links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
|
||||
.isEqualTo("http://localhost/rest/v1/targets/id3");
|
||||
|
||||
assertThat(targetManagement.getByControllerID("id1")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getName()).isEqualTo("testname1");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getDescription()).isEqualTo("testid1");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getSecurityToken()).isEqualTo("token");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getAddress().toString())
|
||||
.isEqualTo("amqp://test123/foobar");
|
||||
assertThat(targetManagement.getByControllerID("id2")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id2").get().getName()).isEqualTo("testname2");
|
||||
assertThat(targetManagement.getByControllerID("id2").get().getDescription()).isEqualTo("testid2");
|
||||
assertThat(targetManagement.getByControllerID("id3")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id3").get().getName()).isEqualTo("testname3");
|
||||
assertThat(targetManagement.getByControllerID("id3").get().getDescription()).isEqualTo("testid3");
|
||||
final Target t1 = assertTarget("id1", "testname1", "testid1");
|
||||
assertThat(t1.getSecurityToken()).isEqualTo("token");
|
||||
assertThat(t1.getAddress()).hasToString("amqp://test123/foobar");
|
||||
|
||||
assertTarget("id2", "testname2", "testid2");
|
||||
assertTarget("id3", "testname3", "testid3");
|
||||
}
|
||||
|
||||
private Target assertTarget(final String controllerId, final String name, final String description) {
|
||||
final Optional<Target> target1 = targetManagement.getByControllerID(controllerId);
|
||||
assertThat(target1).isPresent();
|
||||
final Target t = target1.get();
|
||||
assertThat(t.getName()).isEqualTo(name);
|
||||
assertThat(t.getDescription()).isEqualTo(description);
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating one target within a list works.")
|
||||
public void createTargetsSingleEntryListReturnsSuccessful() throws Exception {
|
||||
void createTargetsSingleEntryListReturnsSuccessful() throws Exception {
|
||||
final String knownName = "someName";
|
||||
final String knownControllerId = "controllerId1";
|
||||
final String knownDescription = "someDescription";
|
||||
@@ -855,7 +863,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating the same target again leads to a conflict response.")
|
||||
public void createTargetsSingleEntryListDoubleReturnConflict() throws Exception {
|
||||
void createTargetsSingleEntryListDoubleReturnConflict() throws Exception {
|
||||
final String knownName = "someName";
|
||||
final String knownControllerId = "controllerId1";
|
||||
final String knownDescription = "someDescription";
|
||||
@@ -885,7 +893,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the get request for action of a target returns no actions if nothing has happened.")
|
||||
public void getActionWithEmptyResult() throws Exception {
|
||||
void getActionWithEmptyResult() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
testdataFactory.createTarget(knownTargetId);
|
||||
|
||||
@@ -897,7 +905,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response is returned for update action.")
|
||||
public void getUpdateAction() throws Exception {
|
||||
void getUpdateAction() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
|
||||
|
||||
@@ -918,7 +926,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response is returned for update action with maintenance window.")
|
||||
public void getUpdateActionWithMaintenanceWindow() throws Exception {
|
||||
void getUpdateActionWithMaintenanceWindow() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final String schedule = getTestSchedule(10);
|
||||
final String duration = getTestDuration(10);
|
||||
@@ -947,7 +955,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response is returned when update action was cancelled.")
|
||||
public void getCancelAction() throws Exception {
|
||||
void getCancelAction() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
|
||||
|
||||
@@ -968,7 +976,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response is returned when update action with maintenance window was cancelled.")
|
||||
public void getCancelActionWithMaintenanceWindow() throws Exception {
|
||||
void getCancelActionWithMaintenanceWindow() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final String schedule = getTestSchedule(10);
|
||||
final String duration = getTestDuration(10);
|
||||
@@ -997,7 +1005,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response of geting actions of a target is returned.")
|
||||
public void getMultipleActions() throws Exception {
|
||||
void getMultipleActions() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
|
||||
|
||||
@@ -1021,7 +1029,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the expected response of getting actions with maintenance window of a target is returned.")
|
||||
public void getMultipleActionsWithMaintenanceWindow() throws Exception {
|
||||
void getMultipleActionsWithMaintenanceWindow() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final String schedule = getTestSchedule(10);
|
||||
final String duration = getTestDuration(10);
|
||||
@@ -1059,7 +1067,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verifies that the API returns the status list with expected content.")
|
||||
public void getMultipleActionStatus() throws Exception {
|
||||
void getMultipleActionStatus() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
|
||||
// retrieve list in default descending order for actionstaus entries
|
||||
@@ -1087,11 +1095,11 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verifies that the API returns the status list with expected content sorted by reportedAt field.")
|
||||
public void getMultipleActionStatusSortedByReportedAt() throws Exception {
|
||||
void getMultipleActionStatusSortedByReportedAt() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
|
||||
final List<ActionStatus> actionStatus = deploymentManagement.findActionStatusByAction(PAGE, action.getId())
|
||||
.getContent().stream().sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId()))
|
||||
.getContent().stream().sorted(Comparator.comparingLong(Identifiable::getId))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// descending order
|
||||
@@ -1133,7 +1141,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verifies that the API returns the status list with expected content split into two pages.")
|
||||
public void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception {
|
||||
void getMultipleActionStatusWithPagingLimitRequestParameter() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
|
||||
final Action action = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId).get(0);
|
||||
@@ -1173,7 +1181,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verifies getting multiple actions with the paging request parameter.")
|
||||
public void getMultipleActionsWithPagingLimitRequestParameter() throws Exception {
|
||||
void getMultipleActionsWithPagingLimitRequestParameter() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final List<Action> actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId);
|
||||
|
||||
@@ -1230,13 +1238,12 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
+ "?offset=0&limit=50&sort=id:DESC";
|
||||
}
|
||||
|
||||
private List<Action> generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId)
|
||||
throws InterruptedException {
|
||||
private List<Action> generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) {
|
||||
return generateTargetWithTwoUpdatesWithOneOverrideWithMaintenanceWindow(knownTargetId, null, null, null);
|
||||
}
|
||||
|
||||
private List<Action> generateTargetWithTwoUpdatesWithOneOverrideWithMaintenanceWindow(final String knownTargetId,
|
||||
final String schedule, final String duration, final String timezone) throws InterruptedException {
|
||||
final String schedule, final String duration, final String timezone) {
|
||||
final Target target = testdataFactory.createTarget(knownTargetId);
|
||||
|
||||
final Iterator<DistributionSet> sets = testdataFactory.createDistributionSets(2).iterator();
|
||||
@@ -1245,11 +1252,14 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
// Update
|
||||
if (schedule == null) {
|
||||
final List<Target> updatedTargets = assignDistributionSet(one, Arrays.asList(target)).getAssignedEntity()
|
||||
final List<Target> updatedTargets = assignDistributionSet(one, Collections.singletonList(target))
|
||||
.getAssignedEntity()
|
||||
.stream().map(Action::getTarget).collect(Collectors.toList());
|
||||
// 2nd update
|
||||
// sleep 10ms to ensure that we can sort by reportedAt
|
||||
Thread.sleep(10);
|
||||
Awaitility.await().atMost(Duration.ONE_HUNDRED_MILLISECONDS).atLeast(5, TimeUnit.MILLISECONDS)
|
||||
.pollInterval(10, TimeUnit.MILLISECONDS)
|
||||
.until(() -> updatedTargets.stream().allMatch(t -> t.getLastModifiedAt() > 0L));
|
||||
assignDistributionSet(two, updatedTargets);
|
||||
} else {
|
||||
final List<Target> updatedTargets = assignDistributionSetWithMaintenanceWindow(one.getId(),
|
||||
@@ -1257,7 +1267,9 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
.map(Action::getTarget).collect(Collectors.toList());
|
||||
// 2nd update
|
||||
// sleep 10ms to ensure that we can sort by reportedAt
|
||||
Thread.sleep(10);
|
||||
Awaitility.await().atMost(Duration.ONE_HUNDRED_MILLISECONDS).atLeast(5, TimeUnit.MILLISECONDS)
|
||||
.pollInterval(10, TimeUnit.MILLISECONDS)
|
||||
.until(() -> updatedTargets.stream().allMatch(t -> t.getLastModifiedAt() > 0L));
|
||||
assignDistributionSetWithMaintenanceWindow(two.getId(), updatedTargets.get(0).getControllerId(), schedule,
|
||||
duration, timezone);
|
||||
}
|
||||
@@ -1272,7 +1284,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verfies that an action is switched from soft to forced if requested by management API")
|
||||
public void updateAction() throws Exception {
|
||||
void updateAction() throws Exception {
|
||||
final Target target = testdataFactory.createTarget();
|
||||
final DistributionSet set = testdataFactory.createDistributionSet();
|
||||
final Long actionId = getFirstAssignedActionId(
|
||||
@@ -1299,7 +1311,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
@Test
|
||||
@Description("Verfies that a DS to target assignment is reflected by the repository and that repeating "
|
||||
+ "the assignment does not change the target.")
|
||||
public void assignDistributionSetToTarget() throws Exception {
|
||||
void assignDistributionSetToTarget() throws Exception {
|
||||
|
||||
Target target = testdataFactory.createTarget();
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1326,7 +1338,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Verfies that a DOWNLOAD_ONLY DS to target assignment is properly handled")
|
||||
public void assignDownloadOnlyDistributionSetToTarget() throws Exception {
|
||||
void assignDownloadOnlyDistributionSetToTarget() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget();
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1339,15 +1351,14 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId()).get()).isEqualTo(set);
|
||||
final Slice<Action> actions = deploymentManagement.findActionsByTarget("targetExist", PageRequest.of(0, 100));
|
||||
assertThat(actions.getSize()).isGreaterThan(0);
|
||||
actions.stream().filter(a -> a.getDistributionSet().equals(set))
|
||||
.forEach(a -> ActionType.DOWNLOAD_ONLY.equals(a.getActionType()));
|
||||
assertThat(actions).isNotEmpty().filteredOn(a -> a.getDistributionSet().equals(set))
|
||||
.extracting(Action::getActionType).containsOnly(ActionType.DOWNLOAD_ONLY);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Verfies that an offline DS to target assignment is reflected by the repository and that repeating "
|
||||
+ "the assignment does not change the target.")
|
||||
public void offlineAssignDistributionSetToTarget() throws Exception {
|
||||
void offlineAssignDistributionSetToTarget() throws Exception {
|
||||
|
||||
Target target = testdataFactory.createTarget();
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1377,7 +1388,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void assignDistributionSetToTargetWithActionTimeForcedAndTime() throws Exception {
|
||||
void assignDistributionSetToTargetWithActionTimeForcedAndTime() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1400,7 +1411,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assigns distribution set to target with only maintenance schedule.")
|
||||
public void assignDistributionSetToTargetWithMaintenanceWindowStartTimeOnly() throws Exception {
|
||||
void assignDistributionSetToTargetWithMaintenanceWindowStartTimeOnly() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1415,7 +1426,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assigns distribution set to target with only maintenance window duration.")
|
||||
public void assignDistributionSetToTargetWithMaintenanceWindowEndTimeOnly() throws Exception {
|
||||
void assignDistributionSetToTargetWithMaintenanceWindowEndTimeOnly() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1430,7 +1441,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assigns distribution set to target with valid maintenance window.")
|
||||
public void assignDistributionSetToTargetWithValidMaintenanceWindow() throws Exception {
|
||||
void assignDistributionSetToTargetWithValidMaintenanceWindow() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1447,7 +1458,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assigns distribution set to target with maintenance window next execution start (should be ignored, calculated automaticaly based on schedule, duration and timezone)")
|
||||
public void assignDistributionSetToTargetWithMaintenanceWindowNextExecutionStart() throws Exception {
|
||||
void assignDistributionSetToTargetWithMaintenanceWindowNextExecutionStart() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1469,7 +1480,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assigns distribution set to target with last maintenance window scheduled before current time.")
|
||||
public void assignDistributionSetToTargetWithMaintenanceWindowEndTimeBeforeStartTime() throws Exception {
|
||||
void assignDistributionSetToTargetWithMaintenanceWindowEndTimeBeforeStartTime() throws Exception {
|
||||
|
||||
final Target target = testdataFactory.createTarget("fsdfsd");
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
@@ -1485,7 +1496,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidRequestsOnAssignDistributionSetToTarget() throws Exception {
|
||||
void invalidRequestsOnAssignDistributionSetToTarget() throws Exception {
|
||||
|
||||
final DistributionSet set = testdataFactory.createDistributionSet("one");
|
||||
|
||||
@@ -1514,7 +1525,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidRequestsOnActionResource() throws Exception {
|
||||
void invalidRequestsOnActionResource() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
|
||||
// target does not exist
|
||||
@@ -1546,7 +1557,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidRequestsOnActionStatusResource() throws Exception {
|
||||
void invalidRequestsOnActionStatusResource() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
|
||||
// target does not exist
|
||||
@@ -1579,7 +1590,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getControllerAttributesViaTargetResourceReturnsAttributesWithOk() throws Exception {
|
||||
void getControllerAttributesViaTargetResourceReturnsAttributesWithOk() throws Exception {
|
||||
// create target with attributes
|
||||
final String knownTargetId = "targetIdWithAttributes";
|
||||
final Map<String, String> knownControllerAttrs = new HashMap<>();
|
||||
@@ -1595,7 +1606,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getControllerEmptyAttributesReturnsNoContent() throws Exception {
|
||||
void getControllerEmptyAttributesReturnsNoContent() throws Exception {
|
||||
// create target with attributes
|
||||
final String knownTargetId = "targetIdWithAttributes";
|
||||
testdataFactory.createTarget(knownTargetId);
|
||||
@@ -1607,7 +1618,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Request update of Controller Attributes.")
|
||||
public void triggerControllerAttributesUpdate() throws Exception {
|
||||
void triggerControllerAttributesUpdate() throws Exception {
|
||||
// create target with attributes
|
||||
final String knownTargetId = "targetIdNeedsUpdate";
|
||||
final Map<String, String> knownControllerAttrs = new HashMap<>();
|
||||
@@ -1656,7 +1667,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void searchTargetsUsingRsqlQuery() throws Exception {
|
||||
void searchTargetsUsingRsqlQuery() throws Exception {
|
||||
final int amountTargets = 10;
|
||||
createTargetsAlphabetical(amountTargets);
|
||||
|
||||
@@ -1686,7 +1697,6 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
*
|
||||
* @param amount
|
||||
* The number of targets to create
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
private void createTargetsAlphabetical(final int amount) {
|
||||
char character = 'a';
|
||||
@@ -1717,7 +1727,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that the metadata creation through API is reflected by the repository.")
|
||||
public void createMetadata() throws Exception {
|
||||
void createMetadata() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
testdataFactory.createTarget(knownControllerId);
|
||||
|
||||
@@ -1735,9 +1745,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
.contentType(MediaType.APPLICATION_JSON).content(metaData1.toString()))
|
||||
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
|
||||
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
|
||||
.andExpect(jsonPath("[0]key", equalTo(knownKey1))).andExpect(jsonPath("[0]value", equalTo(knownValue1)))
|
||||
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
|
||||
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
|
||||
.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 TargetMetadata metaKey1 = targetManagement.getMetaDataByControllerId(knownControllerId, knownKey1).get();
|
||||
final TargetMetadata metaKey2 = targetManagement.getMetaDataByControllerId(knownControllerId, knownKey2).get();
|
||||
@@ -1766,7 +1777,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata update through API is reflected by the repository.")
|
||||
public void updateMetadata() throws Exception {
|
||||
void updateMetadata() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
// prepare and create metadata for update
|
||||
@@ -1799,7 +1810,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry deletion through API is reflected by the repository.")
|
||||
public void deleteMetadata() throws Exception {
|
||||
void deleteMetadata() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
// prepare and create metadata for deletion
|
||||
@@ -1816,7 +1827,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that target metadata deletion request to API on an entity that does not exist results in NOT_FOUND.")
|
||||
public void deleteMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
void deleteMetadataThatDoesNotExistLeadsToNotFound() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
// prepare and create metadata for deletion
|
||||
@@ -1836,7 +1847,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry selection through API reflectes the repository content.")
|
||||
public void getSingleMetadata() throws Exception {
|
||||
void getSingleMetadata() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
// prepare and create metadata for deletion
|
||||
@@ -1852,7 +1863,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a metadata entry paged list selection through API reflectes the repository content.")
|
||||
public void getPagedListOfMetadata() throws Exception {
|
||||
void getPagedListOfMetadata() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
final int totalMetadata = 10;
|
||||
@@ -1885,7 +1896,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a target metadata filtered query with value==knownValue1 parameter returns only the metadata entries with that value.")
|
||||
public void searchDistributionSetMetadataRsql() throws Exception {
|
||||
void searchDistributionSetMetadataRsql() throws Exception {
|
||||
final String knownControllerId = "targetIdWithMetadata";
|
||||
|
||||
final int totalMetadata = 10;
|
||||
@@ -1904,7 +1915,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("A request for assigning multiple DS to a target results in a Bad Request when multiassignment in disabled.")
|
||||
public void multiassignmentRequestNotAllowedIfDisabled() throws Exception {
|
||||
void multiassignmentRequestNotAllowedIfDisabled() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final List<Long> dsIds = testdataFactory.createDistributionSets(2).stream().map(DistributionSet::getId)
|
||||
.collect(Collectors.toList());
|
||||
@@ -1919,7 +1930,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Passing an array in assignment request is allowed if multiassignment is disabled and array size in 1.")
|
||||
public void multiassignmentRequestAllowedIfDisabledButHasSizeOne() throws Exception {
|
||||
void multiassignmentRequestAllowedIfDisabledButHasSizeOne() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
|
||||
@@ -1931,7 +1942,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Identical assignments in a single request are removed when multiassignment in disabled.")
|
||||
public void identicalAssignmentInRequestAreRemovedIfMultiassignmentsDisabled() throws Exception {
|
||||
void identicalAssignmentInRequestAreRemovedIfMultiassignmentsDisabled() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
|
||||
@@ -1945,7 +1956,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Assign multiple DSs to a target in one request with multiassignments enabled.")
|
||||
public void multiAssignment() throws Exception {
|
||||
void multiAssignment() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final List<Long> dsIds = testdataFactory.createDistributionSets(2).stream().map(DistributionSet::getId)
|
||||
.collect(Collectors.toList());
|
||||
@@ -1960,8 +1971,8 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("An assignment request containing a weight is only accepted when weight is valide and multi assignment is on.")
|
||||
public void weightValidation() throws Exception {
|
||||
@Description("An assignment request containing a weight is only accepted when weight is valid and multi assignment is on.")
|
||||
void weightValidation() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
final int weight = 98;
|
||||
@@ -1985,7 +1996,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("An assignment request containing a valid weight when multi assignment is off.")
|
||||
public void weightWithSingleAssignment() throws Exception {
|
||||
void weightWithSingleAssignment() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
|
||||
@@ -1999,7 +2010,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("An assignment request containing a valid weight when multi assignment is on.")
|
||||
public void weightWithMultiAssignment() throws Exception {
|
||||
void weightWithMultiAssignment() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
final int weight = 98;
|
||||
@@ -2018,7 +2029,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Get weight of action")
|
||||
public void getActionWeight() throws Exception {
|
||||
void getActionWeight() throws Exception {
|
||||
final String targetId = testdataFactory.createTarget().getControllerId();
|
||||
final Long dsId = testdataFactory.createDistributionSet().getId();
|
||||
final int customWeightHigh = 800;
|
||||
@@ -2049,7 +2060,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("An action provides information of the rollout it was created for (if any).")
|
||||
public void getActionWithRolloutInfo() throws Exception {
|
||||
void getActionWithRolloutInfo() throws Exception {
|
||||
|
||||
// setup
|
||||
final int amountTargets = 10;
|
||||
@@ -2082,7 +2093,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating targets with target type works.")
|
||||
public void createTargetsWithTargetType() throws Exception {
|
||||
void createTargetsWithTargetType() throws Exception {
|
||||
final TargetType type1 = testdataFactory.createTargetType("typeWithDs", Collections.singletonList(standardDsType));
|
||||
final TargetType type2 = testdataFactory.createTargetType("typeWithOutDs", Collections.singletonList(standardDsType));
|
||||
|
||||
@@ -2132,26 +2143,21 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
.andExpect(jsonPath(JSON_PATH_DESCRIPTION, equalTo("testid2")))
|
||||
.andExpect(jsonPath("$._links.targetType.href", equalTo(hrefType1))).andReturn();
|
||||
|
||||
assertThat(targetManagement.getByControllerID("id1")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getName()).isEqualTo("targetWithoutType");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getDescription()).isEqualTo("testid1");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getTargetType()).isNull();
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getSecurityToken()).isEqualTo("token");
|
||||
assertThat(targetManagement.getByControllerID("id1").get().getAddress().toString())
|
||||
.isEqualTo("amqp://test123/foobar");
|
||||
assertThat(targetManagement.getByControllerID("id2")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id2").get().getName()).isEqualTo("targetOfType1");
|
||||
assertThat(targetManagement.getByControllerID("id2").get().getDescription()).isEqualTo("testid2");
|
||||
assertThat(targetManagement.getByControllerID("id2").get().getTargetType().getName()).isEqualTo("typeWithDs");
|
||||
assertThat(targetManagement.getByControllerID("id3")).isNotNull();
|
||||
assertThat(targetManagement.getByControllerID("id3").get().getName()).isEqualTo("targetOfType2");
|
||||
assertThat(targetManagement.getByControllerID("id3").get().getDescription()).isEqualTo("testid3");
|
||||
assertThat(targetManagement.getByControllerID("id3").get().getTargetType().getName()).isEqualTo("typeWithOutDs");
|
||||
final Target target1 = assertTarget("id1", "targetWithoutType", "testid1");
|
||||
assertThat(target1.getTargetType()).isNull();
|
||||
assertThat(target1.getSecurityToken()).isEqualTo("token");
|
||||
assertThat(target1.getAddress()).hasToString("amqp://test123/foobar");
|
||||
|
||||
final Target target2 = assertTarget("id2", "targetOfType1", "testid2");
|
||||
assertThat(target2.getTargetType()).extracting(TargetType::getName).isEqualTo("typeWithDs");
|
||||
|
||||
final Target target3 = assertTarget("id3", "targetOfType2", "testid3");
|
||||
assertThat(target3.getTargetType()).extracting(TargetType::getName).isEqualTo("typeWithOutDs");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating target with target type works.")
|
||||
public void createTargetWithExistingTargetType() throws Exception {
|
||||
void createTargetWithExistingTargetType() throws Exception {
|
||||
// create target type
|
||||
List<TargetType> targetTypes = testdataFactory.createTargetTypes("targettype",1);
|
||||
assertThat(targetTypes).hasSize(1);
|
||||
@@ -2171,7 +2177,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a put request for updating targets with target type works.")
|
||||
public void updateTargetTypeInTarget() throws Exception {
|
||||
void updateTargetTypeInTarget() throws Exception {
|
||||
// create target type
|
||||
List<TargetType> targetTypes = testdataFactory.createTargetTypes("targettype",2);
|
||||
assertThat(targetTypes).hasSize(2);
|
||||
@@ -2193,7 +2199,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for creating targets with unknown target type fails.")
|
||||
public void addingNonExistingTargetTypeInTargetShouldFail() throws Exception {
|
||||
void addingNonExistingTargetTypeInTargetShouldFail() throws Exception {
|
||||
long unknownTargetTypeId = 999;
|
||||
String errorMsg = String.format("TargetType with given identifier {%s} does not exist.", unknownTargetTypeId);
|
||||
|
||||
@@ -2213,7 +2219,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for assign target type to target works.")
|
||||
public void assignTargetTypeToTarget() throws Exception {
|
||||
void assignTargetTypeToTarget() throws Exception {
|
||||
// create target type
|
||||
TargetType targetType = testdataFactory.findOrCreateTargetType("targettype");
|
||||
assertThat(targetType).isNotNull();
|
||||
@@ -2233,7 +2239,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a post request for assign a invalid target type to target fails.")
|
||||
public void assignInvalidTargetTypeToTargetFails() throws Exception {
|
||||
void assignInvalidTargetTypeToTargetFails() throws Exception {
|
||||
// Invalid target type ID
|
||||
long invalidTargetTypeId = 999;
|
||||
|
||||
@@ -2260,7 +2266,7 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
|
||||
@Test
|
||||
@Description("Ensures that a delete request for unassign target type from target works.")
|
||||
public void unassignTargetTypeFromTarget() throws Exception {
|
||||
void unassignTargetTypeFromTarget() throws Exception {
|
||||
// create target type
|
||||
List<TargetType> targetTypes = testdataFactory.createTargetTypes("targettype",1);
|
||||
assertThat(targetTypes).hasSize(1);
|
||||
@@ -2279,10 +2285,10 @@ public class MgmtTargetResourceTest extends AbstractManagementApiIntegrationTest
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidRequestsOnTargetTypeResource() throws Exception {
|
||||
void invalidRequestsOnTargetTypeResource() throws Exception {
|
||||
final String knownTargetId = "targetId";
|
||||
final Target target = testdataFactory.createTarget(knownTargetId);
|
||||
final TargetType targettype = testdataFactory.createTargetType("targettype", Collections.emptyList());
|
||||
testdataFactory.createTarget(knownTargetId);
|
||||
testdataFactory.createTargetType("targettype", Collections.emptyList());
|
||||
|
||||
// GET is not allowed
|
||||
mvc.perform(get(
|
||||
|
||||
@@ -74,9 +74,9 @@ public class RestConfiguration {
|
||||
* filter in the filter chain
|
||||
*/
|
||||
@Bean
|
||||
FilterRegistrationBean eTagFilter() {
|
||||
FilterRegistrationBean<ExcludePathAwareShallowETagFilter> eTagFilter() {
|
||||
|
||||
final FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
|
||||
final FilterRegistrationBean<ExcludePathAwareShallowETagFilter> filterRegBean = new FilterRegistrationBean<>();
|
||||
// Exclude the URLs for downloading artifacts, so no eTag is generated
|
||||
// in the ShallowEtagHeaderFilter, just using the SH1 hash of the
|
||||
// artifact itself as 'ETag', because otherwise the file will be copied
|
||||
|
||||
@@ -151,7 +151,7 @@ public final class FileStreamingUtil {
|
||||
LOG.debug("range header for filename ({}) is: {}", filename, range);
|
||||
|
||||
// Range header matches"bytes=n-n,n-n,n-n..."
|
||||
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
|
||||
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*+$")) {
|
||||
response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
|
||||
LOG.debug("range header for filename ({}) is not satisfiable: ", filename);
|
||||
return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Copyright (c) 2022 Bosch.IO 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.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.eclipse.hawkbit.artifact.repository.model.DbArtifact;
|
||||
import org.eclipse.hawkbit.artifact.repository.model.DbArtifactHash;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import io.qameta.allure.Feature;
|
||||
import io.qameta.allure.Story;
|
||||
|
||||
@Feature("Component Tests - Management API")
|
||||
@Story("File streaming")
|
||||
class FileStreamingUtilTest {
|
||||
private final static String CONTENT = "This is some very long string which is intended to test";
|
||||
private final static byte[] CONTENT_BYTES = CONTENT.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private static final DbArtifact TEST_ARTIFACT = new DbArtifact() {
|
||||
|
||||
@Override
|
||||
public String getArtifactId() {
|
||||
return "1";
|
||||
}
|
||||
|
||||
@Override
|
||||
public DbArtifactHash getHashes() {
|
||||
return new DbArtifactHash("sha1-111", "md5-123", "sha256-123");
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getSize() {
|
||||
return CONTENT_BYTES.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getContentType() {
|
||||
return "text/plain";
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getFileInputStream() {
|
||||
return new ByteArrayInputStream(CONTENT_BYTES);
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void shouldProcessRangeHeaderForMultipartRequests() throws IOException {
|
||||
final HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
|
||||
final ServletOutputStream outputStream = Mockito.mock(ServletOutputStream.class);
|
||||
|
||||
Mockito.when(servletResponse.getOutputStream()).thenReturn(outputStream);
|
||||
final HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
|
||||
Mockito.when(servletRequest.getHeader("Range")).thenReturn("bytes=0-10,9-15,16-");
|
||||
long lastModified = System.currentTimeMillis();
|
||||
|
||||
final ResponseEntity<InputStream> responseEntity = FileStreamingUtil.writeFileResponse(TEST_ARTIFACT,
|
||||
"test.file", lastModified, servletResponse, servletRequest, null);
|
||||
|
||||
assertThat(responseEntity).isNotNull();
|
||||
verify(servletResponse).setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
|
||||
final ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
|
||||
final ArgumentCaptor<Integer> lenCaptor = ArgumentCaptor.forClass(Integer.class);
|
||||
|
||||
verify(outputStream).print(stringCaptor.capture());
|
||||
assertThat(stringCaptor.getValue()).contains("--THIS_STRING_SEPARATES_MULTIPART--");
|
||||
verify(outputStream, times(3)).write(any(), anyInt(), lenCaptor.capture());
|
||||
assertThat(lenCaptor.getAllValues()).containsExactly(11, 7, 39); // Range lengths
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldValidateRangeHeaderForMultipartRequests() throws IOException {
|
||||
long lastModified = System.currentTimeMillis();
|
||||
final HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
|
||||
final ServletOutputStream outputStream = Mockito.mock(ServletOutputStream.class);
|
||||
Mockito.when(servletResponse.getOutputStream()).thenReturn(outputStream);
|
||||
|
||||
final HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class);
|
||||
Mockito.when(servletRequest.getHeader("Range")).thenReturn("bytes=0-10***,9-15,16-");
|
||||
|
||||
final ResponseEntity<InputStream> responseEntity = FileStreamingUtil.writeFileResponse(TEST_ARTIFACT,
|
||||
"test.file", lastModified, servletResponse, servletRequest, null);
|
||||
|
||||
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||
verify(outputStream, times(0)).print(anyString());
|
||||
verify(outputStream, times(0)).write(any(), anyInt(), anyInt());
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@
|
||||
package org.eclipse.hawkbit.rest.util;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -42,24 +42,21 @@ public class SortUtilityTest {
|
||||
@Description("Ascending sorting based on name.")
|
||||
public void parseSortParam1() {
|
||||
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_1);
|
||||
assertThat(1).as("Count of parsing parameter").isEqualTo(parse.size());
|
||||
assertThat(parse).as("Count of parsing parameter").hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Ascending sorting based on name and descending sorting based on description.")
|
||||
public void parseSortParam2() {
|
||||
final List<Order> parse = SortUtility.parse(TargetFields.class, SORT_PARAM_2);
|
||||
assertThat(2).as("Count of parsing parameter").isEqualTo(parse.size());
|
||||
assertThat(parse).as("Count of parsing parameter").hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Sorting with wrong syntax leads to SortParameterSyntaxErrorException.")
|
||||
public void parseWrongSyntaxParam() {
|
||||
try {
|
||||
SortUtility.parse(TargetFields.class, SYNTAX_FAILURE_SORT_PARAM);
|
||||
fail("SortParameterSyntaxErrorException expected because of wrong syntax");
|
||||
} catch (final SortParameterSyntaxErrorException e) {
|
||||
}
|
||||
assertThrows(SortParameterSyntaxErrorException.class,
|
||||
() -> SortUtility.parse(TargetFields.class, SYNTAX_FAILURE_SORT_PARAM));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -72,22 +69,14 @@ public class SortUtilityTest {
|
||||
@Test
|
||||
@Description("Sorting with unknown direction order leads to SortParameterUnsupportedDirectionException.")
|
||||
public void parseWrongDirectionParam() {
|
||||
try {
|
||||
SortUtility.parse(TargetFields.class, WRONG_DIRECTION_PARAM);
|
||||
fail("SortParameterUnsupportedDirectionException expected because of unknown direction order");
|
||||
} catch (final SortParameterUnsupportedDirectionException e) {
|
||||
}
|
||||
|
||||
assertThrows(SortParameterUnsupportedDirectionException.class,
|
||||
() -> SortUtility.parse(TargetFields.class, WRONG_DIRECTION_PARAM));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Description("Sorting with unknown field leads to SortParameterUnsupportedFieldException.")
|
||||
public void parseWrongFieldParam() {
|
||||
try {
|
||||
SortUtility.parse(TargetFields.class, WRONG_FIELD_PARAM);
|
||||
fail("SortParameterUnsupportedFieldException expected because of unknown field");
|
||||
} catch (final SortParameterUnsupportedFieldException e) {
|
||||
}
|
||||
|
||||
assertThrows(SortParameterUnsupportedFieldException.class,
|
||||
() -> SortUtility.parse(TargetFields.class, WRONG_FIELD_PARAM));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user