Rename and split rest resources ddi, mgmt and system

Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>
This commit is contained in:
SirWayne
2016-04-20 17:33:03 +02:00
parent 8a22ea3df3
commit c3c405c986
169 changed files with 3081 additions and 1871 deletions

View File

@@ -0,0 +1,466 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditions;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.eclipse.hawkbit.repository.model.Target;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Builder class for building certain json strings.
*
*
*
*/
public abstract class JsonBuilder {
public static String softwareModules(final List<SoftwareModule> modules) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final SoftwareModule module : modules) {
try {
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("type", module.getType().getKey())
.put("id", Long.MAX_VALUE).put("vendor", module.getVendor())
.put("version", module.getVersion()).put("createdAt", "0").put("updatedAt", "0")
.put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh").toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < modules.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String softwareModulesCreatableFieldsOnly(final List<SoftwareModule> modules) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final SoftwareModule module : modules) {
try {
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("type", module.getType().getKey())
.put("vendor", module.getVendor()).put("version", module.getVersion()).toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < modules.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String softwareModuleUpdatableFieldsOnly(final SoftwareModule module) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append(new JSONObject().put("description", module.getDescription()).put("vendor", module.getVendor())
.toString());
return builder.toString();
}
public static String softwareModuleTypes(final List<SoftwareModuleType> types) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final SoftwareModuleType module : types) {
try {
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
.put("key", module.getKey()).put("maxAssignments", module.getMaxAssignments())
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
.put("updatedBy", "fghdfkjghdfkjh").toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < types.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String softwareModuleTypesCreatableFieldsOnly(final List<SoftwareModuleType> types)
throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final SoftwareModuleType module : types) {
try {
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("key", module.getKey())
.put("maxAssignments", module.getMaxAssignments()).toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < types.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
/**
* builds a json string for the feedback for the execution "proceeding".
*
* @param id
* of the Action feedback refers to
* @return the built string
* @throws JSONException
*/
public static String deploymentActionInProgressFeedback(final String id) throws JSONException {
return deploymentActionFeedback(id, "proceeding");
}
/**
* builds a certain json string for a action feedback.
*
* @param id
* of the action the feedback refers to
* @param execution
* see ExecutionStatus
* @return the build json string
* @throws JSONException
*/
public static String deploymentActionFeedback(final String id, final String execution) throws JSONException {
return deploymentActionFeedback(id, execution, "none", RandomStringUtils.randomAscii(1000));
}
public static String deploymentActionFeedback(final String id, final String execution, final String message)
throws JSONException {
return deploymentActionFeedback(id, execution, "none", message);
}
public static String deploymentActionFeedback(final String id, final String execution, final String finished,
final String message) throws JSONException {
final List<String> messages = new ArrayList<String>();
messages.add(message);
return new JSONObject()
.put("id", id)
.put("time", "20140511T121314")
.put("status",
new JSONObject()
.put("execution", execution)
.put("result",
new JSONObject().put("finished", finished).put("progress",
new JSONObject().put("cnt", 2).put("of", 5))).put("details", messages))
.toString();
}
/**
* @param types
* @return
*/
public static String distributionSetTypes(final List<DistributionSetType> types) {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final DistributionSetType module : types) {
try {
final JSONArray osmTypes = new JSONArray();
module.getOptionalModuleTypes().forEach(smt -> osmTypes.put(new JSONObject().put("id", smt.getId())));
final JSONArray msmTypes = new JSONArray();
module.getMandatoryModuleTypes().forEach(smt -> msmTypes.put(new JSONObject().put("id", smt.getId())));
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("id", Long.MAX_VALUE)
.put("key", module.getKey()).put("createdAt", "0").put("updatedAt", "0")
.put("createdBy", "fghdfkjghdfkjh").put("optionalmodules", osmTypes)
.put("mandatorymodules", msmTypes).put("updatedBy", "fghdfkjghdfkjh").toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < types.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String distributionSetTypesCreateValidFieldsOnly(final List<DistributionSetType> types) {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final DistributionSetType module : types) {
try {
final JSONArray osmTypes = new JSONArray();
module.getOptionalModuleTypes().forEach(smt -> osmTypes.put(new JSONObject().put("id", smt.getId())));
final JSONArray msmTypes = new JSONArray();
module.getMandatoryModuleTypes().forEach(smt -> msmTypes.put(new JSONObject().put("id", smt.getId())));
builder.append(new JSONObject().put("name", module.getName())
.put("description", module.getDescription()).put("key", module.getKey())
.put("optionalmodules", osmTypes).put("mandatorymodules", msmTypes).toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < types.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String distributionSets(final List<DistributionSet> sets) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final DistributionSet set : sets) {
try {
builder.append(distributionSet(set));
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < sets.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String distributionSetsCreateValidFieldsOnly(final List<DistributionSet> sets) throws JSONException {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final DistributionSet set : sets) {
try {
builder.append(distributionSetCreateValidFieldsOnly(set));
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < sets.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String distributionSetCreateValidFieldsOnly(final DistributionSet set) throws JSONException {
final List<JSONObject> modules = set.getModules().stream().map(module -> {
try {
return new JSONObject().put("id", module.getId());
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
.put("type", set.getType() == null ? null : set.getType().getKey()).put("version", set.getVersion())
.put("requiredMigrationStep", set.isRequiredMigrationStep()).put("modules", modules).toString();
}
public static String distributionSetUpdateValidFieldsOnly(final DistributionSet set) throws JSONException {
final List<JSONObject> modules = set.getModules().stream().map(module -> {
try {
return new JSONObject().put("id", module.getId());
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
.put("version", set.getVersion()).toString();
}
public static String distributionSet(final DistributionSet set) throws JSONException {
final List<JSONObject> modules = set.getModules().stream().map(module -> {
try {
return new JSONObject().put("id", module.getId());
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
return new JSONObject().put("name", set.getName()).put("description", set.getDescription())
.put("type", set.getType() == null ? null : set.getType().getKey()).put("id", Long.MAX_VALUE)
.put("version", set.getVersion()).put("createdAt", "0").put("updatedAt", "0")
.put("createdBy", "fghdfkjghdfkjh").put("updatedBy", "fghdfkjghdfkjh")
.put("requiredMigrationStep", set.isRequiredMigrationStep()).put("modules", modules).toString();
}
/**
* @param targets
* @return
*/
public static String targets(final List<Target> targets) {
final StringBuilder builder = new StringBuilder();
builder.append("[");
int i = 0;
for (final Target target : targets) {
try {
builder.append(new JSONObject().put("controllerId", target.getControllerId())
.put("description", target.getDescription()).put("name", target.getName())
.put("createdAt", "0").put("updatedAt", "0").put("createdBy", "fghdfkjghdfkjh")
.put("updatedBy", "fghdfkjghdfkjh").toString());
} catch (final Exception e) {
e.printStackTrace();
}
if (++i < targets.size()) {
builder.append(",");
}
}
builder.append("]");
return builder.toString();
}
public static String rollout(final String name, final String description, final int groupSize,
final long distributionSetId, final String targetFilterQuery, final RolloutGroupConditions conditions) {
final JSONObject json = new JSONObject();
json.put("name", name);
json.put("description", description);
json.put("amountGroups", groupSize);
json.put("distributionSetId", distributionSetId);
json.put("targetFilterQuery", targetFilterQuery);
if (conditions != null) {
final JSONObject successCondition = new JSONObject();
json.put("successCondition", successCondition);
successCondition.put("condition", conditions.getSuccessCondition().toString());
successCondition.put("expression", conditions.getSuccessConditionExp().toString());
final JSONObject successAction = new JSONObject();
json.put("successAction", successAction);
successAction.put("action", conditions.getSuccessAction().toString());
successAction.put("expression", conditions.getSuccessActionExp().toString());
final JSONObject errorCondition = new JSONObject();
json.put("errorCondition", errorCondition);
errorCondition.put("condition", conditions.getErrorCondition().toString());
errorCondition.put("expression", conditions.getErrorConditionExp().toString());
final JSONObject errorAction = new JSONObject();
json.put("errorAction", errorAction);
errorAction.put("action", conditions.getErrorAction().toString());
errorAction.put("expression", conditions.getErrorActionExp().toString());
}
return json.toString();
}
public static String cancelActionFeedback(final String id, final String execution) throws JSONException {
return cancelActionFeedback(id, execution, RandomStringUtils.randomAscii(1000));
}
public static String cancelActionFeedback(final String id, final String execution, final String message)
throws JSONException {
final List<String> messages = new ArrayList<String>();
messages.add(message);
return new JSONObject()
.put("id", id)
.put("time", "20140511T121314")
.put("status",
new JSONObject().put("execution", execution)
.put("result", new JSONObject().put("finished", "success")).put("details", messages))
.toString();
}
public static String configData(final String id, final Map<String, String> attributes, final String execution)
throws JSONException {
return new JSONObject()
.put("id", id)
.put("time", "20140511T121314")
.put("status",
new JSONObject().put("execution", execution)
.put("result", new JSONObject().put("finished", "success"))
.put("details", new ArrayList<String>())).put("data", attributes).toString();
}
}

View File

@@ -0,0 +1,920 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.ActionRepository;
import org.eclipse.hawkbit.repository.ControllerManagement;
import org.eclipse.hawkbit.repository.DistributionSetManagement;
import org.eclipse.hawkbit.repository.SoftwareManagement;
import org.eclipse.hawkbit.repository.TargetManagement;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetMetadata;
import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.context.annotation.Description;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API")
@Stories("Distribution Set Resource")
public class MgmtDistributionSetResourceTest extends AbstractIntegrationTest {
@Test
@Description("This test verifies the call of all Software Modules that are assiged to a Distribution Set through the RESTful API.")
public void getSoftwaremodules() throws Exception {
// Create DistributionSet with three software modules
final DistributionSet set = TestDataUtil.generateDistributionSet("SMTest", softwareManagement,
distributionSetManagement);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(set.getModules().size())));
}
@Test
@Description("This test verifies the deletion of a assigned Software Module of a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
public void deleteFailureWhenDistributionSetInUse() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Eris", "560a",
distributionSetManagement);
final List<Long> smIDs = new ArrayList<Long>();
SoftwareModule sm = new SoftwareModule(osType, "Dysnomia ", "15,772", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
final JSONArray smList = new JSONArray();
for (final Long smID : smIDs) {
smList.put(new JSONObject().put("id", Long.valueOf(smID)));
}
// post assignment
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(smList.toString())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// create targets and assign DisSet to target
final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
// try to delete the Software Module from DistSet that has been assigned
// to the target.
mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/"
+ smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isLocked())
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
}
@Test
@Description("This test verifies that the assignment of a Software Module to a Distribution Set can not be achieved when that Distribution Set has been assigned or installed to a target.")
public void assignmentFailureWhenAssigningToUsedDistributionSet() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Mars", "686,980",
distributionSetManagement);
final List<Long> smIDs = new ArrayList<>();
SoftwareModule sm = new SoftwareModule(osType, "Phobos", "0,3189", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
final JSONArray smList = new JSONArray();
for (final Long smID : smIDs) {
smList.put(new JSONObject().put("id", Long.valueOf(smID)));
}
// post assignment
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(smList.toString())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// create Targets
final String[] knownTargetIds = new String[] { "1", "2" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign DisSet to target and test assignment
deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]);
mvc.perform(
post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets")
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
// Create another SM and post assignment
final List<Long> smID2s = new ArrayList<Long>();
SoftwareModule sm2 = new SoftwareModule(appType, "Deimos", "1,262", null, null);
sm2 = softwareManagement.createSoftwareModule(sm2);
smID2s.add(sm2.getId());
final JSONArray smList2 = new JSONArray();
for (final Long smID : smID2s) {
smList2.put(new JSONObject().put("id", Long.valueOf(smID)));
}
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(smList2.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked())
.andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked")));
}
@Test
@Description("This test verifies the assignment of Software Modules to a Distribution Set through the RESTful API.")
public void assignSoftwaremoduleToDistributionSet() throws Exception {
// create DisSet
final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Jupiter", "398,88",
distributionSetManagement);
// Test if size is 0
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(disSet.getModules().size())));
// create Software Modules
final List<Long> smIDs = new ArrayList<Long>();
SoftwareModule sm = new SoftwareModule(osType, "Europa", "3,551", null, null);
sm = softwareManagement.createSoftwareModule(sm);
smIDs.add(sm.getId());
SoftwareModule sm2 = new SoftwareModule(appType, "Ganymed", "7,155", null, null);
sm2 = softwareManagement.createSoftwareModule(sm2);
smIDs.add(sm2.getId());
SoftwareModule sm3 = new SoftwareModule(runtimeType, "Kallisto", "16,689", null, null);
sm3 = softwareManagement.createSoftwareModule(sm3);
smIDs.add(sm3.getId());
final JSONArray list = new JSONArray();
for (final Long smID : smIDs) {
list.put(new JSONObject().put("id", Long.valueOf(smID)));
}
// post assignment
mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")
.contentType(MediaType.APPLICATION_JSON).content(list.toString())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// Test if size is 3
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(smIDs.size())));
}
@Test
@Description("This test verifies the removal of Software Modules of a Distribution Set through the RESTful API.")
public void unassignSoftwaremoduleFromDistributionSet() throws Exception {
// Create DistributionSet with three software modules
final DistributionSet set = TestDataUtil.generateDistributionSet("Venus", softwareManagement,
distributionSetManagement);
int amountOfSM = set.getModules().size();
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(amountOfSM)));
// test the removal of all software modules one by one
for (final Iterator<SoftwareModule> iter = set.getModules().iterator(); iter.hasNext();) {
final Long smId = iter.next().getId();
mvc.perform(delete(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId))
.andExpect(status().isOk());
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$.size", equalTo(--amountOfSM)));
}
}
@Test
@Description("Ensures that multi target assignment through API is reflected by the repository.")
public void assignMultipleTargetsToDistributionSet() throws Exception {
// prepare distribution set
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
// prepare targets
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign already one target to DS
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
mvc.perform(post(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")
.contentType(MediaType.APPLICATION_JSON).content(list.toString()))
.andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1)))
.andExpect(jsonPath("$.alreadyAssigned", equalTo(1)))
.andExpect(jsonPath("$.total", equalTo(knownTargetIds.length)));
assertThat(targetManagement.findTargetByAssignedDistributionSet(createdDs.getId(), pageReq).getContent())
.as("Five targets in repository have DS assigned").hasSize(5);
}
@Test
@Description("Ensures that assigned targets of DS are returned as reflected by the repository.")
public void getAssignedTargetsOfDistributionSet() throws Exception {
// prepare distribution set
final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
targetManagement.createTarget(new Target(knownTargetId));
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
}
@Test
@Description("Ensures that assigned targets of DS are returned as persisted in the repository.")
public void getAssignedTargetsOfDistributionSetIsEmpty() throws Exception {
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets"))
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0)))
.andExpect(jsonPath("$.total", equalTo(0)));
}
@Test
@Description("Ensures that installed targets of DS are returned as persisted in the repository.")
public void getInstalledTargetsOfDistributionSet() throws Exception {
// prepare distribution set
final String knownTargetId = "knownTargetId1";
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
final Target createTarget = targetManagement.createTarget(new Target(knownTargetId));
// create some dummy targets which are not assigned or installed
targetManagement.createTarget(new Target("dummy1"));
targetManagement.createTarget(new Target("dummy2"));
// assign knownTargetId to distribution set
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId);
// make it in install state
sendUpdateActionStatusToTargets(controllerManagament, targetManagement, actionRepository, createdDs,
Lists.newArrayList(createTarget), Status.FINISHED, "some message");
mvc.perform(get(
MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets"))
.andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1)))
.andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId)));
}
@Test
@Description("Ensures that DS in repository are listed with proper paging properties.")
public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception {
final int sets = 5;
createDistributionSetsAlphabetical(sets);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(sets)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(sets)));
}
@Test
@Description("Ensures that DS in repository are listed with proper paging results with paging limit parameter.")
public void getDistributionSetsWithPagingLimitRequestParameter() throws Exception {
final int sets = 5;
final int limitSize = 1;
createDistributionSetsAlphabetical(sets);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_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(sets)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Ensures that DS in repository are listed with proper paging results with paging limit and offset parameter.")
public void getDistributionSetsWithPagingLimitAndOffsetRequestParameter() throws Exception {
final int sets = 5;
final int offsetParam = 2;
final int expectedSize = sets - offsetParam;
createDistributionSetsAlphabetical(sets);
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(sets)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multiple DS requested are listed with expected payload.")
public void getDistributionSets() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
set.setRequiredMigrationStep(set.isRequiredMigrationStep());
set = distributionSetManagement.updateDistributionSet(set);
set.setVersion("anotherVersion");
set = distributionSetManagement.updateDistributionSet(set);
// load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
// perform request
mvc.perform(get("/rest/v1/distributionsets").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[0]._links.self.href",
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
.andExpect(jsonPath("$content.[0].id", equalTo(set.getId().intValue())))
.andExpect(jsonPath("$content.[0].name", equalTo(set.getName())))
.andExpect(jsonPath("$content.[0].requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
.andExpect(jsonPath("$content.[0].description", equalTo(set.getDescription())))
.andExpect(jsonPath("$content.[0].type", equalTo(set.getType().getKey())))
.andExpect(jsonPath("$content.[0].createdBy", equalTo(set.getCreatedBy())))
.andExpect(jsonPath("$content.[0].createdAt", equalTo(set.getCreatedAt())))
.andExpect(jsonPath("$content.[0].complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo(set.getLastModifiedBy())))
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$content.[0].version", equalTo(set.getVersion())))
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + appType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("$content.[0].modules.[?(@.type==" + osType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(osType).getId().intValue())));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that single DS requested by ID is listed with expected payload.")
public void getDistributionSet() throws Exception {
final DistributionSet set = createTestDistributionSet(softwareManagement, distributionSetManagement);
// perform request
mvc.perform(get("/rest/v1/distributionsets/{dsId}", set.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$_links.self.href",
equalTo("http://localhost/rest/v1/distributionsets/" + set.getId())))
.andExpect(jsonPath("$id", equalTo(set.getId().intValue())))
.andExpect(jsonPath("$name", equalTo(set.getName())))
.andExpect(jsonPath("$type", equalTo(set.getType().getKey())))
.andExpect(jsonPath("$description", equalTo(set.getDescription())))
.andExpect(jsonPath("$requiredMigrationStep", equalTo(set.isRequiredMigrationStep())))
.andExpect(jsonPath("$createdBy", equalTo(set.getCreatedBy())))
.andExpect(jsonPath("$complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("$createdAt", equalTo(set.getCreatedAt())))
.andExpect(jsonPath("$lastModifiedBy", equalTo(set.getLastModifiedBy())))
.andExpect(jsonPath("$lastModifiedAt", equalTo(set.getLastModifiedAt())))
.andExpect(jsonPath("$version", equalTo(set.getVersion())))
.andExpect(jsonPath("$modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("$modules.[?(@.type==" + appType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("$modules.[?(@.type==" + osType.getKey() + ")][0].id",
equalTo(set.findFirstModuleByType(osType).getId().intValue())));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Ensures that multipe DS posted to API are created in the repository.")
public void createDistributionSets() throws JSONException, Exception {
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
final SoftwareModule ah = softwareManagement
.createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, ""));
final SoftwareModule jvm = softwareManagement
.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", null, ""));
final SoftwareModule os = softwareManagement
.createSoftwareModule(new SoftwareModule(osType, "poky", "3.0.2", null, ""));
DistributionSet one = TestDataUtil.buildDistributionSet("one", "one", standardDsType, os, jvm, ah);
DistributionSet two = TestDataUtil.buildDistributionSet("two", "two", standardDsType, os, jvm, ah);
DistributionSet three = TestDataUtil.buildDistributionSet("three", "three", standardDsType, os, jvm, ah);
three.setRequiredMigrationStep(true);
final List<DistributionSet> sets = new ArrayList<>();
sets.add(one);
sets.add(two);
sets.add(three);
final long current = System.currentTimeMillis();
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/distributionsets/").content(JsonBuilder.distributionSets(sets))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0]name", equalTo(one.getName())))
.andExpect(jsonPath("[0]description", equalTo(one.getDescription())))
.andExpect(jsonPath("[0]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[0]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[0]version", equalTo(one.getVersion())))
.andExpect(jsonPath("[0]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[0]requiredMigrationStep", equalTo(one.isRequiredMigrationStep())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
equalTo(one.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + appType.getKey() + ")][0].id",
equalTo(one.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[0].modules.[?(@.type==" + osType.getKey() + ")][0].id",
equalTo(one.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[1]name", equalTo(two.getName())))
.andExpect(jsonPath("[1]description", equalTo(two.getDescription())))
.andExpect(jsonPath("[1]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[1]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[1]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1]version", equalTo(two.getVersion())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
equalTo(two.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + appType.getKey() + ")][0].id",
equalTo(two.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[1].modules.[?(@.type==" + osType.getKey() + ")][0].id",
equalTo(two.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[1]requiredMigrationStep", equalTo(two.isRequiredMigrationStep())))
.andExpect(jsonPath("[2]name", equalTo(three.getName())))
.andExpect(jsonPath("[2]description", equalTo(three.getDescription())))
.andExpect(jsonPath("[2]complete", equalTo(Boolean.TRUE)))
.andExpect(jsonPath("[2]type", equalTo(standardDsType.getKey())))
.andExpect(jsonPath("[2]createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2]version", equalTo(three.getVersion())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + runtimeType.getKey() + ")][0].id",
equalTo(three.findFirstModuleByType(runtimeType).getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + appType.getKey() + ")][0].id",
equalTo(three.findFirstModuleByType(appType).getId().intValue())))
.andExpect(jsonPath("[2].modules.[?(@.type==" + osType.getKey() + ")][0].id",
equalTo(three.findFirstModuleByType(osType).getId().intValue())))
.andExpect(jsonPath("[2]requiredMigrationStep", equalTo(three.isRequiredMigrationStep()))).andReturn();
one = distributionSetManagement.findDistributionSetByIdWithDetails(
distributionSetManagement.findDistributionSetByNameAndVersion("one", "one").getId());
two = distributionSetManagement.findDistributionSetByIdWithDetails(
distributionSetManagement.findDistributionSetByNameAndVersion("two", "two").getId());
three = distributionSetManagement.findDistributionSetByIdWithDetails(
distributionSetManagement.findDistributionSetByNameAndVersion("three", "three").getId());
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsets/" + one.getId());
assertThat(
JsonPath.compile("[0]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + one.getType().getId());
assertThat(JsonPath.compile("[0]id").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo(String.valueOf(one.getId()));
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsets/" + two.getId());
assertThat(
JsonPath.compile("[1]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + two.getType().getId());
assertThat(JsonPath.compile("[1]id").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo(String.valueOf(two.getId()));
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsets/" + three.getId());
assertThat(
JsonPath.compile("[2]_links.type.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + three.getType().getId());
assertThat(JsonPath.compile("[2]id").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo(String.valueOf(three.getId()));
// check in database
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(3);
assertThat(one.isRequiredMigrationStep()).isEqualTo(false);
assertThat(two.isRequiredMigrationStep()).isEqualTo(false);
assertThat(three.isRequiredMigrationStep()).isEqualTo(true);
assertThat(one.getCreatedAt()).isGreaterThanOrEqualTo(current);
assertThat(two.getCreatedAt()).isGreaterThanOrEqualTo(current);
assertThat(three.getCreatedAt()).isGreaterThanOrEqualTo(current);
}
@Test
@Description("Ensures that DS deletion request to API is reflected by the repository.")
public void deleteUnassignedistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).isEmpty();
assertThat(distributionSetRepository.findAll()).isEmpty();
}
@Test
@Description("Ensures that assigned DS deletion request to API is reflected by the repository by means of deleted flag set.")
public void deleteAssignedDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
targetManagement.createTarget(new Target("test"));
deploymentManagement.assignDistributionSet(set.getId(), "test");
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
// perform request
mvc.perform(delete("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check repository content
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, true, true)).hasSize(1);
}
@Test
@Description("Ensures that DS property update request to API is reflected by the repository.")
public void updateDistributionSet() throws Exception {
// prepare test data
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(0);
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
final DistributionSet update = new DistributionSet();
update.setVersion("anotherVersion");
update.setName(null);
update.setType(standardDsType);
mvc.perform(put("/rest/v1/distributionsets/{dsId}", set.getId()).content(JsonBuilder.distributionSet(update))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0)
.getVersion()).isEqualTo("anotherVersion");
assertThat(
distributionSetManagement.findDistributionSetsAll(pageReq, false, true).getContent().get(0).getName())
.isEqualTo(set.getName());
}
@Test
@Description("Ensures that the server reacts properly to invalid requests (URI, Media Type, Methods) with correct reponses.")
public void invalidRequestsOnDistributionSetsResource() throws Exception {
final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final List<DistributionSet> sets = new ArrayList<>();
sets.add(set);
// SM does not exist
mvc.perform(get("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
mvc.perform(delete("/rest/v1/distributionsets/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
// bad request - no content
mvc.perform(post("/rest/v1/distributionsets").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
// bad request - bad content
mvc.perform(post("/rest/v1/distributionsets").content("sdfjsdlkjfskdjf".getBytes())
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/distributionsets").content(JsonBuilder.distributionSets(sets))
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
// not allowed methods
mvc.perform(post("/rest/v1/distributionsets/{smId}", set.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(put("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/rest/v1/distributionsets")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
}
@Test
@Description("Ensures that the metadata creation through API is reflected by the repository.")
public void createMetadata() throws Exception {
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
final String knownKey1 = "knownKey1";
final String knownKey2 = "knownKey2";
final String knownValue1 = "knownValue1";
final String knownValue2 = "knownValue2";
final JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject().put("key", knownKey1).put("value", knownValue1));
jsonArray.put(new JSONObject().put("key", knownKey2).put("value", knownValue2));
mvc.perform(post("/rest/v1/distributionsets/{dsId}/metadata", testDS.getId())
.contentType(MediaType.APPLICATION_JSON).content(jsonArray.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0]key", equalTo(knownKey1))).andExpect(jsonPath("[0]value", equalTo(knownValue1)))
.andExpect(jsonPath("[1]key", equalTo(knownKey2)))
.andExpect(jsonPath("[1]value", equalTo(knownValue2)));
final DistributionSetMetadata metaKey1 = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey1));
final DistributionSetMetadata metaKey2 = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey2));
assertThat(metaKey1.getValue()).isEqualTo(knownValue1);
assertThat(metaKey2.getValue()).isEqualTo(knownValue2);
}
@Test
@Description("Ensures that a metadata update through API is reflected by the repository.")
public void updateMetadata() throws Exception {
// prepare and create metadata for update
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final String updateValue = "valueForUpdate";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
final JSONObject jsonObject = new JSONObject().put("key", knownKey).put("value", updateValue);
mvc.perform(put("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey)
.contentType(MediaType.APPLICATION_JSON).content(jsonObject.toString()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue)));
final DistributionSetMetadata assertDS = distributionSetManagement
.findOne(new DsMetadataCompositeKey(testDS, knownKey));
assertThat(assertDS.getValue()).isEqualTo(updateValue);
}
@Test
@Description("Ensures that a metadata entry deletion through API is reflected by the repository.")
public void deleteMetadata() throws Exception {
// prepare and create metadata for deletion
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
mvc.perform(delete("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
try {
distributionSetManagement.findOne(new DsMetadataCompositeKey(testDS, knownKey));
fail("expected EntityNotFoundException but didn't throw");
} catch (final EntityNotFoundException e) {
// ok as expected
}
}
@Test
@Description("Ensures that a metadata entry selection through API reflectes the repository content.")
public void getSingleMetadata() throws Exception {
// prepare and create metadata
final String knownKey = "knownKey";
final String knownValue = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
distributionSetManagement
.createDistributionSetMetadata(new DistributionSetMetadata(knownKey, testDS, knownValue));
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata/{key}", testDS.getId(), knownKey))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(knownValue)));
}
@Test
@Description("Ensures that a metadata entry paged list selection through API reflectes the repository content.")
public void getPagedListofMetadata() throws Exception {
final int totalMetadata = 10;
final int limitParam = 5;
final String offsetParam = "0";
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
}
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?offset=" + offsetParam + "&limit=" + limitParam,
testDS.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("size", equalTo(limitParam))).andExpect(jsonPath("total", equalTo(totalMetadata)))
.andExpect(jsonPath("content[0].key", equalTo("knownKey0")))
.andExpect(jsonPath("content[0].value", equalTo("knownValue0")));
}
@Test
@Description("Ensures that a DS search with query parameters returns the expected result.")
public void searchDistributionSetRsql() throws Exception {
final String dsSuffix = "test";
final int amount = 10;
TestDataUtil.generateDistributionSets(dsSuffix, amount, softwareManagement, distributionSetManagement);
TestDataUtil.generateDistributionSet("DS1test", softwareManagement, distributionSetManagement);
TestDataUtil.generateDistributionSet("DS2test", softwareManagement, distributionSetManagement);
final String rsqlFindLikeDs1OrDs2 = "name==DS1test,name==DS2test";
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("DS1test")))
.andExpect(jsonPath("content[1].name", equalTo("DS2test")));
}
@Test
@Description("Ensures that a DS search with complete==true parameter returns only DS that are actually completely filled with mandatory modules.")
public void filterDistributionSetComplete() throws Exception {
final int amount = 10;
TestDataUtil.generateDistributionSets(amount, softwareManagement, distributionSetManagement);
distributionSetManagement.createDistributionSet(new DistributionSet("incomplete", "2", "incomplete",
distributionSetManagement.findDistributionSetTypeByKey("ecl_os"), null));
final String rsqlFindLikeDs1OrDs2 = "complete==" + Boolean.TRUE;
mvc.perform(get("/rest/v1/distributionsets?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(10)))
.andExpect(jsonPath("total", equalTo(10)));
}
@Test
@Description("Ensures that a DS assigned target search with controllerId==1 parameter returns only the target with the given ID.")
public void searchDistributionSetAssignedTargetsRsql() throws Exception {
// prepare distribution set
final Set<DistributionSet> createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1);
final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next();
// prepare targets
final String[] knownTargetIds = new String[] { "1", "2", "3", "4", "5" };
final JSONArray list = new JSONArray();
for (final String targetId : knownTargetIds) {
targetManagement.createTarget(new Target(targetId));
list.put(new JSONObject().put("id", Long.valueOf(targetId)));
}
// assign already one target to DS
deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]);
final String rsqlFindTargetId1 = "controllerId==1";
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId()
+ "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON)
.content(list.toString()))
.andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1)))
.andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1")));
}
@Test
@Description("Ensures that a DS metadata filtered query with value==knownValue1 parameter returns only the metadata entries with that value.")
public void searchDistributionSetMetadataRsql() throws Exception {
final int totalMetadata = 10;
final String knownKeyPrefix = "knownKey";
final String knownValuePrefix = "knownValue";
final DistributionSet testDS = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
for (int index = 0; index < totalMetadata; index++) {
distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata(knownKeyPrefix + index,
distributionSetManagement.findDistributionSetById(testDS.getId()), knownValuePrefix + index));
}
final String rsqlSearchValue1 = "value==knownValue1";
mvc.perform(get("/rest/v1/distributionsets/{dsId}/metadata?q=" + rsqlSearchValue1, testDS.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(1)))
.andExpect(jsonPath("total", equalTo(1))).andExpect(jsonPath("content[0].key", equalTo("knownKey1")))
.andExpect(jsonPath("content[0].value", equalTo("knownValue1")));
}
private Set<DistributionSet> createDistributionSetsAlphabetical(final int amount) {
char character = 'a';
final Set<DistributionSet> created = new HashSet<>();
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
created.add(TestDataUtil.generateDistributionSet(str, softwareManagement, distributionSetManagement));
character++;
}
return created;
}
public static List<Target> sendUpdateActionStatusToTargets(final ControllerManagement controllerManagament,
final TargetManagement targetManagement, final ActionRepository actionRepository, final DistributionSet dsA,
final Iterable<Target> targs, final Status status, final String... msgs) {
final List<Target> result = new ArrayList<Target>();
for (final Target t : targs) {
final List<Action> findByTarget = actionRepository.findByTarget(t);
for (final Action action : findByTarget) {
result.add(sendUpdateActionStatusToTarget(controllerManagament, targetManagement, status, action, t,
msgs));
}
}
return result;
}
private static Target sendUpdateActionStatusToTarget(final ControllerManagement controllerManagament,
final TargetManagement targetManagement, final Status status, final Action updActA, final Target t,
final String... msgs) {
updActA.setStatus(status);
final ActionStatus statusMessages = new ActionStatus();
statusMessages.setAction(updActA);
statusMessages.setOccurredAt(System.currentTimeMillis());
statusMessages.setStatus(status);
for (final String msg : msgs) {
statusMessages.addMessage(msg);
}
controllerManagament.addUpdateActionStatus(statusMessages, updActA);
return targetManagement.findTargetByControllerID(t.getControllerId());
}
public static DistributionSet createTestDistributionSet(final SoftwareManagement softwareManagement,
final DistributionSetManagement distributionSetManagement) {
DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement,
distributionSetManagement);
set.setVersion("anotherVersion");
set = distributionSetManagement.updateDistributionSet(set);
set.getModules().forEach(module -> {
module.setDescription("updated description");
softwareManagement.updateSoftwareModule(module);
});
// load also lazy stuff
set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId());
assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1);
return set;
}
}

View File

@@ -0,0 +1,585 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.google.common.collect.Lists;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Test for {@link MgmtDistributionSetTypeResource}.
*
*/
@Features("Component Tests - Management API")
@Stories("Distribution Set Type Resource")
public class MgmtDistributionSetTypeResourceTest extends AbstractIntegrationTest {
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests.")
public void getDistributionSetTypes() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].name",
equalTo(standardDsType.getName())))
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].description",
equalTo(standardDsType.getDescription())))
.andExpect(jsonPath("$content.[?(@.key==" + standardDsType.getKey() + ")][0].key",
equalTo(standardDsType.getKey())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.self.href",
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.mandatorymodules.href",
equalTo("http://localhost/rest/v1/distributionsettypes/" + testType.getId()
+ "/mandatorymoduletypes")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0]._links.optionalmodules.href", equalTo(
"http://localhost/rest/v1/distributionsettypes/" + testType.getId() + "/optionalmoduletypes")))
.andExpect(jsonPath("$total", equalTo(4)));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with sorting by KEY.")
public void getDistributionSetTypesSortedByKey() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("zzzzz", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
// descending
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:DESC")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[0].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[0].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[0].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
// ascending
mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON)
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:ASC")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[3].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[3].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[3].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[3].key", equalTo("zzzzz"))).andExpect(jsonPath("$total", equalTo(4)));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes POST requests.")
public void createDistributionSetTypes() throws JSONException, Exception {
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
final List<DistributionSetType> types = new ArrayList<>();
types.add(new DistributionSetType("test1", "TestName1", "Desc1").addMandatoryModuleType(osType)
.addOptionalModuleType(runtimeType));
types.add(new DistributionSetType("test2", "TestName2", "Desc2").addOptionalModuleType(osType)
.addOptionalModuleType(runtimeType).addOptionalModuleType(appType));
types.add(new DistributionSetType("test3", "TestName3", "Desc3").addMandatoryModuleType(osType)
.addMandatoryModuleType(runtimeType));
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/distributionsettypes/").content(JsonBuilder.distributionSetTypes(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn();
final DistributionSetType created1 = distributionSetManagement.findDistributionSetTypeByKey("test1");
final DistributionSetType created2 = distributionSetManagement.findDistributionSetTypeByKey("test2");
final DistributionSetType created3 = distributionSetManagement.findDistributionSetTypeByKey("test3");
assertThat(created1.getMandatoryModuleTypes()).containsOnly(osType);
assertThat(created1.getOptionalModuleTypes()).containsOnly(runtimeType);
assertThat(created2.getOptionalModuleTypes()).containsOnly(osType, runtimeType, appType);
assertThat(created3.getMandatoryModuleTypes()).containsOnly(osType, runtimeType);
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created1.getId());
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created2.getId());
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/distributionsettypes/" + created3.getId());
assertThat(JsonPath.compile("[0]_links.mandatorymodules.href")
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/mandatorymoduletypes");
assertThat(JsonPath.compile("[1]_links.mandatorymodules.href")
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/mandatorymoduletypes");
assertThat(JsonPath.compile("[2]_links.mandatorymodules.href")
.read(mvcResult.getResponse().getContentAsString()).toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/mandatorymoduletypes");
assertThat(JsonPath.compile("[0]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
.toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created1.getId() + "/optionalmoduletypes");
assertThat(JsonPath.compile("[1]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
.toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created2.getId() + "/optionalmoduletypes");
assertThat(JsonPath.compile("[2]_links.optionalmodules.href").read(mvcResult.getResponse().getContentAsString())
.toString()).isEqualTo(
"http://localhost/rest/v1/distributionsettypes/" + created3.getId() + "/optionalmoduletypes");
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(6);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes POST requests.")
public void addMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
assertThat(testType.getOptionalModuleTypes()).isEmpty();
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes POST requests.")
public void addOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
mvc.perform(post("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
.content("{\"id\":" + osType.getId() + "}").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(osType);
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes GET requests.")
public void getMandatoryModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes", testType.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0].name", equalTo(osType.getName())))
.andExpect(jsonPath("[0].description", equalTo(osType.getDescription())))
.andExpect(jsonPath("[0].maxAssignments", equalTo(1))).andExpect(jsonPath("[0].key", equalTo("os")));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes GET requests.")
public void getOptionalModulesOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes", testType.getId())
.accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0].name", equalTo(appType.getName())))
.andExpect(jsonPath("[0].description", equalTo(appType.getDescription())))
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("[0].key", equalTo("application")));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} GET requests.")
public void getMandatoryModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(osType.getId().intValue())))
.andExpect(jsonPath("$name", equalTo(osType.getName())))
.andExpect(jsonPath("$description", equalTo(osType.getDescription())))
.andExpect(jsonPath("$createdBy", equalTo(osType.getCreatedBy())))
.andExpect(jsonPath("$createdAt", equalTo(osType.getCreatedAt())))
.andExpect(jsonPath("$lastModifiedBy", equalTo(osType.getLastModifiedBy())))
.andExpect(jsonPath("$lastModifiedAt", equalTo(osType.getLastModifiedAt())));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} GET requests.")
public void getOptionalModuleOfDistributionSetType() throws JSONException, Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("$id", equalTo(appType.getId().intValue())))
.andExpect(jsonPath("$name", equalTo(appType.getName())))
.andExpect(jsonPath("$description", equalTo(appType.getDescription())))
.andExpect(jsonPath("$createdBy", equalTo(appType.getCreatedBy())))
.andExpect(jsonPath("$createdAt", equalTo(appType.getCreatedAt())))
.andExpect(jsonPath("$lastModifiedBy", equalTo(appType.getLastModifiedBy())))
.andExpect(jsonPath("$lastModifiedAt", equalTo(appType.getLastModifiedAt())));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/mandatorymoduletypes/{ID} DELETE requests.")
public void removeMandatoryModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/mandatorymoduletypes/{smtId}", testType.getId(),
osType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).isEmpty();
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID}/optionalmoduletypes/{ID} DELETE requests.")
public void removeOptionalModuleToDistributionSetType() throws JSONException, Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123")
.addMandatoryModuleType(osType).addOptionalModuleType(appType));
assertThat(testType.getOptLockRevision()).isEqualTo(1);
assertThat(testType.getOptionalModuleTypes()).containsExactly(appType);
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
mvc.perform(delete("/rest/v1/distributionsettypes/{dstID}/optionalmoduletypes/{smtId}", testType.getId(),
appType.getId()).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
testType = distributionSetManagement.findDistributionSetTypeById(testType.getId());
assertThat(testType.getLastModifiedBy()).isEqualTo("uploadTester");
assertThat(testType.getOptLockRevision()).isEqualTo(2);
assertThat(testType.getOptionalModuleTypes()).isEmpty();
assertThat(testType.getMandatoryModuleTypes()).containsExactly(osType);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} GET requests.")
public void getDistributionSetType() throws Exception {
DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
testType.setDescription("Desc1234");
testType = distributionSetManagement.updateDistributionSetType(testType);
mvc.perform(get("/rest/v1/distributionsettypes/{dstId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$name", equalTo("TestName123")))
.andExpect(jsonPath("$description", equalTo("Desc1234")))
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (hard delete scenario).")
public void deleteDistributionSetTypeUnused() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
mvc.perform(delete("/rest/v1/distributionsettypes/{dsId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/DistributionSetTypes/{ID} DELETE requests (soft delete scenario).")
public void deleteDistributionSetTypeUsed() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
distributionSetManagement
.createDistributionSet(new DistributionSet("sdfsd", "dsfsdf", "sdfsdf", testType, null));
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(4);
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
mvc.perform(delete("/rest/v1/distributionsettypes/{smId}", testType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
assertThat(distributionSetTypeRepository.count()).isEqualTo(4);
assertThat(distributionSetManagement.countDistributionSetTypesAll()).isEqualTo(3);
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes/{ID} PUT requests.")
public void updateDistributionSetTypeOnlyDescriptionAndNameUntouched() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString();
mvc.perform(put("/rest/v1/distributionsettypes/{smId}", testType.getId()).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$description", equalTo("foobardesc")))
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithoutAddtionalRequestParameters() throws Exception {
final int types = 3;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithPagingLimitRequestParameter() throws Exception {
final int types = 3;
final int limitSize = 1;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_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(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.")
public void getDistributionSetTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
final int types = 3;
final int offsetParam = 2;
final int expectedSize = types - offsetParam;
mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnDistributionSetTypesResource() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final SoftwareModuleType testSmType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final List<DistributionSetType> types = new ArrayList<>();
types.add(testType);
// DST does not exist
mvc.perform(get("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
mvc.perform(get("/rest/v1/distributionsettypes/12345678/mandatorymoduletypes"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(get("/rest/v1/distributionsettypes/12345678/optionalmoduletypes"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(delete("/rest/v1/distributionsettypes/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
// Module types incorrect
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/565765656"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/565765656"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(get(
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/" + osType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes/"
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(get(
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
mvc.perform(get(
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + appType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
mvc.perform(get("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/"
+ testSmType.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
// Modules types at creation time invalid
final DistributionSetType testNewType = new DistributionSetType("test123", "TestName123", "Desc123");
testNewType.addMandatoryModuleType(new SoftwareModuleType("foo", "bar", "test", Integer.MAX_VALUE));
mvc.perform(post("/rest/v1/distributionsettypes")
.content(JsonBuilder.distributionSetTypes(Lists.newArrayList(testNewType)))
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
// bad request - no content
mvc.perform(post("/rest/v1/distributionsettypes").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
// bad request - bad content
mvc.perform(post("/rest/v1/distributionsettypes").content("sdfjsdlkjfskdjf".getBytes())
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// not allowed methods
mvc.perform(put("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/rest/v1/distributionsettypes")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(put("/rest/v1/distributionsettypes/" + standardDsType.getId() + "/mandatorymoduletypes"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
mvc.perform(put(
"/rest/v1/distributionsettypes/" + standardDsType.getId() + "/optionalmoduletypes/" + osType.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed());
}
@Test
@Description("Search erquest of software module types.")
public void searchDistributionSetTypeRsql() throws Exception {
final DistributionSetType testType = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test123", "TestName123", "Desc123"));
final DistributionSetType testType2 = distributionSetManagement
.createDistributionSetType(new DistributionSetType("test1234", "TestName1234", "Desc123"));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
mvc.perform(get("/rest/v1/distributionsettypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
}
private void createSoftwareModulesAlphabetical(final int amount) {
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
softwareManagement.createSoftwareModule(softwareModule);
character++;
}
}
}

View File

@@ -0,0 +1,83 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.cache.CacheConstants;
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
import org.eclipse.hawkbit.cache.DownloadType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.Artifact;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.context.annotation.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
@Features("Component Tests - Management API")
@Stories("Download Resource")
public class MgmtDownloadResourceTest extends AbstractIntegrationTestWithMongoDB {
@Autowired
@Qualifier(CacheConstants.DOWNLOAD_ID_CACHE)
private Cache downloadIdCache;
private final String downloadIdSha1 = "downloadIdSha1";
private final String downloadIdNotAvailable = "downloadIdNotAvailable";
@Before
public void setupCache() {
final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("Test", softwareManagement,
distributionSetManagement);
final SoftwareModule softwareModule = distributionSet.getModules().stream().findFirst().get();
final Artifact artifact = TestDataUtil.generateArtifacts(artifactManagement, softwareModule.getId()).stream()
.findFirst().get();
downloadIdCache.put(downloadIdSha1, new DownloadArtifactCache(DownloadType.BY_SHA1, artifact.getSha1Hash()));
}
@Test
@Description("This test verifies the call of download artifact without a valid download id fails.")
public void testNoDownloadIdAvailable() throws Exception {
mvc.perform(
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
downloadIdNotAvailable))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
}
@Test
@Description("This test verifies the call of download artifact works and the download id will be removed.")
public void testDownload() throws Exception {
mvc.perform(
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
downloadIdSha1))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk());
// because cache is empty
mvc.perform(
get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING,
downloadIdSha1))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound());
}
}

View File

@@ -0,0 +1,597 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import java.util.concurrent.Callable;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.TestDataUtil;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.mgmt.rest.resource.MgmtRolloutResource;
import org.eclipse.hawkbit.repository.RolloutGroupManagement;
import org.eclipse.hawkbit.repository.RolloutManagement;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Rollout;
import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus;
import org.eclipse.hawkbit.repository.model.RolloutGroup;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditionBuilder;
import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition;
import org.eclipse.hawkbit.repository.model.Target;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Tests for covering the {@link MgmtRolloutResource}.
*/
@Features("Component Tests - Management API")
@Stories("Rollout Resource")
public class MgmtRolloutResourceTest extends AbstractIntegrationTest {
@Autowired
private RolloutManagement rolloutManagement;
@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())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rest.body.notReadable")));
}
@Test
@Description("Testing that creating rollout with insufficient permission returns forbidden")
@WithUser(allSpPermissions = true, removeFromAllPermission = "ROLLOUT_MANAGEMENT")
public void createRolloutWithInsufficientPermissionReturnsForbidden() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
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 {
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();
}
@Test
@Description("Testing that creating rollout with not valid formed target filter query returns bad request")
public void createRolloutWithNotWellFormedFilterReturnsBadRequest() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
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();
}
@Description("Ensures that the repository refuses to create rollout without a defined target filter set.")
public void missingTargetFilterQueryInRollout() throws Exception {
final String targetFilterQuery = null;
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout("rollout1", "desc", 10, dsA.getId(), targetFilterQuery, 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("Testing that rollout can be created")
public void createRollout() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
postRollout("rollout1", 10, dsA.getId(), "name==target1");
}
@Test
@Description("Testing the empty list is returned if no rollout exists")
public void noRolloutReturnsEmptyList() throws Exception {
mvc.perform(get("/rest/v1/rollouts")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(0))).andExpect(jsonPath("$total", equalTo(0)));
}
@Test
@Description("Testing that rollout paged list contains rollouts")
public void rolloutPagedListContainsAllRollouts() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "name==target1");
postRollout("rollout2", 5, dsA.getId(), "name==target2");
mvc.perform(get("/rest/v1/rollouts")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)))
.andExpect(jsonPath("content[0].name", equalTo("rollout1")))
.andExpect(jsonPath("content[0].status", equalTo("ready")))
.andExpect(jsonPath("content[0].targetFilterQuery", equalTo("name==target1")))
.andExpect(jsonPath("content[0].distributionSetId", equalTo(dsA.getId().intValue())))
.andExpect(jsonPath("content[1].name", equalTo("rollout2")))
.andExpect(jsonPath("content[1].status", equalTo("ready")))
.andExpect(jsonPath("content[1].targetFilterQuery", equalTo("name==target2")))
.andExpect(jsonPath("content[1].distributionSetId", equalTo(dsA.getId().intValue())));
}
@Test
@Description("Testing that rollout paged list is limited by the query param limit")
public void rolloutPagedListIsLimitedToQueryParam() throws Exception {
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// setup - create 2 rollouts
postRollout("rollout1", 10, dsA.getId(), "name==target1");
postRollout("rollout2", 5, dsA.getId(), "name==target2");
mvc.perform(get("/rest/v1/rollouts?limit=1")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(2)));
}
@Test
@Description("Testing that rollout paged list is limited by the query param limit")
public void retrieveRolloutGroupsForSpecificRollout() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
// retrieve rollout groups from created rollout
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(4))).andExpect(jsonPath("$total", equalTo(4)))
.andExpect(jsonPath("$content[0].status", equalTo("ready")))
.andExpect(jsonPath("$content[1].status", equalTo("ready")))
.andExpect(jsonPath("$content[2].status", equalTo("ready")))
.andExpect(jsonPath("$content[3].status", equalTo("ready")));
}
@Test
@Description("Testing that starting the rollout switches the state to running")
public void startingRolloutSwitchesIntoRunningState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
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())
.andExpect(status().isOk());
// check rollout is in running state
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
.andExpect(jsonPath("status", equalTo("running")));
}
@Test
@Description("Testing that pausing the rollout switches the state to paused")
public void pausingRolloutSwitchesIntoPausedState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
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())
.andExpect(status().isOk());
// pausing rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/pause", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check rollout is in running state
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
.andExpect(jsonPath("status", equalTo("paused")));
}
@Test
@Description("Testing that resuming the rollout switches the state to running")
public void resumingRolloutSwitchesIntoRunningState() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
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())
.andExpect(status().isOk());
// pausing rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/pause", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// resume rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/resume", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check rollout is in running state
mvc.perform(get("/rest/v1/rollouts/{rolloutId}", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("id", equalTo(rollout.getId().intValue())))
.andExpect(jsonPath("status", equalTo("running")));
}
@Test
@Description("Testing that an already started rollout cannot be started again and returns bad request")
public void startingAlreadyStartedRolloutReturnsBadRequest() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
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())
.andExpect(status().isOk());
// starting rollout - already started should lead into bad request
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rollout.illegalstate")));
}
@Test
@Description("Testing that resuming a rollout which is not started leads to bad request")
public void resumingNotStartedRolloutReturnsBadRequest() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
// resume not yet started rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/resume", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("errorCode", equalTo("hawkbit.server.error.rollout.illegalstate")));
}
@Test
@Description("Testing that starting rollout the first rollout group is in running state")
public void startingRolloutFirstRolloutGroupIsInRunningState() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
// starting rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// retrieve rollout groups from created rollout - 2 groups exists
// (amountTargets / groupSize = 2)
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups?sort=ID:ASC", rollout.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)))
.andExpect(jsonPath("$content[0].status", equalTo("running")))
.andExpect(jsonPath("$content[1].status", equalTo("scheduled")));
}
@Test
@Description("Testing that a single rollout group can be retrieved")
public void retrieveSingleRolloutGroup() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
final RolloutGroup firstGroup = rolloutGroupManagement
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
.get(0);
// retrieve single rollout group with known ID
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}", rollout.getId(), firstGroup.getId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("id", equalTo(firstGroup.getId().intValue())))
.andExpect(jsonPath("status", equalTo("ready"))).andExpect(jsonPath("name", notNullValue()));
}
@Test
@Description("Testing that the targets of rollout group can be retrieved")
public void retrieveTargetsFromRolloutGroup() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
final RolloutGroup firstGroup = rolloutGroupManagement
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
.get(0);
// retrieve targets from the first rollout group with known ID
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(),
firstGroup.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(5))).andExpect(jsonPath("$total", equalTo(5)));
}
@Test
@Description("Testing that the targets of rollout group can be retrieved with rsql query param")
public void retrieveTargetsFromRolloutGroupWithQuery() throws Exception {
// setup
final int amountTargets = 10;
final List<Target> targets = targetManagement
.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
final RolloutGroup firstGroup = rolloutGroupManagement
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
.get(0);
// retrieve targets from the first rollout group with known ID
mvc.perform(
get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(), firstGroup.getId())
.param("q", "controllerId==" + targets.get(0).getControllerId()))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)));
}
@Test
@Description("Testing that the targets of rollout group can be retrieved after the rollout has been started")
public void retrieveTargetsFromRolloutGroupAfterRolloutIsStarted() throws Exception {
// setup
final int amountTargets = 10;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 2, dsA.getId(), "controllerId==rollout*");
rolloutManagement.startRollout(rollout);
final RolloutGroup firstGroup = rolloutGroupManagement
.findRolloutGroupsByRolloutId(rollout.getId(), new PageRequest(0, 1, Direction.ASC, "id")).getContent()
.get(0);
// retrieve targets from the first rollout group with known ID
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups/{groupId}/targets", rollout.getId(),
firstGroup.getId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(5))).andExpect(jsonPath("$total", equalTo(5)));
}
@Test
@Description("Start the rollout in async mode")
public void startingRolloutSwitchesIntoRunningStateAsync() throws Exception {
final int amountTargets = 1000;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
// starting rollout
mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId())
.param(MgmtRestConstants.REQUEST_PARAMETER_ASYNC, "true")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
// check if running
assertThat(doWithTimeout(() -> getRollout(rollout.getId()), result -> success(result), 60_000, 100))
.isNotNull();
}
@Test
@Description("Testing that rollout paged list with rsql parameter")
public void getRolloutWithRSQLParam() throws Exception {
final int amountTargetsRollout1 = 25;
final int amountTargetsRollout2 = 25;
final int amountTargetsRollout3 = 25;
final int amountTargetsOther = 25;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout1, "rollout1", "rollout1"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout2, "rollout2", "rollout2"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsRollout3, "rollout3", "rollout3"));
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargetsOther, "other1", "other1"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
createRollout("rollout1", 5, dsA.getId(), "controllerId==rollout1*");
final Rollout rollout2 = createRollout("rollout2", 5, dsA.getId(), "controllerId==rollout2*");
createRollout("rollout3", 5, dsA.getId(), "controllerId==rollout3*");
createRollout("other1", 5, dsA.getId(), "controllerId==other1*");
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*2"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)))
.andExpect(jsonPath("$content[0].name", equalTo(rollout2.getName())));
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==rollout*"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(3))).andExpect(jsonPath("$total", equalTo(3)));
mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*1"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)));
}
@Test
@Description("Testing that rolloutgroup paged list with rsql parameter")
public void retrieveRolloutGroupsForSpecificRolloutWithRSQLParam() throws Exception {
// setup
final int amountTargets = 20;
targetManagement.createTargets(TestDataUtil.buildTargetFixtures(amountTargets, "rollout", "rollout"));
final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement,
distributionSetManagement);
// create rollout including the created targets with prefix 'rollout'
final Rollout rollout = createRollout("rollout1", 4, dsA.getId(), "controllerId==rollout*");
// retrieve rollout groups from created rollout
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1)))
.andExpect(jsonPath("$content[0].name", equalTo("group-1")));
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group*")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(4))).andExpect(jsonPath("$total", equalTo(4)));
mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId())
.param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1,name==group-2"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2)));
}
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) throws Exception {
mvc.perform(post("/rest/v1/rollouts")
.content(JsonBuilder.rollout(name, "desc", groupSize, distributionSetId, targetFilterQuery, null))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated()).andReturn();
}
private Rollout createRollout(final String name, final int amountGroups, final long distributionSetId,
final String targetFilterQuery) {
final Rollout rollout = new Rollout();
rollout.setDistributionSet(distributionSetManagement.findDistributionSetById(distributionSetId));
rollout.setName(name);
rollout.setTargetFilterQuery(targetFilterQuery);
return rolloutManagement.createRollout(rollout, amountGroups, new RolloutGroupConditionBuilder()
.successCondition(RolloutGroupSuccessCondition.THRESHOLD, "100").build());
}
protected boolean success(final Rollout result) {
if (null != result && result.getStatus() == RolloutStatus.RUNNING) {
return true;
}
return false;
}
public Rollout getRollout(final Long rolloutId) throws Exception {
return rolloutManagement.findRolloutById(rolloutId);
}
}

