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:
Peter Vigier
2022-01-31 21:59:46 +01:00
committed by GitHub
parent 5443b5df9c
commit 44a85f20eb
98 changed files with 2583 additions and 2702 deletions

View File

@@ -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);

View File

@@ -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();
}
}

View File

@@ -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";

View File

@@ -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(