View File

@@ -0,0 +1,357 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.WithUser;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.SoftwareModuleType;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import com.jayway.jsonpath.JsonPath;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Test for {@link MgmtSoftwareModuleTypeResource}.
*
*/
@Features("Component Tests - Management API")
@Stories("Software Module Type Resource")
public class MgmtSoftwareModuleTypeResourceTest extends AbstractIntegrationTest {
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests.")
public void getSoftwareModuleTypes() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].name", equalTo(osType.getName())))
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].description",
equalTo(osType.getDescription())))
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("$content.[?(@.key==" + osType.getKey() + ")][0].key", equalTo("os")))
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].name",
equalTo(runtimeType.getName())))
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].description",
equalTo(runtimeType.getDescription())))
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("$content.[?(@.key==" + runtimeType.getKey() + ")][0].key", equalTo("runtime")))
.andExpect(
jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].name", equalTo(appType.getName())))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].description",
equalTo(appType.getDescription())))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("$content.[?(@.key==" + appType.getKey() + ")][0].key", equalTo("application")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].lastModifiedAt",
equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[?(@.key==test123)][0].key", equalTo("test123")))
.andExpect(jsonPath("$total", equalTo(4)));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with sorting by MAXASSIGNMENTS field.")
public void getSoftwareModuleTypesSortedByMaxAssignments() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
// descending
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[0].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[0].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[0].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[0].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[0].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[0].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
// ascending
mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON)
.param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC"))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$content.[3].name", equalTo("TestName123")))
.andExpect(jsonPath("$content.[3].description", equalTo("Desc1234")))
.andExpect(jsonPath("$content.[3].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$content.[3].lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$content.[3].lastModifiedAt", equalTo(testType.getLastModifiedAt())))
.andExpect(jsonPath("$content.[3].maxAssignments", equalTo(5)))
.andExpect(jsonPath("$content.[3].key", equalTo("test123"))).andExpect(jsonPath("$total", equalTo(4)));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes POST requests.")
public void createSoftwareModuleTypes() throws JSONException, Exception {
final List<SoftwareModuleType> types = new ArrayList<>();
types.add(new SoftwareModuleType("test1", "TestName1", "Desc1", 1));
types.add(new SoftwareModuleType("test2", "TestName2", "Desc2", 2));
types.add(new SoftwareModuleType("test3", "TestName3", "Desc3", 3));
final MvcResult mvcResult = mvc
.perform(post("/rest/v1/softwaremoduletypes/").content(JsonBuilder.softwareModuleTypes(types))
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("[0].name", equalTo("TestName1"))).andExpect(jsonPath("[0].key", equalTo("test1")))
.andExpect(jsonPath("[0].description", equalTo("Desc1")))
.andExpect(jsonPath("[0].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[0].maxAssignments", equalTo(1)))
.andExpect(jsonPath("[1].name", equalTo("TestName2"))).andExpect(jsonPath("[1].key", equalTo("test2")))
.andExpect(jsonPath("[1].description", equalTo("Desc2")))
.andExpect(jsonPath("[1].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[1].maxAssignments", equalTo(2)))
.andExpect(jsonPath("[2].name", equalTo("TestName3"))).andExpect(jsonPath("[2].key", equalTo("test3")))
.andExpect(jsonPath("[2].description", equalTo("Desc3")))
.andExpect(jsonPath("[2].createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("[2].createdAt", not(equalTo(0))))
.andExpect(jsonPath("[2].maxAssignments", equalTo(3))).andReturn();
final SoftwareModuleType created1 = softwareManagement.findSoftwareModuleTypeByKey("test1");
final SoftwareModuleType created2 = softwareManagement.findSoftwareModuleTypeByKey("test2");
final SoftwareModuleType created3 = softwareManagement.findSoftwareModuleTypeByKey("test3");
assertThat(
JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created1.getId());
assertThat(
JsonPath.compile("[1]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created2.getId());
assertThat(
JsonPath.compile("[2]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString())
.isEqualTo("http://localhost/rest/v1/softwaremoduletypes/" + created3.getId());
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(6);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} GET requests.")
public void getSoftwareModuleType() throws Exception {
SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
testType.setDescription("Desc1234");
testType = softwareManagement.updateSoftwareModuleType(testType);
mvc.perform(get("/rest/v1/softwaremoduletypes/{smtId}", testType.getId()).accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$name", equalTo("TestName123")))
.andExpect(jsonPath("$description", equalTo("Desc1234")))
.andExpect(jsonPath("$maxAssignments", equalTo(5)))
.andExpect(jsonPath("$createdBy", equalTo("uploadTester")))
.andExpect(jsonPath("$createdAt", equalTo(testType.getCreatedAt())))
.andExpect(jsonPath("$lastModifiedBy", equalTo("uploadTester")))
.andExpect(jsonPath("$lastModifiedAt", equalTo(testType.getLastModifiedAt())));
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (hard delete scenario).")
public void deleteSoftwareModuleTypeUnused() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
@Test
@WithUser(principal = "uploadTester", allSpPermissions = true)
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} DELETE requests (soft delete scenario).")
public void deleteSoftwareModuleTypeUsed() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
softwareManagement
.createSoftwareModule(new SoftwareModule(testType, "name", "version", "description", "vendor"));
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(4);
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
mvc.perform(delete("/rest/v1/softwaremoduletypes/{smId}", testType.getId())).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk());
assertThat(softwareModuleTypeRepository.count()).isEqualTo(4);
assertThat(softwareManagement.countSoftwareModuleTypesAll()).isEqualTo(3);
}
@Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes/{ID} PUT requests.")
public void updateSoftwareModuleTypeOnlyDescriptionAndNameUntouched() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final String body = new JSONObject().put("id", testType.getId()).put("description", "foobardesc")
.put("name", "nameShouldNotBeChanged").toString();
mvc.perform(put("/rest/v1/softwaremoduletypes/{smId}", testType.getId()).content(body)
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath("$id", equalTo(testType.getId().intValue())))
.andExpect(jsonPath("$description", equalTo("foobardesc")))
.andExpect(jsonPath("$name", equalTo("TestName123"))).andReturn();
}
@Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
public void getSoftwareModuleTypesWithoutAddtionalRequestParameters() throws Exception {
final int types = 3;
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types)));
}
@Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
public void getSoftwareModuleTypesWithPagingLimitRequestParameter() throws Exception {
final int types = 3;
final int limitSize = 1;
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_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(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize)));
}
@Test
@Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.")
public void getSoftwareModuleTypesWithPagingLimitAndOffsetRequestParameter() throws Exception {
final int types = 3;
final int offsetParam = 2;
final int expectedSize = types - offsetParam;
mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam))
.param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types)))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isOk())
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize)))
.andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize)));
}
@Test
@Description("Ensures that the server is behaving as expected on invalid requests (wrong media type, wrong ID etc.).")
public void invalidRequestsOnSoftwaremoduleTypesResource() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final List<SoftwareModuleType> types = new ArrayList<>();
types.add(testType);
// SM does not exist
mvc.perform(get("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
mvc.perform(delete("/rest/v1/softwaremoduletypes/12345678")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isNotFound());
// bad request - no content
mvc.perform(post("/rest/v1/softwaremoduletypes").contentType(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest());
// bad request - bad content
mvc.perform(post("/rest/v1/softwaremoduletypes").content("sdfjsdlkjfskdjf".getBytes())
.contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isBadRequest());
// unsupported media type
mvc.perform(post("/rest/v1/softwaremoduletypes").content(JsonBuilder.softwareModuleTypes(types))
.contentType(MediaType.APPLICATION_OCTET_STREAM)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isUnsupportedMediaType());
// not allowed methods
mvc.perform(put("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
mvc.perform(delete("/rest/v1/softwaremoduletypes")).andDo(MockMvcResultPrinter.print())
.andExpect(status().isMethodNotAllowed());
}
@Test
@Description("Search erquest of software module types.")
public void searchSoftwareModuleTypeRsql() throws Exception {
final SoftwareModuleType testType = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test123", "TestName123", "Desc123", 5));
final SoftwareModuleType testType2 = softwareManagement
.createSoftwareModuleType(new SoftwareModuleType("test1234", "TestName1234", "Desc123", 5));
final String rsqlFindLikeDs1OrDs2 = "name==TestName123,name==TestName1234";
mvc.perform(get("/rest/v1/softwaremoduletypes?q=" + rsqlFindLikeDs1OrDs2)).andDo(MockMvcResultPrinter.print())
.andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2)))
.andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].name", equalTo("TestName123")))
.andExpect(jsonPath("content[1].name", equalTo("TestName1234")));
}
private void createSoftwareModulesAlphabetical(final int amount) {
char character = 'a';
for (int index = 0; index < amount; index++) {
final String str = String.valueOf(character);
final SoftwareModule softwareModule = new SoftwareModule(osType, str, str, str, str);
softwareManagement.createSoftwareModule(softwareModule);
character++;
}
}
}

View File

@@ -0,0 +1,55 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
import org.springframework.test.web.servlet.result.PrintingResultHandler;
import org.springframework.util.CollectionUtils;
public abstract class MockMvcResultPrinter {
private static final Logger LOG = LoggerFactory.getLogger(MockMvcResultPrinter.class);
private MockMvcResultPrinter() {
}
/**
* Print {@link MvcResult} details to the "standard" output stream.
*/
public static ResultHandler print() {
return new ConsolePrintingResultHandler();
}
/**
* An {@link PrintingResultHandler} that writes to the "standard" output
* stream
*/
private static class ConsolePrintingResultHandler extends PrintingResultHandler {
public ConsolePrintingResultHandler() {
super(new ResultValuePrinter() {
@Override
public void printHeading(final String heading) {
LOG.debug(String.format("%20s:", heading));
}
@Override
public void printValue(final String label, Object value) {
if (value != null && value.getClass().isArray()) {
value = CollectionUtils.arrayToList(value);
}
LOG.debug(String.format("%20s = %s", label, value));
}
});
}
}
}

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.io.IOException;
import org.eclipse.hawkbit.mgmt.json.model.PagedList;
import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Utility additions for the REST API tests.
*
*
*
*
*/
public final class ResourceUtility {
private static final ObjectMapper mapper = new ObjectMapper();
static ExceptionInfo convertException(final String jsonExceptionResponse)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonExceptionResponse, ExceptionInfo.class);
}
static MgmtArtifact convertArtifactResponse(final String jsonResponse)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(jsonResponse, MgmtArtifact.class);
}
static <T> PagedList<T> mapResponse(final Class<T> clazz, final String responseBody)
throws JsonParseException, JsonMappingException, IOException {
return mapper.readValue(responseBody, PagedList.class);
}
}

View File

@@ -0,0 +1,76 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import static org.fest.assertions.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.apache.commons.lang3.RandomStringUtils;
import org.eclipse.hawkbit.AbstractIntegrationTest;
import org.eclipse.hawkbit.exception.SpServerError;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.rest.json.model.ExceptionInfo;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MvcResult;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
/**
* Tests {@link MgmtSoftwareModuleResource} in case of missing MongoDB
* connection.
*
*/
@Features("Component Tests - Management API")
@Stories("Download Resource")
public class SMRessourceMisingMongoDbConnectionTest extends AbstractIntegrationTest {
@BeforeClass
public static void initialize() {
// set property to mongoPort which does not start any mongoDB of
// parallel test execution
System.setProperty("spring.data.mongodb.port", "1020");
}
@Test
@Description("Ensures that the correct error code is returned in case MongoDB unavailable.")
public void missingMongoDbConnectionResultsInErrorAtUpload() throws Exception {
assertThat(softwareManagement.findSoftwareModulesAll(pageReq)).hasSize(0);
assertThat(artifactRepository.findAll()).hasSize(0);
SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1",
"version 1", null, null);
sm = softwareManagement.createSoftwareModule(sm);
assertThat(artifactRepository.findAll()).hasSize(0);
// create test file
final byte random[] = RandomStringUtils.random(5 * 1024).getBytes();
final MockMultipartFile file = new MockMultipartFile("file", "origFilename", null, random);
// upload
final MvcResult mvcResult = mvc
.perform(fileUpload("/rest/v1/softwaremodules/{smId}/artifacts", sm.getId()).file(file))
.andDo(MockMvcResultPrinter.print()).andExpect(status().isInternalServerError()).andReturn();
// check error result
final ExceptionInfo exceptionInfo = ResourceUtility
.convertException(mvcResult.getResponse().getContentAsString());
assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getKey());
assertThat(exceptionInfo.getMessage()).isEqualTo(SpServerError.SP_ARTIFACT_UPLOAD_FAILED.getMessage());
// ensure that the JPA transaction was rolled back
assertThat(artifactRepository.findAll()).hasSize(0);
}
}

View File

@@ -0,0 +1,26 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
/**
*
* @author Dennis Melzer
*
* @param <T>
*/
public interface SuccessCondition<T> {
/**
*
* @param result
* @return
*/
boolean success(final T result);
}

View File

@@ -0,0 +1,63 @@
#
# Copyright (c) 2015 Bosch Software Innovations GmbH and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# used if IM profile is disabled
security.ignored=true
# IM required for integration tests
spring.profiles.active=im,suiteembedded,artifactrepository,redis
server.port=12222
spring.data.mongodb.uri=mongodb://localhost/spArtifactRepository${random.value}
spring.data.mongodb.port=28017
# supported: H2, MYSQL
hawkbit.server.database=H2
hawkbit.server.database.env=TEST
spring.main.show_banner=false
hawkbit.server.ddi.security.authentication.header=true
hawkbit.server.artifact.repo.upload.maxFileSize=5MB
hawkbit.server.security.dos.maxStatusEntriesPerAction=100
hawkbit.server.security.dos.maxAttributeEntriesPerTarget=10
spring.jpa.database=${hawkbit.server.database}
#spring.jpa.show-sql=true
flyway.sqlMigrationSuffix=${spring.jpa.database}.sql
# effective DB setting
spring.datasource.url=${${hawkbit.server.database}.spring.datasource.url}
spring.datasource.driverClassName=${${hawkbit.server.database}.spring.datasource.driverClassName}
spring.datasource.username=${${hawkbit.server.database}.spring.datasource.username}
spring.datasource.password=${${hawkbit.server.database}.spring.datasource.password}
# H2
##;AUTOCOMMIT=ON
H2.spring.datasource.url=jdbc:h2:mem:sp-db;DB_CLOSE_ON_EXIT=FALSE
#H2.spring.datasource.url=jdbc:h2:./db/sp-db;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE;MVCC=TRUE
H2.spring.datasource.driverClassName=org.h2.Driver
H2.spring.datasource.username=sa
H2.spring.datasource.password=sa
# MYSQL
MYSQL.spring.datasource.url=jdbc:mysql://localhost:3306/sp_test
MYSQL.spring.datasource.driverClassName=org.mariadb.jdbc.Driver
MYSQL.spring.datasource.username=root
MYSQL.spring.datasource.password=
# SP Controller configuration
hawkbit.controller.pollingTime=00:01:00
hawkbit.controller.pollingOverdueTime=00:01:00

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (c) 2015 Bosch Software Innovations GmbH and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html
-->
<Configuration status="WARN" monitorInterval="30">
<Appenders>
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="[%t] [%-5level] %logger{36} - %msg%n" charset="UTF-8"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.eclipse.hawkbit.MockMvcResultPrinter" level="error" />
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>