diff options
Diffstat (limited to 'src/main/java/org/onap/dcae')
69 files changed, 6690 insertions, 0 deletions
diff --git a/src/main/java/org/onap/dcae/ci/api/healthcheck/HealthcheckTest.java b/src/main/java/org/onap/dcae/ci/api/healthcheck/HealthcheckTest.java new file mode 100644 index 0000000..cce54bf --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/healthcheck/HealthcheckTest.java @@ -0,0 +1,59 @@ +package org.onap.dcae.ci.api.healthcheck; + +import com.aventstack.extentreports.Status; +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.restmodels.health.ComponentsInfo; +import org.onap.sdc.dcae.composition.restmodels.health.HealthResponse; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class HealthcheckTest extends DcaeRestBaseTest { + + @Test + public void getHealthcheck_statusOK() throws IOException { + Report.log(Status.INFO, "Starting Health Check test"); + RestResponse response = DcaeRestClient.getHealthcheck(); + Report.log(Status.INFO, "Health Check response=%s", response); + assertThat(response.getStatusCode().intValue()) + .as("response status") + .isEqualTo(200); + } + + @Test + public void getHealthcheck_validDataStructure() throws IOException { + Report.log(Status.INFO, "Starting getHealthcheck_validDataStructure"); + RestResponse response = DcaeRestClient.getHealthcheck(); + Report.log(Status.INFO, "Response=%s", response); + HealthResponse hcData = gson.fromJson(response.getResponse(), HealthResponse.class); + + SoftAssertions.assertSoftly(softly -> { + assertHealthStructure(softly, hcData, "DCAE Designer"); + List<ComponentsInfo> componentsInfo = hcData.getComponentsInfo(); + softly.assertThat(componentsInfo).extracting("healthCheckComponent").contains("BE", "TOSCA_LAB"); + assertHealthComponentStructure(softly, hcData.getComponentsInfo().get(0)); + assertHealthComponentStructure(softly, hcData.getComponentsInfo().get(1)); + }); + } + + private void assertHealthStructure(SoftAssertions softly, HealthResponse hcData, String name) { + softly.assertThat(hcData.getHealthCheckComponent()).isEqualTo(name); + softly.assertThat(hcData.getHealthCheckStatus()).isEqualTo("UP"); + softly.assertThat(hcData.getSdcVersion()).isNotEmpty(); + softly.assertThat(hcData.getDescription()).isNotEmpty(); + } + + private void assertHealthComponentStructure(SoftAssertions softly, ComponentsInfo hcData) { + softly.assertThat(hcData.getHealthCheckStatus()).isEqualTo("UP"); + softly.assertThat(hcData.getVersion()).isNotEmpty(); + softly.assertThat(hcData.getDescription()).isNotEmpty(); + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/dcae/ci/api/tests/DcaeRestBaseTest.java b/src/main/java/org/onap/dcae/ci/api/tests/DcaeRestBaseTest.java new file mode 100644 index 0000000..6bd8b51 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/DcaeRestBaseTest.java @@ -0,0 +1,166 @@ +package org.onap.dcae.ci.api.tests; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.apache.commons.lang3.RandomStringUtils; +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.entities.composition.services.CiService; +import org.onap.dcae.ci.entities.composition.services.Vfi; +import org.onap.dcae.ci.entities.sdc.SdcComponent; +import org.onap.dcae.ci.entities.sdc.SdcResource; +import org.onap.dcae.ci.entities.sdc.SdcService; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.*; +import org.onap.sdc.dcae.composition.model.Requirement; +import org.onap.sdc.dcae.composition.model.Value; +import org.onap.sdc.dcae.composition.model.deserializer.RequirementDeserializer; +import org.onap.sdc.dcae.composition.model.deserializer.ValueDeserializer; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ActionDeserializer; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseAction; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.BaseCondition; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.ConditionDeserializer; +import org.onap.sdc.dcae.composition.services.Artifact; +import org.onap.sdc.dcae.composition.services.Resource; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import org.testng.annotations.AfterSuite; + +import java.io.IOException; +import java.util.*; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class DcaeRestBaseTest extends SetupReport { + + public static Gson gson = null; + protected DcaeEntityClient client = new DcaeEntityClient(); + + public DcaeRestBaseTest() { + super(); + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeAdapter(Requirement.class, new RequirementDeserializer()); + gsonBuilder.registerTypeAdapter(Value.class, new ValueDeserializer()); + gsonBuilder.registerTypeAdapter(BaseAction.class, new ActionDeserializer()); + gsonBuilder.registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()); + gson = gsonBuilder.create(); + } + + @Override + protected Configuration getEnvConfiguration() { + return ConfigurationReader.getConfiguration(); + } + + protected Service createServiceWithVFiAsSdcDesigner() throws IOException { + Report.log(Status.INFO, "Create Service with VFi as SDC Designer method started"); + + SdcResource vf = SdcInternalApiClient.createVf(); + vf = SdcInternalApiClient.checkinVf(vf); + SdcService service = SdcInternalApiClient.createService(); + Vfi vfi = SdcInternalApiClient.createVfi(service, vf); + return convertToDcaeServiceWithVfi(service, vfi.getName()); + + } + + + // converts from ui-api-ci object to dcae-ci object (partial construction) + private Service convertToDcaeServiceWithVfi(SdcService service, String vfiName){ + Service newService = new CiService(service); + Resource newVfi = new Resource(); + newVfi.setResourceInstanceName(vfiName); + newService.setResources(Arrays.asList(newVfi)); + return newService; + } + + protected Vfcmt createVfcmt() throws IOException { + String newName = "CI" + RandomStringUtils.randomAlphanumeric(4); + Report.log(Status.INFO, "createVfcmt start"); + RestResponse res = DcaeRestClient.createVfcmt(newName, "description"); + Report.log(Status.INFO, "createVfcmt response=%s", res); + assertThat(res.getStatusCode()).isEqualTo(200); + return gson.fromJson(res.getResponse(), Vfcmt.class); + } + + protected Artifact fetchVfcmtArtifactMetadataByName(String vfcmtUid, String artifactName) throws IOException { + Report.log(Status.INFO, "fetchVfcmtArtifactMetadataByName, vfcmtUid="+vfcmtUid+", artifactName"+artifactName); + RestResponse res = DcaeRestClient.getResourceDetails(vfcmtUid); + Resource vfcmt = gson.fromJson(res.getResponse(), Resource.class); + return vfcmt.getArtifacts().stream() + .filter(a -> artifactName.equalsIgnoreCase(a.getArtifactName())) + .findAny() + .orElse(null); + } + + //***** delete all assets created by test users - uses internal SDC API ****// + + @AfterSuite(alwaysRun = true) + public static void cleanup() throws IOException { + + final String resources = "resources"; + final String services = "services"; + List<String> testUsers = Collections.synchronizedList(Arrays.asList(DcaeRestClient.getDefaultUserId(), DcaeRestClient.getDesigner2UserId())); + Map<String, List<SdcComponent>> testComponents = testUsers.parallelStream() + .map(DcaeRestBaseTest::getSafeComponentByUser) + .flatMap(m -> m.entrySet().stream()) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> { + v1.addAll(v2); + return v1; + })); + collectAllResourceIds(Collections.synchronizedList(testComponents.get(resources))).parallelStream().forEach(id -> deleteAsset(resources, id)); + collectAllServiceIds(Collections.synchronizedList(testComponents.get(services))).parallelStream().forEach(id -> deleteAsset(services, id)); + SdcInternalApiClient.deleteMarkedResources(); + SdcInternalApiClient.deleteMarkedServices(); + } + + private static Set<String> getUidsToDelete(String context, SdcComponent component) { + try { + return Arrays.asList("0.1", "1.0").contains(component.getVersion()) ? Collections.singleton(component.getUniqueId()) : + new HashSet<>(SdcInternalApiClient.getAssetMetadata(context, component.getUniqueId(), component.getLastUpdaterUserId()).getMetadata().getAllVersions().values()); + } catch (Exception e) { + Report.log(Status.ERROR, "failed to fetch sdc component: %s, Error: %s", component.getUniqueId(), e); + return Collections.emptySet(); + } + } + + private static Set<String> collectAllResourceIds(List<SdcComponent> resources) { + Predicate<SdcComponent> deleteResource = p -> Arrays.asList("VF", "VFCMT").contains(p.getResourceType()) && !"Base Monitoring Template".equals(p.getCategories().get(0).getSubcategories().get(0).getName()); + Set<String> resourceIds = Collections.synchronizedSet(resources.parallelStream() + .filter(deleteResource) + .map(r -> getUidsToDelete("resources", r)) + .flatMap(Set::stream) + .collect(Collectors.toSet())); + Report.log(Status.INFO, "collected %s resourceIds", resourceIds.size()); + return resourceIds; + } + + private static Set<String> collectAllServiceIds(List<SdcComponent> services) { + Set<String> serviceIds = Collections.synchronizedSet(services.parallelStream() + .map(c -> getUidsToDelete("services", c)) + .flatMap(Set::stream) + .collect(Collectors.toSet())); + Report.log(Status.INFO, "collected %s serviceIds", serviceIds.size()); + return serviceIds; + } + + private static Map<String, List<SdcComponent>> getSafeComponentByUser(String userId) { + try { + return SdcInternalApiClient.getAssetsByUser(userId); + } catch (Exception e){ + Report.log(Status.ERROR, "failed to fetch followed components. Error: %s", e); + return new HashMap<>(); + } + } + + private static void deleteAsset(String context, String id) { + try { + Report.log(Status.INFO, "about to delete sdc asset(%s): %s", context, id); + SdcInternalApiClient.deleteAssetFromSdc(context, id); + } catch (Exception e){ + Report.log(Status.ERROR, "failed to delete sdc asset(%s): %s, Error: %s" ,context, id, e); + } + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/blueprint/SaveCompositionPositve.java b/src/main/java/org/onap/dcae/ci/api/tests/blueprint/SaveCompositionPositve.java new file mode 100644 index 0000000..b5f37f8 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/blueprint/SaveCompositionPositve.java @@ -0,0 +1,109 @@ +package org.onap.dcae.ci.api.tests.blueprint; + +import com.aventstack.extentreports.Status; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.text.WordUtils; +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.utilities.DcaeUtil; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; + +public class SaveCompositionPositve extends DcaeRestBaseTest { + + private RestResponse response; + private static final String VFCMT_NAME = "teSt.__.monitoring---TempLATE."; + + private Vfcmt createVFCMTAndServiceWithVFIAndAttach() throws Exception{ + Report.log(Status.INFO, "createVFCMTAndServiceWithVFIAndAttach start"); + Vfcmt newVfcmt = createNewVfcmt(); + + // create a service in sdc + Service newService = createServiceWithVFiAsSdcDesigner(); + + String serviceUuid = newService.getUuid(); + String vfiName = newService.getResources().get(0).getResourceInstanceName(); + String vfcmtId = newVfcmt.getUuid(); + + // attach VFCMT to vfi and service (creation of svc_reference file in the BE) + Report.log(Status.INFO, "Going to attach the created service and VFi to the VFCMT"); + RestResponse res = DcaeRestClient.attachVfiRef(vfcmtId, serviceUuid, vfiName); + Report.log(Status.INFO, "attachment result="+res); + + return newVfcmt; + } + + private Vfcmt createNewVfcmtWithoutArtifact() throws Exception{ + Report.log(Status.INFO, "createNewVfcmtWithoutArtifact"); + Vfcmt newVfcmt = createNewVfcmt(); + return newVfcmt; + } + + private Vfcmt createNewVfcmt() throws Exception { + String randomSuffix = WordUtils.capitalize(RandomStringUtils.randomAlphanumeric(4).toLowerCase()); + Vfcmt newVfcmt = createVfcmtInstance(randomSuffix); + return newVfcmt; + } + + private Vfcmt createVfcmtInstance(String randomSuffix) throws Exception{ + String newName = VFCMT_NAME + randomSuffix; + RestResponse res = DcaeRestClient.createVfcmt(newName,"description"); + assertThat(res.getStatusCode()).isEqualTo(200); + return gson.fromJson(res.getResponse(), Vfcmt.class); + } + + + + @Test + public void test_responseStatusOkAndCreateMode() throws Exception{ + // assert + Report.log(Status.INFO, "Save Composition init"); + Vfcmt vfcmtWithoutArtifactUuid = createNewVfcmtWithoutArtifact(); + String uuid = vfcmtWithoutArtifactUuid.getUuid(); + String lastUpdaterUserId = vfcmtWithoutArtifactUuid.getLastUpdaterUserId(); + response = DcaeRestClient.saveComposition(uuid, lastUpdaterUserId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + Report.log(Status.INFO, "Verifing response status is 200"); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat((gson.fromJson(response.getResponse(), Resource.class)).getVersion()) + .as("version") + .isEqualTo("0.1"); + }); + } + + @Test + public void test_updateMode() throws Exception { + // assert + Report.log(Status.INFO, "Save Composition init"); + Vfcmt vfcmtWithArtifactUuid = createVFCMTAndServiceWithVFIAndAttach(); + String uuid = vfcmtWithArtifactUuid.getUuid(); + String lastUpdaterUserId = vfcmtWithArtifactUuid.getLastUpdaterUserId(); + Report.log(Status.INFO, "New VFCMT uuid="+uuid+", lastUpdaterUserId="+lastUpdaterUserId); + //generate cdump + String cdump = DcaeUtil.generateCdumpFromSnmpModels(uuid); + // save composition.yml + Report.log(Status.INFO, "Going to Save the composition now"); + DcaeRestClient.saveComposition(uuid, lastUpdaterUserId, cdump); + // update + response = DcaeRestClient.saveComposition(uuid, lastUpdaterUserId, cdump); + Report.log(Status.DEBUG, "Save composition Response: " + StringUtils.truncate(response)); + Report.log(Status.INFO, "Verifying response status is 200"); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat((gson.fromJson(response.getResponse(), Resource.class)).getVersion()) + .as("version") + .isEqualTo("0.3"); + }); + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionControllerApiTests.java b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionControllerApiTests.java new file mode 100644 index 0000000..a6e1525 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionControllerApiTests.java @@ -0,0 +1,201 @@ +package org.onap.dcae.ci.api.tests.composition; + +import com.aventstack.extentreports.Status; +import com.google.gson.JsonObject; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.text.WordUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.json.simple.parser.ParseException; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.utilities.DcaeUtil; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.services.Artifact; +import org.onap.sdc.dcae.composition.services.Resource; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CompositionControllerApiTests extends DcaeRestBaseTest { + + private static final String EVENT_PROC_BP_YAML = "event_proc_bp.yaml"; + private static final String CREATE_BLUEPRINT_DESCRIPTION = "creating new artifact blueprint on the service vfi"; + private static final String UPDATE_BLUEPRINT_DESCRIPTION = "updating artifact blueprint on the service vfi"; + private static final String VFCMT_NAME = "teSt.__.monitoring---TempLATE."; + private static final String NORMALIZED_VFCMT_NAME = "TestMonitoringTemplate"; + + @Test + public void createMultipleBlueprintsTest() throws Exception { + Report.log(Status.INFO, "createMultipleBlueprintsTest start"); + String randomSuffix = WordUtils.capitalize(RandomStringUtils.randomAlphanumeric(4).toLowerCase()); + Vfcmt newVfcmt = createVfcmt(randomSuffix); + + // create a service in sdc + Service newService = createServiceWithVFiAsSdcDesigner(); + + String serviceUuid = newService.getUuid(); + String vfiName = newService.getResources().get(0).getResourceInstanceName(); + String vfcmtId = newVfcmt.getUuid(); + + // attach VFCMT to vfi + Report.log(Status.INFO, "Trying to attach the service+vfi to the vfcmt. serviceUuid="+serviceUuid+", vfiName="+vfiName+", vfcmtId="+vfcmtId); + RestResponse res = DcaeRestClient.attachVfiRef(vfcmtId, serviceUuid, vfiName); + assertThat(res.getStatusCode()).isEqualTo(200); + + //generate and save composition.yml(cdump) + generateAndSaveCdump(vfcmtId); + + String bpType1 = "bpType t1"; + String bpType2 = "bpType T2"; + String normalizedVfcmtName = NORMALIZED_VFCMT_NAME + randomSuffix; + List<ImmutablePair<String, String>> expectedBpDetails = Arrays.asList(buildBlueprintDetails(bpType1, normalizedVfcmtName), buildBlueprintDetails(bpType2, normalizedVfcmtName)); + + // submit - generate and save type1 blueprint artifact + Report.log(Status.INFO, "Going to Submit the composition with vfcmtId="+vfcmtId+", serviceUuid="+serviceUuid+", vfiName="+vfiName+", TYPE1="+bpType1); + res = DcaeRestClient.submitComposition(vfcmtId, serviceUuid, vfiName, bpType1); + assertBlueprintSuccessResponse(res); + + // 1806 US 374593 assert vfcmt is certified + res = DcaeRestClient.getResourceDetails(vfcmtId); + newVfcmt = gson.fromJson(res.getResponse(), Vfcmt.class); + Report.log(Status.INFO, "Checking lifecycle state of vfcmt after first blueprint submission. State = {}", newVfcmt.getLifecycleState()); + assertThat(newVfcmt.getLifecycleState()).isEqualTo(DcaeBeConstants.LifecycleStateEnum.CERTIFIED.name()); + Report.log(Status.INFO, "Checking version of vfcmt after first blueprint submission. Version = {}", newVfcmt.getVersion()); + assertThat(newVfcmt.getVersion()).isEqualTo("1.0"); + + res = DcaeRestClient.checkoutVfcmt(vfcmtId, newVfcmt.getLastUpdaterUserId()); + newVfcmt = gson.fromJson(res.getResponse(), Vfcmt.class); + vfcmtId = newVfcmt.getUuid(); + // submit - generate and save type2 blueprint artifact + Report.log(Status.INFO, "Going to Submit the composition with vfcmtId="+vfcmtId+", serviceUuid="+serviceUuid+", vfiName="+vfiName+", TYPE2="+bpType2); + res = DcaeRestClient.submitComposition(vfcmtId, serviceUuid, vfiName, bpType2); + assertBlueprintSuccessResponse(res); + res = DcaeRestClient.getResourceDetails(vfcmtId); + newVfcmt = gson.fromJson(res.getResponse(), Vfcmt.class); + Report.log(Status.INFO, "Checking lifecycle state of vfcmt after checkout and second blueprint submission. State = {}", newVfcmt.getLifecycleState()); + assertThat(newVfcmt.getLifecycleState()).isEqualTo(DcaeBeConstants.LifecycleStateEnum.CERTIFIED.name()); + Report.log(Status.INFO, "Checking version of vfcmt after checkout and second blueprint submission. Version = {}", newVfcmt.getVersion()); + assertThat(newVfcmt.getVersion()).isEqualTo("2.0"); + assertBlueprintsExistOnVfiAfterUpload(expectedBpDetails, serviceUuid, vfiName); + } + + + @Test + public void updateBlueprintTest() throws Exception { + Report.log(Status.INFO, "updateBlueprintTest start"); + String randomSuffix = WordUtils.capitalize(RandomStringUtils.randomAlphanumeric(4).toLowerCase()); + Vfcmt newVfcmt = createVfcmt(randomSuffix); + + // create a service in sdc + Service newService = createServiceWithVFiAsSdcDesigner(); + + String serviceUuid = newService.getUuid(); + String vfiName = newService.getResources().get(0).getResourceInstanceName(); + String vfcmtId = newVfcmt.getUuid(); + + // attach VFCMT to vfi + RestResponse res = DcaeRestClient.attachVfiRef(vfcmtId, serviceUuid, vfiName); + assertThat(res.getStatusCode()).isEqualTo(200); + + generateAndSaveCdump(vfcmtId); + + String normalizedVfcmtName = NORMALIZED_VFCMT_NAME + randomSuffix; + String bpType1 = "bpType 1"; + ImmutablePair<String, String> expectedBpDetails = buildBlueprintDetails(bpType1, normalizedVfcmtName); + + // submit - generate and save type1 blueprint artifact + Report.log(Status.INFO, "Going to Submit the composition with vfcmtId="+vfcmtId+", serviceUuid="+serviceUuid+", vfiName="+vfiName+", bpType1="+bpType1); + res = DcaeRestClient.submitComposition(vfcmtId, serviceUuid, vfiName, bpType1); + assertBlueprintSuccessResponse(res); + // assert initial version exists + assertBlueprintExistsOnVfi(expectedBpDetails, serviceUuid, vfiName, CREATE_BLUEPRINT_DESCRIPTION); + + // submit - regenerate and save type1 blueprint artifact + Report.log(Status.INFO, "Going to Submit the composition with vfcmtId="+vfcmtId+", serviceUuid="+serviceUuid+", vfiName="+vfiName+", bpType1="+bpType1); + res = DcaeRestClient.submitComposition(vfcmtId, serviceUuid, vfiName, bpType1); + assertBlueprintSuccessResponse(res); + // assert blueprint updated + assertBlueprintExistsOnVfi(expectedBpDetails, serviceUuid, vfiName, UPDATE_BLUEPRINT_DESCRIPTION); + + } + + + private void assertBlueprintSuccessResponse(RestResponse response){ + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(DcaeUtil.getValueFromJsonResponse(response.getResponse(), "successResponse")).isNotNull(); + } + + private void assertBlueprintsExistOnVfiAfterUpload(List<ImmutablePair<String, String>> expectedBpDetails, String serviceId, String vfiName) throws IOException{ + List<Artifact> vfiArtifact = fetchVfiArtifacts(serviceId, vfiName); + List<ImmutablePair<String, String>> vfiArtifactDetails = vfiArtifact.stream() + .map(a -> new ImmutablePair<>(a.getArtifactLabel(), a.getArtifactName())) + .collect(Collectors.toList()); + for(ImmutablePair<String,String> bp : expectedBpDetails){ + assertThat(vfiArtifactDetails).contains(bp); + } + } + + private void assertBlueprintExistsOnVfi(ImmutablePair<String, String> expectedBpDetails, String serviceId, String vfiName, String description) throws IOException{ + List<Artifact> vfiArtifact = fetchVfiArtifacts(serviceId, vfiName); + Predicate<Artifact> artifactPredicate = p -> expectedBpDetails.getLeft().equals(p.getArtifactLabel()) && expectedBpDetails.getRight().equals(p.getArtifactName()) && description.equals(p.getArtifactDescription()); + Artifact artifact = vfiArtifact.stream() + .filter(artifactPredicate) + .findAny() + .orElse(null); + assertThat(artifact).isNotNull(); + } + + + private List<Artifact> fetchVfiArtifacts(String serviceId, String vfiName) throws IOException { + Report.log(Status.INFO, "fetchVfiArtifacts start"); + RestResponse serviceRes = DcaeRestClient.getServicesInstance(serviceId); + Report.log(Status.INFO, "fetchVfiArtifacts response=%s", serviceRes); + Service service = gson.fromJson(serviceRes.getResponse(), Service.class); + Resource vfi = service.getResources().stream() + .filter(p -> p.getResourceInstanceName().equals(vfiName)) + .findAny() + .orElse(null); + assertThat(vfi).isNotNull(); + return vfi.getArtifacts(); + } + + private ImmutablePair<String, String> buildBlueprintDetails(String bpType, String normalizedVfcmtName) { + return new ImmutablePair<>("blueprint"+(bpType.replaceAll(" ", "")+normalizedVfcmtName).toLowerCase(),bpType.replaceAll(" ", "-")+"."+normalizedVfcmtName+"."+EVENT_PROC_BP_YAML); + } + + + private Vfcmt createVfcmt(String randomSuffix) throws IOException { + String newName = VFCMT_NAME + randomSuffix; + Report.log(Status.DEBUG, "createVfcmt start. VFCMT Name="+newName); + RestResponse res = DcaeRestClient.createVfcmt(newName,"description"); + Report.log(Status.DEBUG, "Create VFCMT response=%s", res); + assertThat(res.getStatusCode()).isEqualTo(200); + return gson.fromJson(res.getResponse(), Vfcmt.class); + } + + private void generateAndSaveCdump(String vfcmtId) throws ParseException, IOException { + Report.log(Status.DEBUG, "generateAndSaveCdump start"); + RestResponse res = DcaeUtil.SdcElementsModelType.getItemModelFromSdc(0); + assertThat(res.getStatusCode()).isEqualTo(200); + JsonObject cdump = DcaeRestClient.generateCdumpInput(vfcmtId); + Report.log(Status.DEBUG, "Generated cdump="+cdump); + cdump.add("nodes", DcaeUtil.parseNodesFromDcaeModelAndAssignUiNid(res.getResponse())); + Report.log(Status.DEBUG, "save composition - generate and save composition.yml artifact"); + res = DcaeRestClient.saveComposition(vfcmtId, DcaeRestClient.getDefaultUserId(), cdump.toString()); + Report.log(Status.DEBUG, "Save composition result="+res); + assertThat(res.getStatusCode()).isEqualTo(200); + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionElementsControllerTests.java b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionElementsControllerTests.java new file mode 100644 index 0000000..0193df1 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionElementsControllerTests.java @@ -0,0 +1,200 @@ +package org.onap.dcae.ci.api.tests.composition; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.List; +import java.util.stream.Collectors; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; + +import org.onap.dcae.ci.entities.composition.rightMenu.element.Item; +import org.onap.dcae.ci.entities.composition.rightMenu.elements.Element; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.model.Model; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +public class CompositionElementsControllerTests extends DcaeRestBaseTest { + + JsonParser parser = new JsonParser(); + + @Test + public void test_getAllElements() throws IOException{ + Report.log(Status.INFO, "test_getAllElements start"); + RestResponse response = DcaeRestClient.getElements(); + Report.log(Status.INFO, "getElements response=%s", response); + JsonElement getElementJsonResponse = getElementsJson(response); + Type listType = new TypeToken<List<Element>>(){}.getType(); + List<Element> responseData = gson.fromJson(getElementJsonResponse, listType); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(getElementJsonResponse.toString()).isNotEmpty(); + softly.assertThat(responseData).extracting("itemId") + .containsExactlyInAnyOrder("Policy","Utility","Microservice","Database","Collector","Analytics","Source"); + }); + } + + + @DataProvider(name="item") + public static Object[][] allElementsItems() throws IOException{ + RestResponse response = DcaeRestClient.getElements(); + JsonElement getElementJsonResponse = getElementsJson(response); + Type listType = new TypeToken<List<Element>>(){}.getType(); + List<Element> responseData = gson.fromJson(getElementJsonResponse, listType); + return responseData + .stream() + .map(x -> new Object[]{ x.getItemId() } ) + .collect(Collectors.toList()) + .toArray(new Object[responseData.size()][1]); + } + + @Test(dataProvider ="item") + public void test_getAllElementsByItemId(String itemName) throws IOException{ + Report.log(Status.INFO, "test_getAllElementsByItemId start"); + RestResponse response = DcaeRestClient.getItem(itemName); + Report.log(Status.INFO, "getItem response=%s", response); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + }); + } + + @Test + public void test_getModelData() throws IOException{ + Report.log(Status.INFO, "test_getModelData start"); + RestResponse responseGetElements = DcaeRestClient.getElements(); + JsonElement obj = getElementsJson(responseGetElements); + String elementItemName = getElementItemName(obj); + + RestResponse responseElementsItem = DcaeRestClient.getItem(elementItemName); + JsonElement elementsById = parser.parse(responseElementsItem.getResponse()); + JsonElement itemData = elementsById.getAsJsonObject().get("data").getAsJsonObject().get("element").getAsJsonObject().get("items"); + + String elemId = getElementItemID(itemData); + Report.log(Status.INFO, "test_getModelData start"); + + RestResponse response = DcaeRestClient.getItemModel(elemId); + Report.log(Status.INFO, "getItemModel response=%s", response); + JsonElement responseJson = parser.parse(response.getResponse()); + JsonElement itemModelData = responseJson.getAsJsonObject().get("data").getAsJsonObject().get("model"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(itemModelData.toString()).isNotEmpty(); + }); + } + + @Test + public void test_getTypeData() throws IOException{ + Report.log(Status.INFO, "test_getTypeData start"); + RestResponse responseGetElements = DcaeRestClient.getElements(); + JsonElement obj = getElementsJson(responseGetElements); + String elementItemName = getElementItemName(obj); + + RestResponse responseElementsItem = DcaeRestClient.getItem(elementItemName); + JsonElement elementsById = parser.parse(responseElementsItem.getResponse()); + JsonElement itemData = elementsById.getAsJsonObject().get("data").getAsJsonObject().get("element").getAsJsonObject().get("items"); + + String elemId = getElementItemID(itemData); + RestResponse responseModel = DcaeRestClient.getItemModel(elemId); + JsonElement jsonRes = parser.parse(responseModel.getResponse()); + JsonElement jsonModel = jsonRes.getAsJsonObject().get("data").getAsJsonObject().get("model").getAsJsonObject(); + Model model = gson.fromJson(jsonModel, Model.class); + List<String> nodesDataTypes = model.getNodes().stream() + .map(y -> y.getType()) + .collect(Collectors.toList()); + + nodesDataTypes.forEach(z -> Report.log(Status.INFO, "All types inside model: " + z)); + String nodeType = nodesDataTypes.get(0); + RestResponse response = DcaeRestClient.getItemType(elemId, nodeType); + JsonElement elementsById2 = parser.parse(response.getResponse()); + JsonElement data2 = elementsById2.getAsJsonObject().get("data").getAsJsonObject().get("type").getAsJsonObject(); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(data2.toString()).isNotEmpty(); + }); + } + + /**************** nagative ***************/ + @Test + public void test_getAllElementsByNonExistItemId() throws IOException{ + Report.log(Status.INFO, "test_getAllElementsByNonExistItemId start"); + RestResponse response = DcaeRestClient.getItem("notExist"); + JsonElement elementsById = parser.parse(response.getResponse()); + JsonElement exception = elementsById.getAsJsonObject().get("error").getAsJsonObject().get("exception"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(exception.toString()).isNotEmpty(); + }); + } + + @Test + public void test_getErrorNonExistingModelData() throws IOException{ + Report.log(Status.INFO, "test_getErrorNonExistingModelData start"); + RestResponse response = DcaeRestClient.getItemModel("notExist"); + JsonElement elementsById = parser.parse(response.getResponse()); + JsonElement exception = elementsById.getAsJsonObject().get("error"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(500); + softly.assertThat(exception.toString()).isNotEmpty(); + }); + } + + @Test + public void test_getErrorNonExistingItemType() throws IOException{ + Report.log(Status.INFO, "test_getErrorNonExistingItemType start"); + RestResponse response = DcaeRestClient.getItemType("notExistId","nonType"); + JsonElement elementsById = parser.parse(response.getResponse()); + JsonElement exception = elementsById.getAsJsonObject().get("error"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(500); + softly.assertThat(exception.toString()).isNotEmpty(); + }); + } + + /******************** private ********************/ + private static JsonElement getElementsJson(RestResponse response) { + JsonParser parser = new JsonParser(); + JsonElement element = parser.parse(response.getResponse()); + JsonElement obj = element.getAsJsonObject().get("data").getAsJsonObject().get("elements"); + return obj; + } + + private String getElementItemName(JsonElement obj) { + Type listType = new TypeToken<List<Element>>(){}.getType(); + List<Element> fromJson = gson.fromJson(obj, listType); + List<Element> collect = fromJson.stream().filter(x->x.getName().equals("Microservice")).collect(Collectors.toList()); + Element element = collect.get(0); + String elementItemName = element.getName(); + return elementItemName; + } + + private String getElementItemID(JsonElement data) { + Type listType = new TypeToken<List<Item>>(){}.getType(); + List<Item> elementsItemFoi = gson.fromJson(data, listType); + Report.log(Status.INFO, "getElementItemID for map"); + List<Item> foiItemData = elementsItemFoi.stream().filter(x->x.getName().equalsIgnoreCase("map")).collect(Collectors.toList()); + if(foiItemData!=null && foiItemData.size()>0){ + Item item = foiItemData.get(0); + String elemId = item.getItemId(); + return elemId; + }else{ + Report.log(Status.ERROR, "getElementItemID for map failed. Does the CI environment has map component in it??"); + return null; + } + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionMicroServicesApiTests.java b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionMicroServicesApiTests.java new file mode 100644 index 0000000..9808400 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/composition/CompositionMicroServicesApiTests.java @@ -0,0 +1,90 @@ +package org.onap.dcae.ci.api.tests.composition; + +import static org.assertj.core.api.Assertions.*; + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.utilities.DcaeTestConstants; +import org.onap.dcae.ci.utilities.DcaeUtil; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.model.ModelDcae; +import org.testng.annotations.*; + +import java.io.IOException; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + + +import com.aventstack.extentreports.Status; + + +public class CompositionMicroServicesApiTests extends DcaeRestBaseTest { + + @Test + public void getAllElementsTest() throws IOException, ParseException{ + Report.log(Status.INFO, "getAllElementsTest start"); + RestResponse services = DcaeRestClient.getElements(); + Report.log(Status.INFO, "getAllElementsTest response=%s", services); + assertThat(services.getStatusCode().intValue()).isEqualTo(200); + String response = services.getResponse(); + JSONParser parser = new JSONParser(); + JSONObject o = (JSONObject) parser.parse(response); + JSONObject ele = (JSONObject) o.get("data"); + String arrString = ele.get("elements").toString(); + assertThat(arrString) + .as("Check that elements not empty") + .isNotEmpty(); + } + + @Test + public void getMsElementsTest() throws IOException, ParseException{ + Report.log(Status.INFO, "getMsElementsTest start"); + RestResponse services = DcaeUtil.SdcElementsModelType.getMsElements(); + Report.log(Status.INFO, "getMsElementsTest response=%s", services); + assertThat(services.getStatusCode().intValue()).isEqualTo(200); + String response = services.getResponse(); + JSONParser parser = new JSONParser(); + JSONObject o = (JSONObject) parser.parse(response); + JSONObject ele = (JSONObject) o.get("data"); + String arrString = ele.get("element").toString(); + assertThat(arrString) + .as("Check that elements not empty") + .isNotEmpty(); + } + + @Test + public void getItemModelTest() throws IOException{ + Report.log(Status.INFO, "getItemModelTest start"); + RestResponse itemModelRes = DcaeUtil.SdcElementsModelType.getItemModelFromSdc(0); + Report.log(Status.INFO, "getItemModelTest response=%s", itemModelRes); + assertThat(itemModelRes.getStatusCode().intValue()).isEqualTo(200); + + String response = itemModelRes.getResponse(); + JSONObject object = (JSONObject) JSONValue.parse(response); + String errorMsg = object.get("error").toString(); + assertThat(errorMsg).isEqualTo(DcaeTestConstants.Composition.EMPTY_OBJECT); + } + + @Test + public void getItemTypeTest() throws IOException{ + Report.log(Status.INFO, "getItemModelTest start"); + RestResponse itemModelRes = DcaeUtil.SdcElementsModelType.getItemModelFromSdc(0); + Report.log(Status.INFO, "itemModelRes response=%s", itemModelRes); + String response = itemModelRes.getResponse(); + + String uuid = DcaeUtil.SdcElementsModelType.getItemUuid(0); + + ModelDcae model = gson.fromJson(response, ModelDcae.class); + Report.log(Status.INFO, "model "+model); + String type = model.getData().getModel().getNodes().get(0).getType(); + Report.log(Status.INFO, "type "+type); + + RestResponse services = DcaeRestClient.getItemType(uuid, type); + assertThat(services.getStatusCode().intValue()).isEqualTo(200); + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/composition/GetCompositionControllerTests.java b/src/main/java/org/onap/dcae/ci/api/tests/composition/GetCompositionControllerTests.java new file mode 100644 index 0000000..169c5a8 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/composition/GetCompositionControllerTests.java @@ -0,0 +1,105 @@ +package org.onap.dcae.ci.api.tests.composition; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.text.WordUtils; +import org.assertj.core.api.SoftAssertions; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.utilities.DcaeUtil; +import org.onap.dcae.ci.report.Report; +import org.testng.annotations.Test; + +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; + +public class GetCompositionControllerTests extends DcaeRestBaseTest { + + private static final String VFCMT_NAME = "teSt.__.monitoring---TempLATE."; + + @Test + public void test_getComposition() throws Exception{ + Report.log(Status.INFO, "test_getComposition start"); + Vfcmt vfcmtWithArtifactUuid = createServiceAndVfiAndVfcmtAndAttach(); + String uuid = vfcmtWithArtifactUuid.getUuid(); + String lastUpdaterUserId = vfcmtWithArtifactUuid.getLastUpdaterUserId(); + Report.log(Status.INFO, "the created VFCMT uuid is:"+uuid+", going to save composition now"); + saveComposition(uuid, lastUpdaterUserId); + Report.log(Status.INFO, "Composition saved"); + + Report.log(Status.INFO, "Get Composition - execute"); + RestResponse response = DcaeRestClient.getComposition(uuid); + JSONObject resData = (JSONObject) JSONValue.parse(response.getResponse()); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(resData.get("successResponse").toString()).isNotEmpty(); + }); + } + + @Test + public void test_getCompositionNoArtifact() throws Exception{ + Report.log(Status.INFO, "test_getCompositionNoArtifact Get Composition - create vfcmt"); + + Vfcmt newVfcmt = createNewVfcmt(); + String uuid = newVfcmt.getUuid(); + + Report.log(Status.INFO, "Get Composition - execute"); + RestResponse response = DcaeRestClient.getComposition(uuid); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(204); + }); + } + + private void saveComposition(String uuid, String lastUpdaterUserId) throws Exception, IOException { + //generate cdump + String cdump = generateAndSaveCdump(uuid); + // save composition.yml + DcaeRestClient.saveComposition(uuid, lastUpdaterUserId, cdump); + } + + private Vfcmt createServiceAndVfiAndVfcmtAndAttach() throws Exception{ + Vfcmt newVfcmt = createNewVfcmt(); + + // create a service in sdc + Service newService = createServiceWithVFiAsSdcDesigner(); + + String serviceUuid = newService.getUuid(); + String vfiName = newService.getResources().get(0).getResourceInstanceName(); + String vfcmtId = newVfcmt.getUuid(); + + // attach VFCMT to vfi + RestResponse res = DcaeRestClient.attachVfiRef(vfcmtId, serviceUuid, vfiName); + + return newVfcmt; + } + + private Vfcmt createNewVfcmt() throws Exception { + String randomSuffix = WordUtils.capitalize(RandomStringUtils.randomAlphanumeric(4).toLowerCase()); + Vfcmt newVfcmt = createVfcmtInstance(randomSuffix); + return newVfcmt; + } + + private Vfcmt createVfcmtInstance(String randomSuffix) throws Exception{ + String newName = VFCMT_NAME + randomSuffix; + RestResponse res = DcaeRestClient.createVfcmt(newName,"description"); + assertThat(res.getStatusCode()).isEqualTo(200); + return gson.fromJson(res.getResponse(), Vfcmt.class); + } + private String generateAndSaveCdump(String vfcmtId) throws Exception{ + JsonArray snmpModelItemFromSdc = DcaeUtil.SdcElementsModelType.getSNMPModelItemFromSdc(); + JsonObject cdump = DcaeRestClient.generateCdumpInput(vfcmtId); + cdump.add("nodes", snmpModelItemFromSdc); + return cdump.toString(); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/composition/SaveAndSubmitCompositionFullFlowTest.java b/src/main/java/org/onap/dcae/ci/api/tests/composition/SaveAndSubmitCompositionFullFlowTest.java new file mode 100644 index 0000000..566a028 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/composition/SaveAndSubmitCompositionFullFlowTest.java @@ -0,0 +1,116 @@ +package org.onap.dcae.ci.api.tests.composition; + + +import com.aventstack.extentreports.Status; +import com.google.gson.reflect.TypeToken; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SaveAndSubmitCompositionFullFlowTest extends DcaeRestBaseTest { + + private Resource baseTemplate = null; + + + @BeforeClass + public void setup() { + try { + Report.log(Status.INFO, "running before class - find a base template"); + Resource[] resources = gson.fromJson(DcaeRestClient.getAllMonitoringTemplatesVfcmts().getResponse(), Resource[].class); + if (resources.length > 0){ + baseTemplate = resources[0]; + } + } catch (Exception e) { + Report.log(Status.ERROR, e); + } + } + + + @Test + public void saveAndSubmitCompositionSuccessTest() throws IOException { + + CreateVFCMTRequest request = new CreateVFCMTRequest(); + // If you crashed here (below) it is because your environment has no Base Monitoring Templates + request.setTemplateUuid(baseTemplate.getUuid()); + Service service = createServiceWithVFiAsSdcDesigner(); + request.setVfiName(service.getResources().get(0).getResourceInstanceName()); + request.setServiceUuid(service.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + RestResponse response = DcaeRestClient.createMc(gson.toJson(request)); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + CreateMcResponse mcResponse = gson.fromJson(response.getResponse(), CreateMcResponse.class); + Report.log(Status.INFO, "Vfcmt created successfully. About to update composition"); + String initialUuid = mcResponse.getVfcmt().getUuid(); + response = DcaeRestClient.saveComposition(request.getServiceUuid(), request.getVfiName(), initialUuid, gson.toJson(mcResponse.getCdump())); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + ResourceDetailed mc = gson.fromJson(response.getResponse(), ResourceDetailed.class); + // the save action should check the mc out then in - promoting the version + assertThat(mc.getLifecycleState()).isEqualTo(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name()); + assertThat(mc.getVersion()).isEqualTo("0.2"); + + Report.log(Status.INFO, "About to submit the composition"); + response = DcaeRestClient.submitComposition(request.getServiceUuid(), request.getVfiName(), mc.getUuid()); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + // the submit action should certify the mc. + Report.log(Status.INFO, "Save new composition version after submit"); + response = DcaeRestClient.saveComposition(request.getServiceUuid(), request.getVfiName(), initialUuid, gson.toJson(mcResponse.getCdump())); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + // the save action should promote the mc version to 1.1 and create a new reference to it - both references should be kept at this point + mc = gson.fromJson(response.getResponse(), ResourceDetailed.class); + assertThat(mc.getLifecycleState()).isEqualTo(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name()); + assertThat(mc.getVersion()).isEqualTo("1.1"); + + response = DcaeRestClient.getServiceExternalReferences(service.getUuid(), service.getVersion()); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + Report.log(Status.INFO, "Verify service vfi has references to both mc versions"); + Type typeToken = new TypeToken<Map<String, List<MonitoringComponent>>>(){}.getType(); + Map<String, List<MonitoringComponent>> monitoringComponents = gson.fromJson(response.getResponse(), typeToken); + assertThat(monitoringComponents.get("monitoringComponents").size()).isEqualTo(2); + Report.log(Status.INFO, "About to re-submit the composition"); + response = DcaeRestClient.submitComposition(request.getServiceUuid(), request.getVfiName(), mc.getUuid()); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + // a successful submission of the new version should result in the deletion of the previous reference + response = DcaeRestClient.getServiceExternalReferences(service.getUuid(), service.getVersion()); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + monitoringComponents = gson.fromJson(response.getResponse(), typeToken); + List<MonitoringComponent> mcList = monitoringComponents.get("monitoringComponents"); + assertThat(mcList.size()).isEqualTo(1); + assertThat(mcList.get(0).getUuid()).isEqualTo(mc.getUuid()); + + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/deploy_tool/DeployToolTest.java b/src/main/java/org/onap/dcae/ci/api/tests/deploy_tool/DeployToolTest.java new file mode 100644 index 0000000..46836f2 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/deploy_tool/DeployToolTest.java @@ -0,0 +1,19 @@ +package org.onap.dcae.ci.api.tests.deploy_tool; + + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import org.testng.annotations.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DeployToolTest extends DcaeRestBaseTest { + + @Test + public void verifyDeployToolVfcmtExist() throws Exception { + Vfcmt[] vfcmts = client.getAllBaseVfcmts(); + assertThat(vfcmts).isNotNull(); + assertThat(vfcmts.length).isGreaterThan(0); + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/ArrangeHelper.java b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/ArrangeHelper.java new file mode 100644 index 0000000..a3631f8 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/ArrangeHelper.java @@ -0,0 +1,68 @@ +package org.onap.dcae.ci.api.tests.lifeCycle; + +import static org.assertj.core.api.Assertions.fail; + +import org.onap.dcae.ci.utilities.DcaeEntityClient; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +public class ArrangeHelper { + + private DcaeEntityClient client; + + public ArrangeHelper(DcaeEntityClient client) { + this.client = client; + } + + /** + * Tries to arrange checkedin vfcmt. + * If unable to do so, fails test with arrange error message + * @param userId - lastUpdater of the returned vfcmt + * @return checkedin vfcmt + */ + public Vfcmt getCheckedinVfcmt(String userId) { + Vfcmt vfcmt = null; + try { + vfcmt = client.createCheckedinVfcmt(userId); + } catch (Exception err) { + fail("could not arrange test: ", err); + } + return vfcmt; + } + + /** + * Tries to arrange checkedin vfcmt. + * If unable to do so, fails test with arrange error message + * @return checkedin vfcmt + */ + public Vfcmt getCheckedinVfcmt() { + String userId = DcaeRestClient.getDefaultUserId(); + return getCheckedinVfcmt(userId); + } + + /** + * Tries to arrange checkedout vfcmt. + * If unable to do so, fails test with arrange error message + * @param userId - lastUpdater of the returned vfcmt + * @return checkedout vfcmt + */ + public Vfcmt getCheckedoutVfcmt(String userId) { + Vfcmt vfcmt = null; + try { + vfcmt = client.createCheckedoutVfcmt(userId); + } catch (Exception err) { + fail("could not arrange test: ", err); + } + return vfcmt; + } + + /** + * Tries to arrange checkedout vfcmt. + * If unable to do so, fails test with arrange error message + * @return checkedout vfcmt + */ + public Vfcmt getCheckedoutVfcmt() { + String userId = DcaeRestClient.getDefaultUserId(); + return getCheckedoutVfcmt(userId); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCertify.java b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCertify.java new file mode 100644 index 0000000..6fc6bbe --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCertify.java @@ -0,0 +1,34 @@ +package org.onap.dcae.ci.api.tests.lifeCycle; + + +import com.aventstack.extentreports.Status; +import org.assertj.core.api.SoftAssertions; + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import org.testng.annotations.Test; + +public class PutCertify extends DcaeRestBaseTest { + + private ArrangeHelper arrange = new ArrangeHelper(client); + + /* Positive */ + + @Test + public void certifyVfcmt_success() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedinVfcmt(); + // act + Report.log(Status.INFO, "Calling certify vfcmt with lastUpdater as user (designer role)"); + RestResponse response = DcaeRestClient.certifyVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + // assert + Vfcmt vfcmtAfterCheckin = gson.fromJson(response.getResponse(), Vfcmt.class); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).isEqualTo(200); + softly.assertThat(vfcmtAfterCheckin.getLifecycleState()).isEqualTo("CERTIFIED"); + }); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckin.java b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckin.java new file mode 100644 index 0000000..6866a0a --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckin.java @@ -0,0 +1,146 @@ +package org.onap.dcae.ci.api.tests.lifeCycle; + +import java.io.IOException; +import java.util.UUID; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; + +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.testng.annotations.*; +import static org.assertj.core.api.Assertions.*; + + +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import com.aventstack.extentreports.Status; + +public class PutCheckin extends DcaeRestBaseTest { + + private ArrangeHelper arrange = new ArrangeHelper(client); + + /* Positive */ + + @Test + public void checkedoutVfcmt_success() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(); + // act + Report.log(Status.INFO, "Checkin the vfcmt with it's lastUpdater user"); + RestResponse response = checkinVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + // assert + Vfcmt vfcmtAfterCheckin = gson.fromJson(response.getResponse(), Vfcmt.class); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).isEqualTo(200); + softly.assertThat(vfcmtAfterCheckin.getLifecycleState()).contains("CHECKIN"); + }); + } + + /* Negative */ + + @Test + public void alreadyCheckedinVfcmt_statusCode409() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedinVfcmt(); + // act + Report.log(Status.INFO, "Checkin the vfcmt <b>AGAIN</b> with it's lastUpdater user"); + RestResponse response = checkinVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + // assert + assertThat(response.getStatusCode()).isEqualTo(409); + } + + @Test + public void invalidVfcmtUuid_statusCode400() throws Exception { + // arrange + String userId = DcaeRestClient.getDefaultUserId(); + // act + Report.log(Status.INFO, "Checkin with an invalid-uuid as vfcmt-uuid"); + RestResponse response = checkinVfcmt("invalid-vfcmt-uuid", userId); + // assert + assertThat(response.getStatusCode()).isEqualTo(400); + } + + @Test + public void nonExistingUuid_statusCode409() throws Exception { + // arrange + String uuid = UUID.randomUUID().toString(); + String userId = DcaeRestClient.getDefaultUserId(); + // act + Report.log(Status.INFO, "Checkin with a non-existing vfcmt-uuid"); + RestResponse response = checkinVfcmt(uuid, userId); + // assert + assertThat(response.getStatusCode()).isEqualTo(409); + } + + @Test + public void nonExistingUser_statusCode403() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(); + // act + Report.log(Status.INFO, "Checkin with a non-existing user"); + RestResponse response = checkinVfcmt(vfcmt.getUuid(), "anonymus"); + // assert + assertThat(response.getStatusCode()).isEqualTo(403); + } + + @Test + public void notLastUser_statusCode403() throws Exception { + // arrange + String user1 = DcaeRestClient.getDefaultUserId(); + String user2 = DcaeRestClient.getDesigner2UserId(); + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(user1); + // act + Report.log(Status.INFO, "Checkin the vfcmt with different user: " + user2); + RestResponse response = checkinVfcmt(vfcmt.getUuid(), user2); + // assert + assertThat(response.getStatusCode()).isEqualTo(403); + } + + @Test + public void invalidAssetType_statusCode400() throws Exception { + // arrange + String assetType = "kengero"; + String userId = DcaeRestClient.getDefaultUserId(); + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(); + // act + Report.log(Status.INFO, "Checkin the vfcmt with invalid asset-type"); + RestResponse response = checkinGeneral(assetType, userId, vfcmt); + // assert + assertThat(response.getStatusCode()).isEqualTo(400); + } + + + /* Private Methods */ + + /** + * Performs checkin on a general vfcmt, use this in test action + * @param assetType + * @param userId + * @param vfcmt + * @return + * @throws IOException + */ + private RestResponse checkinGeneral(String assetType, String userId, Vfcmt vfcmt) throws IOException { + RestResponse response = DcaeRestClient.checkinGeneral(assetType, vfcmt.getUuid(), userId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + return response; + } + + /** + * Performs checkin on vfcmt, use this in test action + * @param vfcmtUuid + * @param userId + * @return + * @throws IOException + */ + private RestResponse checkinVfcmt(String vfcmtUuid, String userId) throws IOException { + RestResponse response = DcaeRestClient.checkinVfcmt(vfcmtUuid, userId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + return response; + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckout.java b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckout.java new file mode 100644 index 0000000..b8b7afc --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/lifeCycle/PutCheckout.java @@ -0,0 +1,148 @@ +package org.onap.dcae.ci.api.tests.lifeCycle; + +import java.io.IOException; +import java.util.UUID; + + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; + +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.testng.annotations.*; +import static org.assertj.core.api.Assertions.*; + +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; + +public class PutCheckout extends DcaeRestBaseTest { + + private ArrangeHelper arrange = new ArrangeHelper(client); + + /* Positive */ + + @Test + public void checkedinVfcmt_success() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedinVfcmt(); + // act + Report.log(Status.INFO, "Checkout the vfcmt with it's lastUpdater user"); + RestResponse response = checkoutVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + // assert + Vfcmt vfcmtAfterCheckout = gson.fromJson(response.getResponse(), Vfcmt.class); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).isEqualTo(200); + softly.assertThat(vfcmtAfterCheckout.getLifecycleState()).contains("CHECKOUT"); + }); + } + + @Test + public void notLastUser_success() throws Exception { + // arrange + String user1 = DcaeRestClient.getDefaultUserId(); + String user2 = DcaeRestClient.getDesigner2UserId(); + Vfcmt vfcmt = arrange.getCheckedinVfcmt(user1); + // act + Report.log(Status.INFO, "Checkout the vfcmt with different user: " + user2); + RestResponse response = checkoutVfcmt(vfcmt.getUuid(), user2); + // assert + Vfcmt vfcmtAfterCheckout = gson.fromJson(response.getResponse(), Vfcmt.class); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).isEqualTo(200); + softly.assertThat(vfcmtAfterCheckout.getLifecycleState()).contains("CHECKOUT"); + }); + } + + + /* Negative */ + + @Test + public void alreadyCheckedoutVfcmt_statusCode403() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(); + // act + Report.log(Status.INFO, "Checkout the vfcmt with it's lastUpdater user"); + RestResponse response = checkoutVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + // assert + assertThat(response.getStatusCode()).isEqualTo(403); + } + + @Test + public void invalidVfcmtUuid_statusCode400() throws Exception { + // arrange + String userId = DcaeRestClient.getDefaultUserId(); + // act + Report.log(Status.INFO, "Checkout with an invalid-uuid as vfcmt-uuid"); + RestResponse response = checkoutVfcmt("invalid-vfcmt-uuid", userId); + // assert + assertThat(response.getStatusCode()).isEqualTo(400); + } + + @Test + public void nonExistingUuid_statusCode409() throws Exception { + // arrange + String uuid = UUID.randomUUID().toString(); + String userId = DcaeRestClient.getDefaultUserId(); + // act + Report.log(Status.INFO, "Checkin with a non-existing vfcmt-uuid"); + RestResponse response = checkoutVfcmt(uuid, userId); + // assert + assertThat(response.getStatusCode()).isEqualTo(409); + } + + @Test + public void nonExistingUser_statusCode403() throws Exception { + // arrange + Vfcmt vfcmt = arrange.getCheckedinVfcmt(); + // act + Report.log(Status.INFO, "Checkin with a non-existing user"); + RestResponse response = checkoutVfcmt(vfcmt.getUuid(), "anonymus"); + // assert + assertThat(response.getStatusCode()).isEqualTo(403); + } + + @Test + public void invalidAssetType_statusCode400() throws Exception { + // arrange + String assetType = "kengero"; + String userId = DcaeRestClient.getDefaultUserId(); + Vfcmt vfcmt = arrange.getCheckedoutVfcmt(); + // act + Report.log(Status.INFO, "Checkout the vfcmt with invalid asset-type"); + RestResponse response = checkoutGeneral(assetType, userId, vfcmt); + // assert + assertThat(response.getStatusCode()).isEqualTo(400); + } + + + /* Private Methods */ + + /** + * Performs checkout on a general vfcmt/service and logs the response + * @param assetType + * @param userId + * @param vfcmt + * @return + * @throws IOException + */ + private RestResponse checkoutGeneral(String assetType, String userId, Vfcmt vfcmt) throws IOException { + RestResponse response = DcaeRestClient.checkinGeneral(assetType, vfcmt.getUuid(), userId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + return response; + } + + /** + * Performs checkout on vfcmt and logs the response + * @param vfcmtUuid + * @param userId + * @return + * @throws IOException + */ + private RestResponse checkoutVfcmt(String vfcmtUuid, String userId) throws IOException { + RestResponse response = DcaeRestClient.checkoutVfcmt(vfcmtUuid, userId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + return response; + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetDefinitionTest.java b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetDefinitionTest.java new file mode 100644 index 0000000..154d952 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetDefinitionTest.java @@ -0,0 +1,138 @@ +package org.onap.dcae.ci.api.tests.ruleEditor; + +import java.lang.reflect.Field; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; + +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.EventTypeDefinitionUI; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.EventTypesByVersionUI; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +public class GetDefinitionTest extends DcaeRestBaseTest { + + @DataProvider(name = "EventTypes") + public static Object[][] getVesVersions() { + Gson gson = new GsonBuilder().create(); + try { + Report.log(Status.INFO, "Requesting VES event types"); + RestResponse response = DcaeRestClient.getVesEventTypes(); + Report.logDebug("Response", response); + if (response.getStatusCode() != 200) { + throw new Exception(response.toString()); + } + EventTypesByVersionUI[] eventsByVersionList = gson.fromJson(response.getResponse(), EventTypesByVersionUI[].class); + + return Arrays.stream(eventsByVersionList) + .flatMap(version -> version.getEventTypes().stream() + .map( event -> new Object[] {version.getVersion(), event} ) + ).toArray(Object[][]::new); + + } catch (Exception err) { + Report.log(Status.ERROR, "Unable to get ves event types\nException: %s", err.toString()); + return new Object[][] {}; + } + } + + + /* Positive */ + + @Test(dataProvider = "EventTypes") + public void testParameterized(String version, String eventType) throws Exception { + // arrange + + Report.log(Status.INFO, "testParameterized. version="+version+", eventType="+eventType); + + Gson gsonStrict = new GsonBuilder() + .registerTypeAdapter(EventTypeDefinitionUI.class, new StrictJsonDeserializer<EventTypeDefinitionUI>()) + .create(); + + // act + RestResponse response = DcaeRestClient.getVesDataTypes(version, eventType); + Report.logDebug("Response", response); + // assert + + EventTypeDefinitionUI[] resBody = gson.fromJson(response.getResponse(), EventTypeDefinitionUI[].class); + List<EventTypeDefinitionUI> resBodyFlat = flatten(Arrays.asList(resBody)); + Report.logDebug("resBodyFlat", gsonStrict.toJson(resBodyFlat)); + + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + + softly.assertThat(resBodyFlat).extracting("name").as("name") + .doesNotContain(StringUtils.EMPTY) + .doesNotContainNull(); + + softly.assertThat(resBodyFlat).extracting("id").as("id") + .doesNotContain(StringUtils.EMPTY) + .doesNotContainNull(); + }); + } + + + /* Negative */ + + + + + /* Private Methods */ + + public class StrictJsonDeserializer<T> implements JsonDeserializer<T> { + private Gson gson = new Gson(); + + @Override + public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + Field[] declaredFields = Class.forName(typeOfT.getTypeName()).getDeclaredFields(); + Arrays.asList(declaredFields).stream() + .map(field -> field.getName()) + .forEach(fieldName -> { + if (json.getAsJsonObject().has(fieldName) == false) { + throw new JsonParseException(String.format("Missing field '%s'", fieldName)); + } + }); + } catch (SecurityException e) { + throw new JsonParseException("unable to parse", e); + } catch (ClassNotFoundException e) { + throw new JsonParseException("unable to parse", e); + } + return gson.fromJson(json, typeOfT); + } + + } + + + private List<EventTypeDefinitionUI> flatten(List<EventTypeDefinitionUI> events) { + List<EventTypeDefinitionUI> result = new ArrayList<EventTypeDefinitionUI>(); + events.stream().forEach(e -> { + List<EventTypeDefinitionUI> children = e.getChildren(); + result.add(e); // add this node + if (children != null) { + result.addAll(flatten(children)); // add child nodes recursively + } + }); + return result; + } + + /* Negative */ + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetListEventsAndVersionsTest.java b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetListEventsAndVersionsTest.java new file mode 100644 index 0000000..0764e34 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/GetListEventsAndVersionsTest.java @@ -0,0 +1,49 @@ +package org.onap.dcae.ci.api.tests.ruleEditor; + + +import org.apache.commons.collections4.SetUtils; +import org.apache.commons.lang3.StringUtils; +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; + +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.EventTypesByVersionUI; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; + +public class GetListEventsAndVersionsTest extends DcaeRestBaseTest { + + /* Positive */ + + @Test + public void test_successResponse() throws Exception { + // act + Report.log(Status.INFO, "test_successResponse: Requesting VES event types"); + RestResponse response = DcaeRestClient.getVesEventTypes(); + Report.logDebug("Response", response); + // assert + EventTypesByVersionUI[] resBody = gson.fromJson(response.getResponse(), EventTypesByVersionUI[].class); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + + softly.assertThat(resBody).as("response body").isNotEmpty(); + + softly.assertThat(resBody).extracting("version").as("version") + .doesNotContain(StringUtils.EMPTY) + .doesNotContainNull(); + + softly.assertThat(resBody).extracting("eventTypes").as("eventTypes list") + .doesNotContain(SetUtils.emptySet()) + .doesNotContainNull(); + softly.assertThat(resBody).flatExtracting("eventTypes").as("eventTypes list (flatten)") + .doesNotContainAnyElementsOf(EventTypesByVersionUI.DEFAULT_EVENTS) + .doesNotContain(StringUtils.EMPTY) + .doesNotContainNull(); + }); + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/RuleEditorControllerTest.java b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/RuleEditorControllerTest.java new file mode 100644 index 0000000..45de16a --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/ruleEditor/RuleEditorControllerTest.java @@ -0,0 +1,353 @@ +package org.onap.dcae.ci.api.tests.ruleEditor; + + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.entities.rule_editor.SaveRuleError; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.services.Artifact; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonObject; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.MappingRules; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.Rule; + +import org.testng.annotations.Test; +import org.assertj.core.api.SoftAssertions; + + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.Assert.fail; + +import java.util.List; + +public class RuleEditorControllerTest extends DcaeRestBaseTest { + + private String ruleRequestBody = + "{version:4.1,eventType:syslogFields,description:newRule,actions:[{from:{value:fromField,regex:\"\"},target:event.commonEventHeader.target,id:id,actionType:copy}," + + "{actionType:concat,from:{values:[{value:concat1},{value:_concat2}]},target:concatTargetField},{actionType:copy,from:{value:extractFromHere,regex:\"([^:]*):.*\"},target:regexTargetField}," + + "{actionType:\"Log Text\",logText:{text:\"some text\",level:WARN}},{actionType:CLear,from:{values:[{value:first_input},{value:second_input}]}}," + + "{actionType:map,from:{value:fromField},target:mapTargetField,map:{values:[{key:sourceVal1,value:targetVal1},{key:sourceVal2,value:targetVal2}],haveDefault:true,default:'\"\"'}}," + + "{actionType:\"Date Formatter\",id:98908,from:{value:\"${dateFormatterFrom}\"},target:dateFormatterTarget,dateFormatter:{toTimezone:UVW,fromTimezone:XYZ,fromFormat:inputFormat,toFormat:outputFormat}}," + + "{actionType:\"Log Event\",id:465456,logEvent:{title:\"some log title\"}},{actionType:\"Replace Text\",from:{value:fromField},replaceText:{find:findText,replace:replacement}}]," + + "condition:{left:\"${leftOperand}\",operator:contains,right:[rightOperand1,rightOperand2]}}"; + + @Test + public void saveNewMappingRulesArtifactSuccessTest() throws Exception { + Report.log(Status.INFO, "test start"); + Vfcmt vfcmt = createVfcmt(); + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", "n.1.map", "param1", ruleRequestBody); + JsonObject jsonRes = gson.fromJson(res.getResponse(), JsonObject.class); + assertThat(jsonRes.get("version").getAsString()).isEqualTo("4.1"); + assertThat(jsonRes.get("eventType").getAsString()).isEqualTo("syslogFields"); + assertThat(jsonRes.get("uid")).isNotNull(); + String expectedArtifactName = "map_n.1.map_param1_MappingRules.json"; + Artifact savedArtifact = fetchVfcmtArtifactMetadataByName(vfcmt.getUuid(), expectedArtifactName); + assertThat(savedArtifact).isNotNull(); + } + + @Test + public void translateSnmpMappingRuleWithAllActionTypesSuccessTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"%s\",\"class\":\"RunPhase\"}]},{\"phase\":\"%s\",\"filter\":{\"filters\":[{\"string\":\"${leftOperand}\",\"value\":\"rightOperand1\",\"class\":\"Contains\"}," + + "{\"string\":\"${leftOperand}\",\"value\":\"rightOperand2\",\"class\":\"Contains\"}],\"class\":\"Or\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.target\":\"fromField\",\"concatTargetField\":\"concat1_concat2\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"regexTargetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}," + + "{\"logLevel\":\"WARN\",\"logText\":\"some text\",\"class\":\"LogText\"},{\"fields\":[\"first_input\",\"second_input\"],\"class\":\"Clear\"}," + + "{\"map\":{\"sourceVal1\":\"targetVal1\",\"sourceVal2\":\"targetVal2\"},\"field\":\"fromField\",\"toField\":\"mapTargetField\",\"default\":\"\",\"class\":\"MapAlarmValues\"}," + + "{\"fromFormat\":\"inputFormat\",\"fromTz\":\"XYZ\",\"toField\":\"dateFormatterTarget\",\"toFormat\":\"outputFormat\",\"toTz\":\"UVW\",\"value\":\"${dateFormatterFrom}\",\"class\":\"DateFormatter\"}," + + "{\"title\":\"some log title\",\"class\":\"LogEvent\"},{\"field\":\"fromField\",\"find\":\"findText\",\"replace\":\"replacement\",\"class\":\"ReplaceText\"}]}," + + "{\"phase\":\"%s\",\"processors\":[{\"phase\":\"snmp_publish\",\"class\":\"RunPhase\"}]}]}"; + Vfcmt vfcmt = createVfcmt(); + String name = vfcmt.getName(); + saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + RestResponse res = DcaeRestClient.translateRules(vfcmt.getUuid(),"map", "map", "param1", "SNMP MSE"); + Report.log(Status.INFO, "translateRules response= "+res); + assertThat(res.getStatusCode()).isEqualTo(200); + assertThat(res.getResponse()).isEqualTo(String.format(expectedTranslation, name, name, name)); + } + + @Test + public void addNewRuleToExistingArtifact() throws Exception { + Vfcmt vfcmt = createVfcmt(); + String nid = "n.565663636.0"; + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", nid, "param1", ruleRequestBody); + Rule rule1 = gson.fromJson(res.getResponse(), Rule.class); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", nid, "param1", ruleRequestBody); + Report.log(Status.INFO, "saveRule response= "+res); + Rule rule2 = gson.fromJson(res.getResponse(), Rule.class); + RestResponse responseGetRules = DcaeRestClient.getRules(vfcmt.getUuid(),"map", nid, "param1"); + Report.log(Status.INFO, "getRules response= "+responseGetRules); + MappingRules rules = gson.fromJson(responseGetRules.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules="+responseGetRules.getResponse()); + assertThat(rules.getRules()).hasSize(2); + assertThat(rules.getRules().keySet()).containsOnly(rule1.getUid(), rule2.getUid()); + } + + @Test + public void editExistingRuleInArtifact() throws Exception{ + Vfcmt vfcmt = createVfcmt(); + String updated = "This is an update"; + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + Rule rule = gson.fromJson(res.getResponse(), Rule.class); + Report.log(Status.INFO, "save rule response=%s", res.getResponse()); + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules3 response= "+res); + MappingRules rules = gson.fromJson(res.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules1="+res.getResponse()); + assertThat(rules.getRules().get(rule.getUid()).getDescription()).isEqualTo("newRule"); + assertThat(rules.getRules().keySet()).containsOnly(rule.getUid()); + rule.setDescription(updated); + DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "param1", rule.toJson()); + Report.log(Status.INFO, "saveRule response= "+res); + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules2 response= "+res); + rules = gson.fromJson(res.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules2="+res.getResponse()); + assertThat(rules.getRules()).hasSize(1); + assertThat(rules.getRules().get(rule.getUid()).getDescription()).isEqualTo(updated); + } + + @Test + public void editRuleInArtifactNoSuchIdErrorTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6036\",\"text\":\"Error - Failed to save rule. Internal persistence error\",\"variables\":[],\"formattedErrorMessage\":\"Error - Failed to save rule. Internal persistence error\"}},\"notes\":\"\"}"; + Vfcmt vfcmt = createVfcmt(); + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + Rule rule = gson.fromJson(res.getResponse(), Rule.class); + Report.log(Status.INFO, "rule="+rule); + rule.setUid("NoSuchUid"); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "param1", rule.toJson()); + Report.log(Status.INFO, "saveRule response= "+res); + assertThat(res.getStatusCode()).isEqualTo(409); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + + @Test + public void getAllRules() throws Exception{ + Vfcmt vfcmt = createVfcmt(); + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + String uid1 = gson.fromJson(res.getResponse(), JsonObject.class).get("uid").getAsString(); + //save two more rules + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "param1", ruleRequestBody); + Report.log(Status.INFO, "saveRule1 response= "+res); + String uid2 = gson.fromJson(res.getResponse(), JsonObject.class).get("uid").getAsString(); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "param1", ruleRequestBody); + Report.log(Status.INFO, "saveRule2 response= "+res); + String uid3 = gson.fromJson(res.getResponse(), JsonObject.class).get("uid").getAsString(); + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules response= "+res); + JsonObject jsonRes = gson.fromJson(res.getResponse(), JsonObject.class); + Report.log(Status.INFO, "jsonRes="+jsonRes); + assertThat(jsonRes.get("schema")).isNotNull(); + MappingRules actualRules = gson.fromJson(res.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules="+res.getResponse()); + assertThat(actualRules.getRules()).hasSize(3); + assertThat(actualRules.getRules().keySet()).containsOnly(uid1, uid2, uid3); + } + + + @Test + public void deleteRuleSuccessTest() throws Exception{ + Vfcmt vfcmt = createVfcmt(); + //save first rule + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + String uid1 = gson.fromJson(res.getResponse(), JsonObject.class).get("uid").getAsString(); + // save second rule + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "param1", ruleRequestBody); + Report.log(Status.INFO, "saveRule response= "+res); + String uid2 = gson.fromJson(res.getResponse(), JsonObject.class).get("uid").getAsString(); + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules1 response= "+res); + MappingRules actualRules = gson.fromJson(res.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules1="+res.getResponse()); + // get all rules should return both + assertThat(actualRules.getRules()).hasSize(2); + assertThat(actualRules.getRules().keySet()).containsOnly(uid1, uid2); + // delete a rule + res = DcaeRestClient.deleteRule(vfcmt.getUuid(),"map", "map", "param1", uid2); + Report.log(Status.INFO, "deleteRule1 response= "+res); + assertThat(res.getStatusCode()).isEqualTo(200); + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules2 response= "+res); + actualRules = gson.fromJson(res.getResponse(), MappingRules.class); + Report.log(Status.INFO, "MappingRules2="+res.getResponse()); + // get rules should return one rule + assertThat(actualRules.getRules()).hasSize(1); + assertThat(actualRules.getRules().keySet()).containsOnly(uid1); + // delete the last rule - artifact should be deleted + res = DcaeRestClient.deleteRule(vfcmt.getUuid(),"map", "map", "param1", uid1); + Report.log(Status.INFO, "deleteRule2 response= "+res); + assertThat(res.getStatusCode()).isEqualTo(200); + String expectedArtifactName = "map_map_param1_MappingRules.json"; + Artifact savedArtifact = fetchVfcmtArtifactMetadataByName(vfcmt.getUuid(), expectedArtifactName); + Report.log(Status.INFO, "savedArtifact= "+savedArtifact); + assertThat(savedArtifact).isNull(); + // get rules should return empty + res = DcaeRestClient.getRules(vfcmt.getUuid(),"map", "map", "param1"); + Report.log(Status.INFO, "getRules3 response= "+res); + assertThat(res.getStatusCode()).isEqualTo(200); + assertThat(res.getResponse()).isEqualTo("{}"); + + } + + @Test + public void invalidJsonRuleFormatTest() throws Exception{ + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6035\",\"text\":\"Error - Rule format is invalid: %1.\",\"variables\":[\"java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $\"],\"formattedErrorMessage\":\"Error - Rule format is invalid: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $.\"}},\"notes\":\"\"}"; + RestResponse res = DcaeRestClient.saveRule("someId", "someName", "someNid", "someParam", "gibberish" ); + assertThat(res.getStatusCode()).isEqualTo(400); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + @Test + public void invalidActionTypeTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6035\",\"text\":\"Error - Rule format is invalid: %1.\",\"variables\":[\"Undefined action type: gibberish\"],\"formattedErrorMessage\":\"Error - Rule format is invalid: Undefined action type: gibberish.\"}},\"notes\":\"\"}"; + RestResponse res = DcaeRestClient.saveRule("someId", "someName", "someNid", "someParam", "{actions:[{actionType:gibberish}]}"); + assertThat(res.getStatusCode()).isEqualTo(400); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + @Test + public void conflictingUsersErrorTest() throws Exception { + Vfcmt vfcmt = createVfcmt(); + RestResponse res = DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), "{\"nid\":\"map\"}"); + assertThat(res.getStatusCode()).isEqualTo(200); + //check out by other user then try to save rule by current user + res = DcaeRestClient.checkoutVfcmt(vfcmt.getUuid(), DcaeRestClient.getDesigner2UserId()); + assertThat(res.getStatusCode()).isEqualTo(200); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "someParam", ruleRequestBody); + assertThat(res.getStatusCode()).isEqualTo(403); + } + + @Test + public void uploadArtifactSdcErrorTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6036\",\"text\":\"Error - Failed to save rule. Internal persistence error\",\"variables\":[],\"formattedErrorMessage\":\"Error - Failed to save rule. Internal persistence error\"}},\"notes\":\"Error: Invalid content.\"}"; + Vfcmt vfcmt = createVfcmt(); + RestResponse res = DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), "{\"nid\":\"map\"}"); + assertThat(res.getStatusCode()).isEqualTo(200); + // Generated artifact label would be invalid and should fail when submitted to SDC + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "map", "map", "()someParam", ruleRequestBody); + assertThat(res.getStatusCode()).isEqualTo(409); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + @Test + public void saveMappingRuleNoSuchNidErrorTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6114\",\"text\":\"DCAE component %1 not found in composition\",\"variables\":[\"noSuchComponent\"],\"formattedErrorMessage\":\"DCAE component noSuchComponent not found in composition\"}},\"notes\":\"\"}"; + Vfcmt vfcmt = createVfcmt(); + RestResponse res = DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), "{\"nid\":\"map\"}"); + assertThat(res.getStatusCode()).isEqualTo(200); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), "noSuchComponent", "noSuchComponent", "someParam", ruleRequestBody); + assertThat(res.getStatusCode()).isEqualTo(400); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + + @Test + public void deleteRuleNoSuchIdTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6115\",\"text\":\"Delete rule failed. Internal persistence error\",\"variables\":[],\"formattedErrorMessage\":\"Delete rule failed. Internal persistence error\"}},\"notes\":\"\"}"; + Vfcmt vfcmt = createVfcmt(); + //save rule + saveCompositionAndFirstRuleSuccess(vfcmt, "map", "map", "param1", ruleRequestBody); + RestResponse res = DcaeRestClient.deleteRule(vfcmt.getUuid(),"map", "map", "param1", "noSuchRuleId"); + Report.log(Status.INFO, "deleteRule response=%s", res); + assertThat(res.getStatusCode()).isEqualTo(409); + assertThat(res.getResponse()).isEqualTo(expectedError); + } + + // After first rule is saved the mappingRules.json artifact is available for get/delete/edit tests + private RestResponse saveCompositionAndFirstRuleSuccess(Vfcmt vfcmt, String dcaeCompName, String nid, String configParam, String body) throws Exception { + // generate and save a composition.yml + Report.log(Status.INFO, "saveCompositionAndFirstRuleSuccess start"); + RestResponse res = DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), String.format("{\"nid\":\"%s\"}", nid)); + Report.log(Status.INFO, "saveComposition response=%s", res); + assertThat(res.getStatusCode()).isEqualTo(200); + + res = DcaeRestClient.saveRule(vfcmt.getUuid(), dcaeCompName, nid, configParam, body); + Report.log(Status.INFO, "saveRule response=%s", res); + assertThat(res.getStatusCode()).isEqualTo(200); + return res; + } + + + @Test + public void saveMappingRuleNegativeTest_BadResponse() throws Exception { + // arrange + Report.log(Status.INFO, "Arrangeing test..."); + ObjectMapper mapper = new ObjectMapper(); + String badRuleRequestBody = "{\"version\":\"5.3\",\"eventType\":\"syslogFields\",\"uid\":\"\",\"description\":\"map rules\"," + + "\"actions\":[{actionType:\"Date Formatter\",from:{value:whatever}},{\"id\":\"22fdded0-c9eb-11e7-83c1-3592231134a4\",\"actionType\":\"map\",\"from\":{\"value\":\"AAA\",\"regex\":\"\",\"state\":\"closed\",\"values\":[{\"value\":\"\"},{\"value\":\"\"}]},\"target\":\"BBB\",\"map\":{\"values\":[{\"key\":\"foo\",\"value\":\"bar\"}],\"haveDefault\":true,\"default\":\"\"}},{\"id\":\"2d6fab00-c9eb-11e7-83c1-3592231134a4\",\"actionType\":\"map\",\"from\":{\"value\":\"\",\"regex\":\"\",\"state\":\"closed\",\"values\":[{\"value\":\"\"},{\"value\":\"\"}]},\"target\":\"DDD\",\"map\":{\"values\":[{\"key\":\"foo\",\"value\":\"bar\"}],\"haveDefault\":false,\"default\":\"\"}},{\"id\":\"60bff5a0-c9eb-11e7-83c1-3592231134a4\",\"actionType\":\"map\",\"from\":{\"value\":\"EEE\",\"regex\":\"\",\"state\":\"closed\",\"values\":[{\"value\":\"\"},{\"value\":\"\"}]},\"target\":\"\",\"map\":{\"values\":[{\"key\":\"foo\",\"value\":\"bar\"}],\"haveDefault\":false,\"default\":\"\"}},{\"id\":\"75ea0ce0-c9eb-11e7-83c1-3592231134a4\",\"actionType\":\"map\",\"from\":{\"value\":\"FFF\",\"regex\":\"\",\"state\":\"closed\",\"values\":[{\"value\":\"\"},{\"value\":\"\"}]},\"target\":\"GGG\",\"map\":{\"values\":[{\"key\":\"foo\",\"value\":\"bar\"},{\"key\":\"\",\"value\":\"\"}],\"haveDefault\":false,\"default\":\"\"}},{\"id\":\"75ea0ce0-c9eb-11e7-83c1-3592231134a4\",\"actionType\":\"map\",\"from\":{\"value\":\"FFF\",\"regex\":\"\",\"state\":\"closed\",\"values\":[{\"value\":\"\"},{\"value\":\"\"}]},\"target\":\"GGG\",\"map\":{\"values\":[{\"key\":\"foo\",\"value\":\"bar\"},{\"key\":\"foo\",\"value\":\"not bar\"}],\"haveDefault\":false,\"default\":\"\"}}],\"condition\":null}"; + Vfcmt vfcmt = createVfcmt(); + Report.log(Status.INFO, "Saving composition of a fake cdump..."); + RestResponse res = DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), "{\"nid\":\"map\"}"); + Report.logDebug("saveComposition response", res); + if (res.getStatusCode() != 200) { + fail("Unable to arrange test, save composition failed\n" + res.toString()); + } + // act + Report.log(Status.INFO, "Executing..."); + Report.logDebug("Request body", badRuleRequestBody); + RestResponse targetRes = DcaeRestClient.saveRule(vfcmt.getUuid(), "noSuchComponent", "map", "someParam", badRuleRequestBody); + Report.logDebug("saveRule response", targetRes); + // assert + Report.log(Status.INFO, "Asserting..."); + List<String> errors = mapper.readValue(targetRes.getResponse(), SaveRuleError.class).getFormattedErrors(); // parse response + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(targetRes.getStatusCode()).isEqualTo(400); + softly.assertThat(errors).containsExactlyInAnyOrder( + "Please fill the default value of map action to BBB", + "Please fill the from field of map action to DDD", + "Please fill the target field of map action to ", + "Please fill all key-value pairs of map action to GGG", + "Error: Duplication in map keys exists, please modify rule configuration", + "Please fill the target field of Date Formatter action to null", + "Please fill the to timezone field of Date Formatter action to null", + "Please fill the from timezone field of Date Formatter action to null", + "Please fill the from format field of Date Formatter action to null", + "Please fill the to format field of Date Formatter action to null" + ); + }); + } + + @Test + public void translateInvalidFlowTypeFailureTest() throws Exception { + String expectedError = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC6116\",\"text\":\"Translation failed. Reason: %s\",\"variables\":[\"%s\"],\"formattedErrorMessage\":\"Translation failed. Reason: %s\"}},\"notes\":\"\"}"; + RestResponse res = DcaeRestClient.translateRules("someId","map", "map", "param1", "noSuchFlowType"); + assertThat(res.getStatusCode()).isEqualTo(400); + assertThat(res.getResponse()).isEqualTo(String.format(expectedError, "%1", "Flow type noSuchFlowType not found", "Flow type noSuchFlowType not found")); + res = DcaeRestClient.translateRules("someId","map", "map", "param1", null); + assertThat(res.getStatusCode()).isEqualTo(400); + assertThat(res.getResponse()).isEqualTo(String.format(expectedError, "%1", "Flow type null not found", "Flow type null not found")); + } + + @Test + public void getExistingRuleTargetsTest() throws Exception { + String dcaeCompName = "theComponent"; + String nid = "theNid"; + String configParam1 = "ConfigParam1"; + String configParam2 = "ConfigParam2"; + final String UID = "uid"; + + Vfcmt vfcmt = createVfcmt(); + RestResponse res = saveCompositionAndFirstRuleSuccess(vfcmt, dcaeCompName, nid, configParam1, ruleRequestBody); + gson.fromJson(res.getResponse(), JsonObject.class).get(UID).getAsString(); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), dcaeCompName, nid, configParam2, ruleRequestBody); + Report.log(Status.INFO, "saveRule1 response= "+res); + gson.fromJson(res.getResponse(), JsonObject.class).get(UID).getAsString(); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), dcaeCompName, nid, configParam1, ruleRequestBody); + Report.log(Status.INFO, "saveRule2 response= "+res); + gson.fromJson(res.getResponse(), JsonObject.class).get(UID).getAsString(); + res = DcaeRestClient.saveRule(vfcmt.getUuid(), dcaeCompName, nid, configParam1, ruleRequestBody); + Report.log(Status.INFO, "saveRule3 response= "+res); + + res = DcaeRestClient.getExistingRuleTargets(vfcmt.getUuid(),dcaeCompName,nid); + if (res.getStatusCode() != 200) { + fail("Unable to arrange test, get existing rule targets test failed\n" + res.toString()); + } + String response = res.getResponse(); + assertThat(response.contains(configParam1)); + assertThat(response.contains(configParam2)); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/GetAttachment.java b/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/GetAttachment.java new file mode 100644 index 0000000..e9e4d27 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/GetAttachment.java @@ -0,0 +1,62 @@ +package org.onap.dcae.ci.api.tests.services.attachment; + +import static org.assertj.core.api.Assertions.*; + +import java.util.UUID; + +import org.assertj.core.api.SoftAssertions; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import org.testng.annotations.*; + +import com.aventstack.extentreports.Status; + +public class GetAttachment extends DcaeRestBaseTest { + + /* Positive */ + + @Test + public void testNewVfcmt_noAttachedService() throws Exception { + Report.log(Status.INFO, "testNewVfcmt_noAttachedService start"); + // arrange + Vfcmt vfcmt = client.createVfcmt(); + // act + RestResponse response = DcaeRestClient.getAttachedService(vfcmt.getUuid()); + // assert + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + JSONObject resData = (JSONObject) JSONValue.parse(response.getResponse()); + softly.assertThat(resData.get("successResponse")) + .as("successResponse") + .isEqualTo("No Artifacts"); + }); + } + + /* Negative */ + + @Test + public void testNonUuidVfcmt_responseStatus404() throws Exception { + // act + RestResponse response = DcaeRestClient.getAttachedService("I am not a uuid"); + // assert + assertThat(response.getStatusCode()).as("status code").isEqualTo(404); + } + + @Test + public void testNonExistingVfcmt_responseStatus404() throws Exception { + // arrange + String fakeUuid = UUID.randomUUID().toString(); + // act + RestResponse response = DcaeRestClient.getAttachedService(fakeUuid); + // assert + assertThat(response.getStatusCode()).as("status code").isEqualTo(404); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/PostAttachment.java b/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/PostAttachment.java new file mode 100644 index 0000000..e435ee2 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/attachment/PostAttachment.java @@ -0,0 +1,173 @@ +package org.onap.dcae.ci.api.tests.services.attachment; + +import static org.assertj.core.api.Assertions.*; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.entities.composition.services.Vfi; +import org.onap.dcae.ci.entities.sdc.SdcResource; +import org.onap.dcae.ci.entities.sdc.SdcService; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.SdcInternalApiClient; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import org.testng.annotations.*; + +import java.util.UUID; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + +import com.aventstack.extentreports.Status; + +public class PostAttachment extends DcaeRestBaseTest { + + /* Positive */ + + @Test + public void vfcmtWithVfi_responseStatusOk() throws Exception { + // arrange + Vfcmt vfcmt; + Vfi vfi; + try { + vfcmt = client.createCheckedinVfcmt(); + vfi = arrangeVfi(); + } catch (Exception err) { + throw new Exception("Could not arrange test", err); + } + // act + Report.log(Status.INFO, "Attaching vfcmt [%s] to vfi [%s]", vfcmt.getUuid(), vfi.getName()); + RestResponse response = DcaeRestClient.attachVfiRef(vfcmt.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + Report.logDebug("Response:", response); + // assert + JSONObject resData = (JSONObject) JSONValue.parse(response.getResponse()); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(resData.get("successResponse")) + .as("successResponse") + .isEqualTo("Artifact updated"); + }); + } + + + @Test + public void vfcmtAlreadyAttached_responseStatusOk() throws Exception { + // arrange + Vfcmt vfcmt; + Vfi vfi; + try { + vfcmt = client.createCheckedinVfcmt(); + Report.log(Status.INFO, "Arranging first attachment"); + arrangeAttachmentToNewVfi(vfcmt); + vfi = arrangeVfi(); + } catch (Exception err) { + throw new Exception("Could not arrange test", err); + } + // act + Report.log(Status.INFO, "Updating attachment of vfcmt [%s] to a new vfi [%s]", vfcmt.getUuid(), vfi.getName()); + RestResponse response = DcaeRestClient.attachVfiRef(vfcmt.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + Report.logDebug("Response:", response); + // assert + JSONObject resData = (JSONObject) JSONValue.parse(response.getResponse()); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + softly.assertThat(resData.get("successResponse")) + .as("successResponse") + .isEqualTo("Artifact updated"); + }); + } + + + /* Negative */ + + + @Test + public void vfWithVfi_statusCode400() throws Exception { + // arrange + SdcResource vf; + Vfi vfi; + try { + Report.log(Status.INFO, "Create vf"); + vf = SdcInternalApiClient.createVf(); + vfi = arrangeVfi(); + } catch (Exception err) { + throw new Exception("Could not arrange test", err); + } + // act + Report.log(Status.INFO, "Attaching vf [%s] to vfi [%s]", vf.getUuid(), vfi.getName()); + RestResponse response = DcaeRestClient.attachVfiRef(vf.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + Report.logDebug("Response:", response); + // assert + assertThat(response.getStatusCode()).as("status code").isEqualTo(400); + } + + + @Test + public void vfcmtWithFakeServiceAndFakeVfi_statusCode404() throws Exception { + // arrange + Vfcmt vfcmt; + String fakeServiceUuid = UUID.randomUUID().toString(); + String fakeVfiName = "fakeVfi"; + try { + vfcmt = client.createCheckedinVfcmt(); + fakeServiceUuid = UUID.randomUUID().toString(); + fakeVfiName = "fakeVfi"; + } catch (Exception err) { + throw new Exception("Could not arrange test", err); + } + // act + Report.log(Status.INFO, "Attaching real vfcmt [%s] to fake service [%s] (random uuid) and fake vfi [%s]", vfcmt.getUuid(), fakeServiceUuid, fakeVfiName); + RestResponse response = DcaeRestClient.attachVfiRef(vfcmt.getUuid(), fakeServiceUuid, fakeVfiName); + Report.logDebug("Response:", response); + // assert + assertThat(response.getStatusCode()).as("status code").isEqualTo(404); + } + + + @Test + public void vfcmtWithFakeVfi_statusCode404() throws Exception { + // arrange + Vfcmt vfcmt; + Vfi vfi; + try { + vfcmt = client.createCheckedinVfcmt(); + Report.log(Status.INFO, "Create service"); + SdcService service = SdcInternalApiClient.createService(); + vfi = new Vfi("fakeVfi", service); + } catch (Exception err) { + throw new Exception("Could not arrange test", err); + } + // act + Report.log(Status.INFO, "Attaching vfcmt [%s] to real service [%s] and fake vfi [%s]", vfcmt.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + RestResponse response = DcaeRestClient.attachVfiRef(vfcmt.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + Report.logDebug("Response:", response); + // assert + assertThat(response.getStatusCode()).as("status code").isEqualTo(404); + } + + + /* Private Methods */ + + private Vfi arrangeVfi() throws Exception { + Report.log(Status.INFO, "Create service"); + SdcService service = SdcInternalApiClient.createService(); + Report.log(Status.INFO, "Create vf"); + SdcResource vf = SdcInternalApiClient.createVf(); + Report.log(Status.INFO, "Checkin vf"); + vf = SdcInternalApiClient.checkinVf(vf); + Report.log(Status.INFO, "Create vfi from (service [%s] + vf [%s])", service.getUuid(), vf.getUuid()); + return SdcInternalApiClient.createVfi(service, vf); + } + + + private void arrangeAttachmentToNewVfi(Vfcmt vfcmt) throws Exception { + Vfi vfi = arrangeVfi(); + Report.log(Status.INFO, "Attaching vfcmt [%s] to vfi [%s]", vfcmt.getUuid(), vfi.getName()); + RestResponse response = DcaeRestClient.attachVfiRef(vfcmt.getUuid(), vfi.getContainer().getUuid(), vfi.getName()); + Report.logDebug("Response:", response); + if (response.getStatusCode() != 200) { + throw new Exception("Failed to attach vfcmt to vfi\nResponse: " + response.toString()); + } + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstanceNagative.java b/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstanceNagative.java new file mode 100644 index 0000000..8e72204 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstanceNagative.java @@ -0,0 +1,25 @@ +package org.onap.dcae.ci.api.tests.services.instance; + + +import com.aventstack.extentreports.Status; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; + +import org.onap.dcae.ci.report.Report; +import org.testng.annotations.Test; + +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetServiceInstanceNagative extends DcaeRestBaseTest { + + @Test + public void test_invalidServiceID() throws IOException{ + Report.log(Status.INFO, "Send invalid service Instance"); + RestResponse response = DcaeRestClient.getServicesInstance("123456789"); + Report.log(Status.INFO, "Verifying response status is 404"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(404); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstancePositive.java b/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstancePositive.java new file mode 100644 index 0000000..b22e2f7 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/instance/GetServiceInstancePositive.java @@ -0,0 +1,121 @@ +package org.onap.dcae.ci.api.tests.services.instance; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.Arrays; +import java.util.List; +import java.util.function.Predicate; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.onap.sdc.dcae.composition.restmodels.sdc.ServiceDetailed; +import org.onap.sdc.dcae.composition.services.Resource; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService; +import org.springframework.util.CollectionUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +public class GetServiceInstancePositive extends DcaeRestBaseTest { + + private RestResponse response; + + @BeforeClass + public void executeApiCall() throws Exception { + // arrange + DcaeMinimizedService service = arrangeService(); + try { + // act + Report.log(Status.INFO, "Get all VFIs for service [" + service.getUuid() + "]"); + response = DcaeRestClient.getServicesInstance(service.getUuid()); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } catch (Exception err) { + Report.log(Status.FAIL, "Unable to execute api call: " + err.toString()); + err.printStackTrace(); + } + } + + private DcaeMinimizedService arrangeService() throws Exception { + DcaeMinimizedService service = null; + try { + Predicate<DcaeMinimizedService> hasVfi = p -> !CollectionUtils.isEmpty(getService(p.getUuid()).getResources()); + Vfcmt vfcmt = client.createCheckedoutVfcmt(); + Report.log(Status.INFO, "Created vfcmt [" + vfcmt.getUuid() + "]"); + Report.log(Status.INFO, "Get all services for vfcmt [" + vfcmt.getUuid() + "]"); + RestResponse responseServices = DcaeRestClient.getServices(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(responseServices)); + DcaeMinimizedService[] servicesList = gson.fromJson(responseServices.getResponse(), DcaeMinimizedService[].class); + // TODO: create a service instead of picking a random one + // find a service with a vfi + service = Arrays.stream(servicesList).filter(hasVfi).findAny().orElse(null); + } catch (Exception err) { + Report.log(Status.ERROR, "Could not arrange test: " + err.toString()); + } + return service; + } + + private ServiceDetailed getService(String serviceId) { + ServiceDetailed service = null; + try { + service = gson.fromJson(DcaeRestClient.getServicesInstance(serviceId).getResponse(), ServiceDetailed.class); + } catch (Exception e) { + Report.log(Status.ERROR, "Could not arrange test: " + e.toString()); + } + return service; + } + + @Test + public void test_responseStatusOk() throws IOException{ + // assert + Report.log(Status.INFO, "Verifing response status is 200"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + } + + @Test + public void test_atLeastOneOrMoreResources() throws IOException{ + // assert + Report.log(Status.INFO, "Parsing response to a one service instance"); + List<Resource> resourceList = getResourceListFromJsonResponse(); + Report.log(Status.INFO, "validating parsed response structure"); + assertThat(resourceList).size().isGreaterThanOrEqualTo(1); // TODO: create a VFI for the service instead of picking a random one + } + + @Test + public void test_responseIsValidStructure() throws IOException{ + // assert + Report.log(Status.INFO, "Parsing response to a one service instance"); + + List<Resource> resourceList = getResourceListFromJsonResponse(); + + Report.log(Status.INFO, "validating parsed response structure"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(resourceList.get(0).getResourceInstanceName()).isNotEmpty(); + softly.assertThat(resourceList.get(0).getResourceInvariantUUID()).isNotEmpty(); + }); + } + + + /*** private method ***/ + private List<Resource> getResourceListFromJsonResponse() { + JsonParser jsonParser = new JsonParser(); + JsonObject responseJson = (JsonObject)jsonParser.parse(response.getResponse()); + JsonArray resources = responseJson.getAsJsonArray("resources"); + Type listType = new TypeToken<List<Resource>>(){}.getType(); + List<Resource> resourceList = gson.fromJson(resources, listType); + return resourceList; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesNagative.java b/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesNagative.java new file mode 100644 index 0000000..be7d651 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesNagative.java @@ -0,0 +1,47 @@ +package org.onap.dcae.ci.api.tests.services.list; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.Assert.fail; + +import java.io.IOException; + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.testng.annotations.Test; + +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import com.aventstack.extentreports.Status; + +public class GetAllServicesNagative extends DcaeRestBaseTest { + + @Test + public void userNotLastUpdater_statusCode403() throws Exception{ + // arrange + String user1 = DcaeRestClient.getDefaultUserId(); + String user2 = DcaeRestClient.getDesigner2UserId(); + Vfcmt vfcmt = null; + try { + vfcmt = client.createCheckedoutVfcmt(user1); + } catch (Exception err) { + fail("Unable to arrange test", err); + } + // act + Report.log(Status.INFO, "GetServices for user that is not the vfcmt last-updater"); + RestResponse response = getServices(vfcmt.getUuid(), user2); + // assert + assertThat(response.getStatusCode()).as("response status").isEqualTo(403); + } + + + /* Private Methods */ + + private RestResponse getServices(String uuid, String user2) throws IOException { + RestResponse response = DcaeRestClient.getServices(uuid, user2); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + return response; + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesPositive.java b/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesPositive.java new file mode 100644 index 0000000..b8b947f --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/services/list/GetAllServicesPositive.java @@ -0,0 +1,72 @@ +package org.onap.dcae.ci.api.tests.services.list; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.List; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; + +import org.onap.sdc.dcae.composition.restmodels.sdc.Service; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; +import com.google.gson.reflect.TypeToken; + +public class GetAllServicesPositive extends DcaeRestBaseTest { + + private RestResponse response; + + @BeforeClass + public void executeApiCall() throws Exception { + Report.log(Status.INFO, "@BeforeClass --> executeApiCall"); + Vfcmt component = client.createCheckedoutVfcmt(); + String uuid = component.getUuid(); + String userIdLastUpdaterUserId = component.getLastUpdaterUserId(); + try { + // act + Report.log(Status.INFO, "Get all services"); + response = DcaeRestClient.getServices(uuid, userIdLastUpdaterUserId); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } catch (Exception err) { + Report.log(Status.ERROR, err); + err.printStackTrace(); + } + } + + @Test + public void test_responseStatusOk() throws IOException{ + // assert + Report.log(Status.INFO, "Verifing response status is 200"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + } + + @Test + public void test_responseIsValidStructure() throws IOException{ + // assert + Report.log(Status.INFO, "Parsing response to a List of Services"); + Type listType = new TypeToken<List<Service>>(){}.getType(); + List<Service> servicesList = gson.fromJson(response.getResponse(), listType); + Service service = servicesList.get(0); + + Report.log(Status.INFO, "validating parsed response structure"); + + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(service.getInvariantUUID()).isNotEmpty(); + softly.assertThat(service.getLastUpdaterUserId()).isNotEmpty(); + softly.assertThat(service.getName()).isNotEmpty(); + softly.assertThat(service.getUuid()).isNotEmpty(); + softly.assertThat(service.getLifecycleState()).isNotEmpty(); + softly.assertThat(service.getVersion()).isNotEmpty(); + }); + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateMonitoringComponent.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateMonitoringComponent.java new file mode 100644 index 0000000..1dc27d6 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateMonitoringComponent.java @@ -0,0 +1,253 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + + +import com.aventstack.extentreports.Status; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.ImportVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.MessageResponse; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CreateMonitoringComponent extends DcaeRestBaseTest { + + private RestResponse response; + private Resource res = null; + + + @BeforeClass + public void executeApiCall() { + // arrange + try { + // act + Report.log(Status.INFO, "Creating vfcmt"); + RestResponse clientResponse = DcaeRestClient.getAllMonitoringTemplatesVfcmts(); + Resource[] resources = gson.fromJson(clientResponse.getResponse(),Resource[].class); + if (resources.length > 0){ + res = resources[0]; + } + } catch (Exception err) { + Report.log(Status.ERROR, err); + } + } + + @Test + public void testCreateMonitoringComponentSuccess() throws IOException { + + Service service; + + try { + service = createServiceWithVFiAsSdcDesigner(); + } catch (Exception e) { + Report.log(Status.ERROR, e); + return; + } + + CreateVFCMTRequest request = new CreateVFCMTRequest(); + // If you crashed here (below) it is because your environment has no Base Monitoring Templates + request.setTemplateUuid(res.getUuid()); + request.setVfiName(service.getResources().get(0).getResourceInstanceName()); + request.setServiceUuid(service.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + response = DcaeRestClient.createMc(gson.toJson(request)); + + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + CreateMcResponse mcResponse = gson.fromJson(response.getResponse(),CreateMcResponse.class); + + String vfUuid = mcResponse.getVfcmt().getUuid(); + String vfCdump = gson.toJson(mcResponse.getCdump()); + assertThat(vfCdump.contains(vfUuid)).isTrue(); + + RestResponse r = DcaeRestClient.getAttachedService(vfUuid); + assertThat(r.getResponse().contains(service.getUuid())).isTrue(); + + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } + + @Test + public void testCreateMonitoringComponentBadUser() throws IOException { + + String fakeUserId = "anonymous"; + CreateVFCMTRequest request = new CreateVFCMTRequest(); + // If you crashed here (below) it is because your environment has no Base Monitoring Templates + request.setTemplateUuid(res.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + response = DcaeRestClient.createMc(gson.toJson(request),fakeUserId); + + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + // assert + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(403); + } + + @Test + public void testImportMonitoringComponentBothFlagsFalseSuccess() throws Exception { + + Service service; + + try { + service = createServiceWithVFiAsSdcDesigner(); + } catch (Exception e) { + Report.log(Status.ERROR, e); + return; + } + + String vfiName = service.getResources().get(0).getResourceInstanceName(); + Vfcmt vfcmt = prepareMockVfcmtForImport(); + ImportVFCMTRequest request = new ImportVFCMTRequest(); + request.setTemplateUuid(vfcmt.getUuid()); + request.setVfiName(vfiName); + request.setServiceUuid(service.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + response = DcaeRestClient.importMc(gson.toJson(request)); + + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + // the service vfi should now have an external reference record to the vfcmt + response = DcaeRestClient.getServiceExternalReferences(service.getUuid(), service.getVersion()); + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + Map<String, List<Map>> refs = gson.fromJson(response.getResponse(), Map.class); + assertThat(vfcmt.getUuid().equals(refs.get("monitoringComponents").get(0).get("uuid"))).isTrue(); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } + + @Test + public void testImportMonitoringComponentCloneFalseUpdateFlowTypeTrueSuccess() throws Exception { + + Service service; + + try { + service = createServiceWithVFiAsSdcDesigner(); + } catch (Exception e) { + Report.log(Status.ERROR, e); + return; + } + + String vfiName = service.getResources().get(0).getResourceInstanceName(); + Vfcmt vfcmt = prepareMockVfcmtForImport(); + ImportVFCMTRequest request = new ImportVFCMTRequest(); + request.setUpdateFlowType(true); + request.setTemplateUuid(vfcmt.getUuid()); + request.setVfiName(vfiName); + request.setServiceUuid(service.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + response = DcaeRestClient.importMc(gson.toJson(request)); + + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + // TODO update to one GET call after editMC is implemented + // assert that the vfcmt was updated as expected (version, owner, lifecycle) + response = DcaeRestClient.getResourceDetails(vfcmt.getUuid()); + ResourceDetailed updatedMC = gson.fromJson(response.getResponse(), ResourceDetailed.class); + assertThat(updatedMC.getVersion()).isEqualTo("0.2"); + assertThat(updatedMC.getLastUpdaterUserId()).isEqualTo(DcaeRestClient.getDefaultUserId()); + assertThat(updatedMC.getLifecycleState()).isEqualTo(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name()); + // assert that the updated cdump includes 'flowType' + + response = DcaeRestClient.getComposition(vfcmt.getUuid()); + String cdump = gson.fromJson(response.getResponse(), MessageResponse.class).getSuccessResponse(); + assertThat(cdump).isEqualTo("{\"flowType\":\"flowType_xxx\",\"cid\":\"1234567\"}"); + Report.log(Status.DEBUG, "Response updated mock cdump: " + cdump); + } + + @Test + public void testImportMonitoringComponentBothFlagsTrueSuccess() throws Exception { + + Service service; + + try { + service = createServiceWithVFiAsSdcDesigner(); + } catch (Exception e) { + Report.log(Status.ERROR, e); + return; + } + + String vfiName = service.getResources().get(0).getResourceInstanceName(); + Vfcmt vfcmt = prepareMockVfcmtForImport(); + ImportVFCMTRequest request = new ImportVFCMTRequest(); + request.setUpdateFlowType(true); + request.setCloneVFCMT(true); + request.setTemplateUuid(vfcmt.getUuid()); + request.setVfiName(vfiName); + request.setServiceUuid(service.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + + response = DcaeRestClient.importMc(gson.toJson(request)); + + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(200); + + // assert that the vfcmt was cloned, the flowType updated and the reference artifact created + CreateMcResponse mcResponse = gson.fromJson(response.getResponse(),CreateMcResponse.class); + + assertThat(mcResponse.getVfcmt().getFlowType()).isEqualTo("flowType_xxx"); + // check the reference artifact + response = DcaeRestClient.getAttachedService(mcResponse.getVfcmt().getUuid()); + String ref = gson.fromJson(response.getResponse(), MessageResponse.class).getSuccessResponse(); + assertThat(ref).isEqualTo(service.getUuid()+"/resources/"+vfiName); + + Report.log(Status.DEBUG, "Response cloned Monitoring component: " + mcResponse); + } + + @Test + public void testImportMonitoringComponentServiceNotFoundFailure() throws Exception { + + Vfcmt vfcmt = prepareMockVfcmtForImport(); + ImportVFCMTRequest request = new ImportVFCMTRequest(); + request.setTemplateUuid(vfcmt.getUuid()); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + response = DcaeRestClient.importMc(gson.toJson(request)); + + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(404); + + Report.log(Status.DEBUG, "Error response: " + response.getResponse()); + // assert vfcmt version was not increased + response = DcaeRestClient.getResourceDetails(vfcmt.getUuid()); + vfcmt = gson.fromJson(response.getResponse(), Vfcmt.class); + assertThat(vfcmt.getVersion()).isEqualTo("0.1"); + } + + + private Vfcmt prepareMockVfcmtForImport() throws IOException { + RestResponse createResponse = DcaeRestClient.createVfcmt(StringUtils.randomString("CI-", 20), "description", DcaeRestClient.getDesigner2UserId()); + Vfcmt vfcmt = gson.fromJson(createResponse.getResponse(), Vfcmt.class); + // create a composition artifact + DcaeRestClient.saveComposition(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId(), "{\"cid\":\"1234567\"}"); + return vfcmt; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateVfcmt.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateVfcmt.java new file mode 100644 index 0000000..6ca6053 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/CreateVfcmt.java @@ -0,0 +1,126 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + +import static org.assertj.core.api.Assertions.*; + +import java.io.IOException; + +import org.assertj.core.api.SoftAssertions; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.utilities.DcaeTestConstants; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.testng.annotations.*; + +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; + +public class CreateVfcmt extends DcaeRestBaseTest { + + private Vfcmt input; + private RestResponse response; + + @BeforeClass + public void executeApiCall() { + // arrange + input = new Vfcmt(); + input.setName(StringUtils.randomString("CI-", 20)); + input.setDescription(StringUtils.randomString("", 10)); + try { + // act + Report.log(Status.INFO, "Creating vfcmt"); + response = DcaeRestClient.createVfcmt(input.getName(), input.getDescription()); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } catch (Exception err) { + Report.log(Status.ERROR, err); + } + } + + /* Positive tests */ + + @Test + public void test_responseStatusOk() throws IOException { + // assert + Report.log(Status.INFO, "Verifing response status is 200"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + } + + @Test + public void test_responseIsValidStructure() throws IOException { + // assert + Report.log(Status.INFO, "Parsing response to a VFCMT"); + Vfcmt createdVfcmt = gson.fromJson(response.getResponse(), Vfcmt.class); + Report.log(Status.INFO, "validating parsed response structure"); + SoftAssertions.assertSoftly(softly -> { + softly.assertThat(createdVfcmt.getCategory()).isEqualTo("Template"); + softly.assertThat(createdVfcmt.getInvariantUUID()).isNotEmpty(); + softly.assertThat(createdVfcmt.getUuid()).isNotEmpty(); + softly.assertThat(createdVfcmt.getLastUpdaterUserId()).isEqualTo(DcaeRestClient.getDefaultUserId()); + softly.assertThat(createdVfcmt.getLifecycleState()).isEqualTo(DcaeTestConstants.Sdc.State.NOT_CERTIFIED_CHECKOUT); + softly.assertThat(createdVfcmt.getName()).isEqualTo(input.getName()); + softly.assertThat(createdVfcmt.getDescription()).isEqualTo(input.getDescription()); + softly.assertThat(createdVfcmt.getResourceType()).isEqualTo("VFCMT"); + softly.assertThat(createdVfcmt.getSubCategory()).isEqualTo("Monitoring Template"); + softly.assertThat(createdVfcmt.getVersion()).isEqualTo("0.1"); + }); + } + + /* Negative tests */ + + + + @Test + public void testWithNonExistingUser_status403() throws IOException { + // arrange + String fakeUserId = "anonymous"; + String name = StringUtils.randomString("CI-", 20); + String description = StringUtils.randomString("", 10); + // act + Report.log(Status.INFO, "Creating vfcmt with fake user"); + RestResponse res = DcaeRestClient.createVfcmt(name, description, fakeUserId); + Report.log(Status.DEBUG, "response: " + StringUtils.truncate(res)); + // assert + assertThat(res.getStatusCode()) + .as("status code") + .isEqualTo(403); + } + + @Test + public void testCreateTwoVfcmtsWithSameName_status409() throws IOException { + // arrange + String name = StringUtils.randomString("CI-", 20); + Report.log(Status.INFO, "Creating first vfcmt with name '" + name + "'"); + RestResponse response1 = DcaeRestClient.createVfcmt(name, StringUtils.randomString("", 10)); + Report.log(Status.DEBUG, "First Response: " + StringUtils.truncate(response1)); + if (response1.getStatusCode() != 200) { + fail("unable to arrange test - could not create the first vfcmt"); + } + // act + Report.log(Status.INFO, "Creating second vfcmt with same name '" + name + "'"); + RestResponse response2 = DcaeRestClient.createVfcmt(name, StringUtils.randomString("", 10)); + Report.log(Status.DEBUG, "Second response: " + StringUtils.truncate(response2)); + // assert + assertThat(response2.getStatusCode()) + .as("second status code") + .isEqualTo(409); + } + + @Test + public void testWithNonDesignerRole_status403() throws IOException { + // arrange + String testerId = DcaeRestClient.getDefaultTesterId(); + String name = StringUtils.randomString("CI-", 20); + String description = StringUtils.randomString("", 10); + // act + Report.log(Status.INFO, "Creating vfcmt with role tester"); + RestResponse response = DcaeRestClient.createVfcmt(name, description, testerId); + Report.log(Status.DEBUG, "response: " + StringUtils.truncate(response)); + // assert + assertThat(response.getStatusCode()) + .as("status code") + .isEqualTo(403); + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllMonitoringTemplateVfcmts.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllMonitoringTemplateVfcmts.java new file mode 100644 index 0000000..4a9a952 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllMonitoringTemplateVfcmts.java @@ -0,0 +1,61 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + +import com.aventstack.extentreports.Status; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetAllMonitoringTemplateVfcmts extends DcaeRestBaseTest { + + private RestResponse response; + private static final String BASE_MONITORING_TEMPLATE = "Base Monitoring Template"; + + @BeforeClass + public void executeApiCall() { + try { + // act + Report.log(Status.INFO, "Fetching all monitoring templates vfcmt resources"); + response = DcaeRestClient.getAllMonitoringTemplatesVfcmts(); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } catch (Exception err) { + Report.log(Status.ERROR, err); + } + } + + @Test + public void testResponseStatusOk() { + // assert + Report.log(Status.INFO, "Verifying response status is 200"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + } + + @Test + public void testResponseBodyIsListOfVfcmtsOnly() { + // assert + Report.log(Status.INFO, "Parsing response to a list of monitoring template VFCMTs"); + Vfcmt[] vfcmtList = gson.fromJson(response.getResponse(), Vfcmt[].class); + + Report.log(Status.INFO, "Verifying we got items"); + assertThat(vfcmtList).isNotEmpty(); + + Report.log(Status.INFO, "Verifying all items of the parsed response are VFCMTs"); + assertThat(vfcmtList) + .as("response data") + .extracting("resourceType") + .containsOnly("VFCMT"); + + Report.log(Status.INFO, "Verifying that all items of the parsed response are monitoring template VFCMTs"); + assertThat(vfcmtList) + .as("response data") + .extracting("subCategory") + .containsOnly(BASE_MONITORING_TEMPLATE); + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllVfcmts.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllVfcmts.java new file mode 100644 index 0000000..65e3f91 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetAllVfcmts.java @@ -0,0 +1,55 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + +import static org.assertj.core.api.Assertions.*; + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.testng.annotations.*; + + +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +import com.aventstack.extentreports.Status; + +public class GetAllVfcmts extends DcaeRestBaseTest { + + private RestResponse response; + + @BeforeClass + public void executeApiCall() { + try { + // act + Report.log(Status.INFO, "Fetching all vfcmt resources"); + response = DcaeRestClient.getAllVfcmts(); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + } catch (Exception err) { + Report.log(Status.ERROR, err); + } + } + + /* Positive tests */ + + @Test + public void testResponseStatusOk() { + // assert + Report.log(Status.INFO, "Verifying response status is 200"); + assertThat(response.getStatusCode()).as("response status").isEqualTo(200); + } + + @Test + public void testResponseBodyIsListOfVfcmtsOnly() { + // assert + Report.log(Status.INFO, "Parsing response to a list of VFCMTs"); + Vfcmt[] vfcmtList = gson.fromJson(response.getResponse(), Vfcmt[].class); + Report.log(Status.INFO, "Verifying all items of the parsed response are VFCMTs"); + assertThat(vfcmtList) + .as("response data") + .extracting("resourceType") + .containsOnly("VFCMT"); + } + + /* Negative tests */ +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetVfcmtsForMigration.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetVfcmtsForMigration.java new file mode 100644 index 0000000..c12a14c --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/GetVfcmtsForMigration.java @@ -0,0 +1,96 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + + +import com.aventstack.extentreports.Status; +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.utilities.DcaeRestClient; +import org.onap.dcae.ci.report.Report; +import org.onap.dcae.ci.utilities.StringUtils; +import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.services.Service; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GetVfcmtsForMigration extends DcaeRestBaseTest { + + private static final String STATUS_CODE = "status code"; + private RestResponse response; + private Resource res = null; + + @BeforeClass + public void executeApiCall() { + try { + // act + Report.log(Status.INFO, "Selecting vfcmt resources for migration"); + response = DcaeRestClient.getVfcmtsForMigration("services","1111111","1.3"); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + + Report.log(Status.INFO, "getAllMonitoringTemplatesVfcmts"); + RestResponse clientResponse = DcaeRestClient.getAllMonitoringTemplatesVfcmts(); + Resource[] resources = gson.fromJson(clientResponse.getResponse(),Resource[].class); + if (resources.length > 0){ + res = resources[0]; + } + } catch (Exception err) { + Report.log(Status.ERROR, err); + } + } + + // If tests are taking too long: consider removing this very tedious and long test + @Test + public void testCreateMonitoringComponentSuccess() throws IOException { + CreateVFCMTRequest request = new CreateVFCMTRequest(); + + request.setDescription("Test description"); + + Service service; + + try { + service = createServiceWithVFiAsSdcDesigner(); + } catch (Exception e) { + Report.log(Status.ERROR, e); + return; + } + + // If you crashed here (below) it is because your environment has no Base Monitoring Templates + request.setTemplateUuid(res.getUuid()); + if (service != null) { + request.setServiceUuid(service.getUuid()); + } + request.setVfiName(service.getResources().get(0).getResourceInstanceName()); + + List<String> listOfVfcmtsConnectedToService = new ArrayList<>(); + for (int i = 0 ; i < 4 ; i++){ + request.setName(StringUtils.randomString("CI-", 20)); + DcaeRestClient.fillCreateMcRequestMandatoryFields(request); + response = DcaeRestClient.createMc(gson.toJson(request)); + assertThat(response.getStatusCode()).as(STATUS_CODE).isEqualTo(200); + CreateMcResponse mcResponse = gson.fromJson(response.getResponse(),CreateMcResponse.class); + String key = mcResponse.getVfcmt().getUuid(); + String value = gson.toJson(mcResponse.getCdump()); + assertThat(value.contains(key)).isTrue(); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + listOfVfcmtsConnectedToService.add(key); + } + + response = DcaeRestClient.getVfcmtsForMigration("service",service.getUuid(),service.getVersion()); + assertThat(response.getStatusCode()).as(STATUS_CODE).isEqualTo(200); + + listOfVfcmtsConnectedToService.forEach( s -> assertThat(response.getResponse().contains(s)).isFalse()); + + response = DcaeRestClient.getAllVfcmts(); + assertThat(response.getStatusCode()).as(STATUS_CODE).isEqualTo(200); + + listOfVfcmtsConnectedToService.forEach( s -> assertThat(response.getResponse().contains(s)).isTrue()); + + } +} diff --git a/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/VfcmtCreationFlow.java b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/VfcmtCreationFlow.java new file mode 100644 index 0000000..f5ed264 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/api/tests/vfcmt/VfcmtCreationFlow.java @@ -0,0 +1,37 @@ +package org.onap.dcae.ci.api.tests.vfcmt; + +import org.onap.dcae.ci.api.tests.DcaeRestBaseTest; +import org.onap.dcae.ci.report.Report; +import org.testng.annotations.*; +import static org.assertj.core.api.Assertions.*; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +public class VfcmtCreationFlow extends DcaeRestBaseTest { + + private Vfcmt[] vfcmtsBeforeAdd; + private Vfcmt newVfcmt; + private Vfcmt[] vfcmtsAfterAdd; + + @BeforeClass + public void executeFlow() throws Exception { + Report.log(Status.INFO, "@BeforeClass --> executeFlow (getAllVfcmts)"); + try { + // act + vfcmtsBeforeAdd = client.getAllVfcmts(); + newVfcmt = client.createVfcmt(); + vfcmtsAfterAdd = client.getAllVfcmts(); + } catch (Exception err) { + Report.log(Status.ERROR, err); + err.printStackTrace(); + } + } + + @Test + public void test_numberOfVfcmtsIncresed() { + Report.log(Status.INFO, String.format("asserting (after[%d] > before[%d])", vfcmtsAfterAdd.length, vfcmtsBeforeAdd.length)); + // assert + assertThat(vfcmtsAfterAdd.length).isGreaterThan(vfcmtsBeforeAdd.length); + } +} diff --git a/src/main/java/org/onap/dcae/ci/config/Configuration.java b/src/main/java/org/onap/dcae/ci/config/Configuration.java new file mode 100644 index 0000000..0631800 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/config/Configuration.java @@ -0,0 +1,299 @@ +package org.onap.dcae.ci.config; + +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.Paths; + +public class Configuration { + private String apiPath; + private String dcaeBeHost; + private String beHost; + private String feHost; + private int bePort; + private int fePort; + private String dcaeBePort; + private String url; + private String remoteTestingMachineIP; + private int remoteTestingMachinePort; + private boolean remoteTesting; + private String browser; + private String systemUnderDebug; + private String reportDBhost; + private int reportDBport; + private boolean captureTraffic; + private boolean useBrowserMobProxy; + private String stopOnClassFailure; + private String reportFileName; + private String reportFolder; + private int numOfAttemptsToRefresh; + private boolean rerun; + private String windowsDownloadDirectory; + private String screenshotFolder; + private String harFilesFolder; + private String ruleEditorUrl; + + public Configuration() { + this.basicInit((String) null); + } + + public Configuration(String url) { + this.basicInit(url); + } + + public static synchronized Configuration loadConfigFile(File configFile) { + return loadConfigFile(configFile, Configuration.class); + } + + private void basicInit(String url) { + this.remoteTesting = false; + this.captureTraffic = false; + this.useBrowserMobProxy = false; + this.reportFolder = "." + File.separator + "ExtentReport" + File.separator; + this.reportFileName = "UI_Extent_Report.html"; + this.screenshotFolder = this.reportFolder + "screenshots" + File.separator; + this.harFilesFolder = this.reportFolder + "har_files" + File.separator; + this.browser = "firefox"; + this.url = url; + this.numOfAttemptsToRefresh = 2; + } + + public String getBeHost() { + return this.beHost; + } + + public void setBeHost(String beHost) { + this.beHost = beHost; + } + + public String getFeHost() { + return this.feHost; + } + + public void setFeHost(String feHost) { + this.feHost = feHost; + } + + public int getBePort() { + return this.bePort; + } + + public void setBePort(int bePort) { + this.bePort = bePort; + } + + public int getFePort() { + return this.fePort; + } + + public void setFePort(int fePort) { + this.fePort = fePort; + } + + public String getUrl() { + return this.url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRemoteTestingMachineIP() { + return this.remoteTestingMachineIP; + } + + public void setRemoteTestingMachineIP(String remoteTestingMachineIP) { + this.remoteTestingMachineIP = remoteTestingMachineIP; + } + + public int getRemoteTestingMachinePort() { + return this.remoteTestingMachinePort; + } + + public void setRemoteTestingMachinePort(int remoteTestingMachinePort) { + this.remoteTestingMachinePort = remoteTestingMachinePort; + } + + public boolean isRemoteTesting() { + return this.remoteTesting; + } + + public void setRemoteTesting(boolean remoteTesting) { + this.remoteTesting = remoteTesting; + } + + public String getBrowser() { + return this.browser; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getSystemUnderDebug() { + return this.systemUnderDebug; + } + + public void setSystemUnderDebug(String systemUnderDebug) { + this.systemUnderDebug = systemUnderDebug; + } + + public String getReportDBhost() { + return this.reportDBhost; + } + + public void setReportDBhost(String reportDBhost) { + this.reportDBhost = reportDBhost; + } + + public int getReportDBport() { + return this.reportDBport; + } + + public void setReportDBport(int reportDBport) { + this.reportDBport = reportDBport; + } + + public boolean isCaptureTraffic() { + return this.captureTraffic; + } + + public void setCaptureTraffic(boolean captureTraffic) { + this.captureTraffic = captureTraffic; + } + + public boolean isUseBrowserMobProxy() { + return this.useBrowserMobProxy; + } + + public void setUseBrowserMobProxy(boolean useBrowserMobProxy) { + this.useBrowserMobProxy = useBrowserMobProxy; + } + + public String getStopOnClassFailure() { + return this.stopOnClassFailure; + } + + public void setStopOnClassFailure(String stopOnClassFailure) { + this.stopOnClassFailure = stopOnClassFailure; + } + + public String getReportFileName() { + return this.reportFileName; + } + + public void setReportFileName(String reportFileName) { + this.reportFileName = reportFileName; + } + + public String getReportFolder() { + return this.reportFolder; + } + + public void setReportFolder(String reportFolder) { + this.reportFolder = reportFolder; + } + + public int getNumOfAttemptsToRefresh() { + return this.numOfAttemptsToRefresh; + } + + public void setNumOfAttemptsToRefresh(int numOfAttemptsToRefresh) { + this.numOfAttemptsToRefresh = numOfAttemptsToRefresh; + } + + public boolean isRerun() { + return this.rerun; + } + + public void setRerun(boolean rerun) { + this.rerun = rerun; + } + + public String getWindowsDownloadDirectory() { + return this.windowsDownloadDirectory; + } + + public void setWindowsDownloadDirectory(String windowsDownloadDirectory) { + this.windowsDownloadDirectory = windowsDownloadDirectory; + } + + public String getScreenshotFolder() { + return this.screenshotFolder; + } + + public void setScreenshotFolder(String screenshotFolder) { + this.screenshotFolder = screenshotFolder; + } + + public String getHarFilesFolder() { + return this.harFilesFolder; + } + + public void setHarFilesFolder(String harFilesFolder) { + this.harFilesFolder = harFilesFolder; + } + + public String getDcaeBeHost() { + return dcaeBeHost; + } + + public void setDcaeBeHost(String dcaeBeHost) { + this.dcaeBeHost = dcaeBeHost; + } + + public String getDcaeBePort() { + return dcaeBePort; + } + + public void setDcaeBePort(String dcaeBePort) { + this.dcaeBePort = dcaeBePort; + } + + public String getApiPath() { + return apiPath; + } + + public void setApiPath(String apiPath) { + this.apiPath = apiPath; + } + + public String getRuleEditorUrl() { + return ruleEditorUrl; + } + + public void setRuleEditorUrl(String ruleEditorUrl) { + this.ruleEditorUrl = ruleEditorUrl; + } + + + public static synchronized <T> T loadConfigFile(File configFile, Class<T> clazz) { + InputStream in = null; + T config = null; + + try { + String absolutePath = configFile.getAbsolutePath(); + in = Files.newInputStream(Paths.get(absolutePath, new String[0]), new OpenOption[0]); + Yaml yaml = new Yaml(); + config = yaml.loadAs(in, clazz); + } catch (IOException var14) { + var14.printStackTrace(); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException var13) { + var13.printStackTrace(); + } + } + + } + + return config; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/RestResponse.java b/src/main/java/org/onap/dcae/ci/entities/RestResponse.java new file mode 100644 index 0000000..4e5b60f --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/RestResponse.java @@ -0,0 +1,57 @@ +package org.onap.dcae.ci.entities; + +import java.util.List; +import java.util.Map; + +public class RestResponse { + Integer statusCode; + String response; + Map<String, List<String>> headerFields; + String responseMessage; + + public RestResponse() { + } + + public RestResponse(Integer errorCode, String response, Map<String, List<String>> headerFields, String responseMessage) { + this.statusCode = errorCode; + this.response = response; + this.headerFields = headerFields; + this.responseMessage = responseMessage; + } + + public Integer getStatusCode() { + return this.statusCode; + } + + public void setStatusCode(Integer errorCode) { + this.statusCode = errorCode; + } + + public String getResponse() { + return this.response; + } + + public void setResponse(String response) { + this.response = response; + } + + public Map<String, List<String>> getHeaderFields() { + return this.headerFields; + } + + public void setHeaderFields(Map<String, List<String>> headerFields) { + this.headerFields = headerFields; + } + + public String getResponseMessage() { + return this.responseMessage; + } + + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } + + public String toString() { + return "RestResponse [errorCode=" + this.statusCode + ", response=" + this.response + ", headerFields=" + this.headerFields + ", responseMessage=" + this.responseMessage + "]"; + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Artifact.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Artifact.java new file mode 100644 index 0000000..eae61ea --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Artifact.java @@ -0,0 +1,109 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Artifact { + + @SerializedName("artifactChecksum") + @Expose + private String artifactChecksum; + @SerializedName("artifactType") + @Expose + private String artifactType; + @SerializedName("artifactUUID") + @Expose + private String artifactUUID; + @SerializedName("artifactVersion") + @Expose + private String artifactVersion; + @SerializedName("artifactName") + @Expose + private String artifactName; + @SerializedName("artifactGroupType") + @Expose + private String artifactGroupType; + @SerializedName("artifactURL") + @Expose + private String artifactURL; + @SerializedName("artifactDescription") + @Expose + private String artifactDescription; + @SerializedName("artifactLabel") + @Expose + private String artifactLabel; + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Data.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Data.java new file mode 100644 index 0000000..f7f44d3 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Data.java @@ -0,0 +1,21 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Data { + + @SerializedName("element") + @Expose + private Element element; + + public Element getElement() { + return element; + } + + public void setElement(Element element) { + this.element = element; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/DcaeComponents.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/DcaeComponents.java new file mode 100644 index 0000000..c434a0d --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/DcaeComponents.java @@ -0,0 +1,56 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import java.lang.*; + +public class DcaeComponents { + + @SerializedName("id") + @Expose + private Object id; + @SerializedName("timestamp") + @Expose + private Integer timestamp; + @SerializedName("data") + @Expose + private Data data; + @SerializedName("error") + @Expose + private java.lang.Error error; + + public Object getId() { + return id; + } + + public void setId(Object id) { + this.id = id; + } + + public Integer getTimestamp() { + return timestamp; + } + + public void setTimestamp(Integer timestamp) { + this.timestamp = timestamp; + } + + public Data getData() { + return data; + } + + public void setData(Data data) { + this.data = data; + } + + public java.lang.Error getError() { + return error; + } + + public void setError(java.lang.Error error) { + this.error = error; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Element.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Element.java new file mode 100644 index 0000000..64c6601 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Element.java @@ -0,0 +1,55 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Element { + + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("name") + @Expose + private String name; + @SerializedName("id") + @Expose + private String id; + @SerializedName("items") + @Expose + private List<Item> items = null; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List<Item> getItems() { + return items; + } + + public void setItems(List<Item> items) { + this.items = items; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Error.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Error.java new file mode 100644 index 0000000..bad41a1 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Error.java @@ -0,0 +1,8 @@ + +package org.onap.dcae.ci.entities.composition.items; + + +public class Error { + + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Item.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Item.java new file mode 100644 index 0000000..a184886 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Item.java @@ -0,0 +1,220 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Item { + + @SerializedName("lifecycleState") + @Expose + private String lifecycleState; + @SerializedName("models") + @Expose + private List<Model> models = null; + @SerializedName("subCategory") + @Expose + private String subCategory; + @SerializedName("catalog") + @Expose + private String catalog; + @SerializedName("lastUpdaterUserId") + @Expose + private String lastUpdaterUserId; + @SerializedName("description") + @Expose + private String description; + @SerializedName("uuid") + @Expose + private String uuid; + @SerializedName("version") + @Expose + private String version; + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("catalogId") + @Expose + private Integer catalogId; + @SerializedName("toscaModelURL") + @Expose + private String toscaModelURL; + @SerializedName("name") + @Expose + private String name; + @SerializedName("invariantUUID") + @Expose + private String invariantUUID; + @SerializedName("id") + @Expose + private Integer id; + @SerializedName("category") + @Expose + private String category; + @SerializedName("lastUpdaterFullName") + @Expose + private String lastUpdaterFullName; + @SerializedName("toscaResourceName") + @Expose + private String toscaResourceName; + @SerializedName("resourceType") + @Expose + private String resourceType; + @SerializedName("artifacts") + @Expose + private List<Artifact> artifacts = null; + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public List<Model> getModels() { + return models; + } + + public void setModels(List<Model> models) { + this.models = models; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getCatalog() { + return catalog; + } + + public void setCatalog(String catalog) { + this.catalog = catalog; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public Integer getCatalogId() { + return catalogId; + } + + public void setCatalogId(Integer catalogId) { + this.catalogId = catalogId; + } + + public String getToscaModelURL() { + return toscaModelURL; + } + + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public List<Artifact> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<Artifact> artifacts) { + this.artifacts = artifacts; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/items/Model.java b/src/main/java/org/onap/dcae/ci/entities/composition/items/Model.java new file mode 100644 index 0000000..2b3a85b --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/items/Model.java @@ -0,0 +1,65 @@ + +package org.onap.dcae.ci.entities.composition.items; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Model { + + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("name") + @Expose + private String name; + @SerializedName("description") + @Expose + private String description; + @SerializedName("id") + @Expose + private String id; + @SerializedName("version") + @Expose + private String version; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Artifact.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Artifact.java new file mode 100644 index 0000000..4d095ab --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Artifact.java @@ -0,0 +1,109 @@ + +package org.onap.dcae.ci.entities.composition.rightMenu.element; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Artifact { + + @SerializedName("artifactChecksum") + @Expose + private String artifactChecksum; + @SerializedName("artifactType") + @Expose + private String artifactType; + @SerializedName("artifactUUID") + @Expose + private String artifactUUID; + @SerializedName("artifactVersion") + @Expose + private String artifactVersion; + @SerializedName("artifactName") + @Expose + private String artifactName; + @SerializedName("artifactGroupType") + @Expose + private String artifactGroupType; + @SerializedName("artifactURL") + @Expose + private String artifactURL; + @SerializedName("artifactDescription") + @Expose + private String artifactDescription; + @SerializedName("artifactLabel") + @Expose + private String artifactLabel; + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public void setArtifactChecksum(String artifactChecksum) { + this.artifactChecksum = artifactChecksum; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public String getArtifactGroupType() { + return artifactGroupType; + } + + public void setArtifactGroupType(String artifactGroupType) { + this.artifactGroupType = artifactGroupType; + } + + public String getArtifactURL() { + return artifactURL; + } + + public void setArtifactURL(String artifactURL) { + this.artifactURL = artifactURL; + } + + public String getArtifactDescription() { + return artifactDescription; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Item.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Item.java new file mode 100644 index 0000000..aa96b43 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Item.java @@ -0,0 +1,220 @@ + +package org.onap.dcae.ci.entities.composition.rightMenu.element; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Item { + + @SerializedName("lifecycleState") + @Expose + private String lifecycleState; + @SerializedName("models") + @Expose + private List<Model> models = null; + @SerializedName("subCategory") + @Expose + private String subCategory; + @SerializedName("catalog") + @Expose + private String catalog; + @SerializedName("lastUpdaterUserId") + @Expose + private String lastUpdaterUserId; + @SerializedName("description") + @Expose + private String description; + @SerializedName("uuid") + @Expose + private String uuid; + @SerializedName("version") + @Expose + private String version; + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("catalogId") + @Expose + private Integer catalogId; + @SerializedName("toscaModelURL") + @Expose + private String toscaModelURL; + @SerializedName("name") + @Expose + private String name; + @SerializedName("invariantUUID") + @Expose + private String invariantUUID; + @SerializedName("id") + @Expose + private Integer id; + @SerializedName("category") + @Expose + private String category; + @SerializedName("lastUpdaterFullName") + @Expose + private String lastUpdaterFullName; + @SerializedName("toscaResourceName") + @Expose + private String toscaResourceName; + @SerializedName("resourceType") + @Expose + private String resourceType; + @SerializedName("artifacts") + @Expose + private List<Artifact> artifacts = null; + + public String getLifecycleState() { + return lifecycleState; + } + + public void setLifecycleState(String lifecycleState) { + this.lifecycleState = lifecycleState; + } + + public List<Model> getModels() { + return models; + } + + public void setModels(List<Model> models) { + this.models = models; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getCatalog() { + return catalog; + } + + public void setCatalog(String catalog) { + this.catalog = catalog; + } + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public void setLastUpdaterUserId(String lastUpdaterUserId) { + this.lastUpdaterUserId = lastUpdaterUserId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public Integer getCatalogId() { + return catalogId; + } + + public void setCatalogId(Integer catalogId) { + this.catalogId = catalogId; + } + + public String getToscaModelURL() { + return toscaModelURL; + } + + public void setToscaModelURL(String toscaModelURL) { + this.toscaModelURL = toscaModelURL; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getLastUpdaterFullName() { + return lastUpdaterFullName; + } + + public void setLastUpdaterFullName(String lastUpdaterFullName) { + this.lastUpdaterFullName = lastUpdaterFullName; + } + + public String getToscaResourceName() { + return toscaResourceName; + } + + public void setToscaResourceName(String toscaResourceName) { + this.toscaResourceName = toscaResourceName; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public List<Artifact> getArtifacts() { + return artifacts; + } + + public void setArtifacts(List<Artifact> artifacts) { + this.artifacts = artifacts; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/ItemsElement.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/ItemsElement.java new file mode 100644 index 0000000..d7ed2cb --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/ItemsElement.java @@ -0,0 +1,55 @@ + +package org.onap.dcae.ci.entities.composition.rightMenu.element; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class ItemsElement { + + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("name") + @Expose + private String name; + @SerializedName("id") + @Expose + private Integer id; + @SerializedName("items") + @Expose + private List<Item> items = null; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public List<Item> getItems() { + return items; + } + + public void setItems(List<Item> items) { + this.items = items; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Model.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Model.java new file mode 100644 index 0000000..4541aaf --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Model.java @@ -0,0 +1,65 @@ + +package org.onap.dcae.ci.entities.composition.rightMenu.element; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Model { + + @SerializedName("itemId") + @Expose + private String itemId; + @SerializedName("name") + @Expose + private String name; + @SerializedName("description") + @Expose + private String description; + @SerializedName("id") + @Expose + private String id; + @SerializedName("version") + @Expose + private String version; + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Service.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Service.java new file mode 100644 index 0000000..3c33535 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/element/Service.java @@ -0,0 +1,21 @@ + +package org.onap.dcae.ci.entities.composition.rightMenu.element; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Service { + + @SerializedName("element") + @Expose + private ItemsElement element; + + public ItemsElement getElement() { + return element; + } + + public void setElement(ItemsElement element) { + this.element = element; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Element.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Element.java new file mode 100644 index 0000000..350a350 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Element.java @@ -0,0 +1,76 @@ +package org.onap.dcae.ci.entities.composition.rightMenu.elements; + +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Element { + +@SerializedName("itemId") +@Expose +private String itemId; +@SerializedName("catalogId") +@Expose +private Integer catalogId; +@SerializedName("catalog") +@Expose +private String catalog; +@SerializedName("name") +@Expose +private String name; +@SerializedName("id") +@Expose +private Integer id; +@SerializedName("labels") +@Expose +private List<String> labels = null; + +public String getItemId() { +return itemId; +} + +public void setItemId(String itemId) { +this.itemId = itemId; +} + +public Integer getCatalogId() { +return catalogId; +} + +public void setCatalogId(Integer catalogId) { +this.catalogId = catalogId; +} + +public String getCatalog() { +return catalog; +} + +public void setCatalog(String catalog) { +this.catalog = catalog; +} + +public String getName() { +return name; +} + +public void setName(String name) { +this.name = name; +} + +public Integer getId() { +return id; +} + +public void setId(Integer id) { +this.id = id; +} + +public List<String> getLabels() { +return labels; +} + +public void setLabels(List<String> labels) { +this.labels = labels; +} + +}
\ No newline at end of file diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Elements.java b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Elements.java new file mode 100644 index 0000000..b5dad46 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/rightMenu/elements/Elements.java @@ -0,0 +1,18 @@ +package org.onap.dcae.ci.entities.composition.rightMenu.elements; +import java.util.List; +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +public class Elements { + @SerializedName("elements") + @Expose + private List<Element> elements = null; + + public List<Element> getElements() { + return elements; + } + + public void setElements(List<Element> elements) { + this.elements = elements; + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/services/CiService.java b/src/main/java/org/onap/dcae/ci/entities/composition/services/CiService.java new file mode 100644 index 0000000..5a272b6 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/services/CiService.java @@ -0,0 +1,11 @@ +package org.onap.dcae.ci.entities.composition.services; + +import org.onap.dcae.ci.entities.sdc.SdcService; +import org.onap.sdc.dcae.composition.services.Service; + +public class CiService extends Service { + // partial construction - converts from internal SDC object to dcae-ci object (external SDC) + public CiService(SdcService service) { + super(service.getName(), service.getUuid(), service.getVersion()); + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/composition/services/Vfi.java b/src/main/java/org/onap/dcae/ci/entities/composition/services/Vfi.java new file mode 100644 index 0000000..4b084d6 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/composition/services/Vfi.java @@ -0,0 +1,21 @@ +package org.onap.dcae.ci.entities.composition.services; + +import org.onap.dcae.ci.entities.sdc.SdcService; + +public class Vfi { + private String name; + private SdcService container; + + public Vfi(String name, SdcService container) { + this.name = name; + this.container = container; + } + + public String getName() { + return name; + } + + public SdcService getContainer() { + return container; + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/dcae/ci/entities/rule_editor/SaveRuleError.java b/src/main/java/org/onap/dcae/ci/entities/rule_editor/SaveRuleError.java new file mode 100644 index 0000000..407cc37 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/rule_editor/SaveRuleError.java @@ -0,0 +1,27 @@ +package org.onap.dcae.ci.entities.rule_editor; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class SaveRuleError { + private Map<String, Object> requestError; + private String notes; + + @JsonCreator + public SaveRuleError( + @JsonProperty("requestError") Map<String, Object> requestError, @JsonProperty("notes") String notes) { + this.requestError = requestError; + this.notes = notes; + } + + + + public List<String> getFormattedErrors() { + List<Map<String, String>> errors = (List<Map<String, String>>)requestError.get("serviceExceptions"); + return errors.stream().map(e -> e.get("formattedErrorMessage")).collect(Collectors.toList()); + } +}
\ No newline at end of file diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcCategory.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcCategory.java new file mode 100644 index 0000000..8d14aa2 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcCategory.java @@ -0,0 +1,28 @@ +package org.onap.dcae.ci.entities.sdc; + +import java.util.Arrays; +import java.util.List; + +public class SdcCategory { + + private String name; + private List<SdcCategory> subcategories; + + + public String getName() { + return name; + } + + public List<SdcCategory> getSubcategories() { + return subcategories; + } + + public SdcCategory(String categoryName) { + this.name = categoryName; + } + + public SdcCategory(String categoryName, String subCategoryName){ + this(categoryName); + this.subcategories = Arrays.asList(new SdcCategory(subCategoryName)); + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponent.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponent.java new file mode 100644 index 0000000..1dc7206 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponent.java @@ -0,0 +1,113 @@ +package org.onap.dcae.ci.entities.sdc; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class SdcComponent { + + private String name; + private String description; + private List<String> tags; + private String contactId; + private String icon; + private String uuid; + + private String lastUpdaterUserId; + private String uniqueId; + private String version; + private String resourceType; + private List<SdcCategory> categories; + private Map<String, String> allVersions; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List<String> getTags() { + return tags; + } + + public void setTags(List<String> tags) { + this.tags = tags; + } + + public String getContactId() { + return contactId; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getLastUpdaterUserId() { + return lastUpdaterUserId; + } + + public String getUniqueId() { + return uniqueId; + } + + public void setUniqueId(String uniqueId) { + this.uniqueId = uniqueId; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public List<SdcCategory> getCategories() { + return categories; + } + + public void setCategories(List<SdcCategory> categories) { + this.categories = categories; + } + + public Map<String, String> getAllVersions() { + return allVersions; + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentFactory.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentFactory.java new file mode 100644 index 0000000..1cb9cbc --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentFactory.java @@ -0,0 +1,41 @@ +package org.onap.dcae.ci.entities.sdc; + +import org.apache.commons.lang3.RandomStringUtils; + +import org.onap.dcae.ci.utilities.DcaeRestClient; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class SdcComponentFactory { + + private SdcComponentFactory(){} + + public static SdcService getDefaultService() { + SdcService service = new SdcService(); + service.setCategories(Arrays.asList(new SdcCategory("Mobility"))); + setDefaultComponentFields(service, "CiService"); + return service; + } + + public static SdcResource getDefaultResource() { + SdcResource resource = new SdcResource(); + resource.setVendorName("vendorName"); + resource.setVendorRelease("1.1"); + resource.setResourceType("VF"); + resource.setCategories(Arrays.asList(new SdcCategory("Generic", "Infrastructure"))); + setDefaultComponentFields(resource, "CiResource"); + return resource; + } + + private static void setDefaultComponentFields(SdcComponent component, String name) { + component.setName(name.concat(RandomStringUtils.randomAlphanumeric(4))); + List<String> tags = new ArrayList<>(); + tags.add(component.getName()); + component.setTags(tags); + component.setDescription("Ci component description"); + component.setIcon("defaultIcon"); + component.setContactId(DcaeRestClient.getDefaultUserId()); + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentInstance.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentInstance.java new file mode 100644 index 0000000..d300908 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentInstance.java @@ -0,0 +1,20 @@ +package org.onap.dcae.ci.entities.sdc; + + +public class SdcComponentInstance { + + String componentUid; + String description; + String posX; + String posY; + String name; + String uniqueId; + + public SdcComponentInstance(SdcResource vf) { + this.componentUid = vf.getUniqueId(); + this.posX = "20"; + this.posY = "20"; + this.name = vf.getName(); + this.description = vf.getDescription(); + } +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentMetadata.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentMetadata.java new file mode 100644 index 0000000..c284e5d --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcComponentMetadata.java @@ -0,0 +1,12 @@ +package org.onap.dcae.ci.entities.sdc; + + +public class SdcComponentMetadata { + + private SdcComponent metadata; + + public SdcComponent getMetadata() { + return metadata; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcResource.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcResource.java new file mode 100644 index 0000000..8cd5605 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcResource.java @@ -0,0 +1,26 @@ +package org.onap.dcae.ci.entities.sdc; + + +public class SdcResource extends SdcComponent { + + private String vendorName; + private String vendorRelease; + + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVendorRelease() { + return vendorRelease; + } + + public void setVendorRelease(String vendorRelease) { + this.vendorRelease = vendorRelease; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/entities/sdc/SdcService.java b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcService.java new file mode 100644 index 0000000..4ee3ac0 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/entities/sdc/SdcService.java @@ -0,0 +1,37 @@ +package org.onap.dcae.ci.entities.sdc; + +import org.onap.dcae.ci.entities.sdc.SdcComponent; + + +public class SdcService extends SdcComponent { + + private String projectCode = "12345"; + private String serviceRole = "";// empty string is valid + private String serviceType = "";// empty string is valid + private String instantiationType = "Macro"; + + + public void setServiceRole(String serviceRole){ + this.serviceRole = serviceRole; + } + + public String getServiceRole(){ + return serviceRole; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceType(){ + return serviceType; + } + + public void setInstantiationType(String instantiationType) { + this.instantiationType = instantiationType; + } + + public String getInstantiationType(){ + return instantiationType; + } +} diff --git a/src/main/java/org/onap/dcae/ci/enums/HttpHeaderEnum.java b/src/main/java/org/onap/dcae/ci/enums/HttpHeaderEnum.java new file mode 100644 index 0000000..aed1c53 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/enums/HttpHeaderEnum.java @@ -0,0 +1,25 @@ +package org.onap.dcae.ci.enums; + +public enum HttpHeaderEnum { + Content_MD5("Content-MD5"), + USER_ID("USER_ID"), + CONTENT_TYPE("Content-Type"), + ACCEPT("Accept"), + X_ECOMP_REQUEST_ID_HEADER("X-ECOMP-RequestID"), + CACHE_CONTROL("Cache-Control"), + X_ECOMP_INSTANCE_ID("X-ECOMP-InstanceID"), + AUTHORIZATION("Authorization"), + CONTENT_LENGTH("Content-Length"), + X_ECOMP_SERVICE_ID_HEADER("X-ECOMP-ServiceID"); + + + String value; + + private HttpHeaderEnum(String value) { + this.value = value; + } + + public String getValue() { + return this.value; + } +} diff --git a/src/main/java/org/onap/dcae/ci/report/ExtentManager.java b/src/main/java/org/onap/dcae/ci/report/ExtentManager.java new file mode 100644 index 0000000..cbf28cb --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/report/ExtentManager.java @@ -0,0 +1,192 @@ +package org.onap.dcae.ci.report; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.reporter.ExtentHtmlReporter; +import com.aventstack.extentreports.reporter.ExtentXReporter; +import com.aventstack.extentreports.reporter.configuration.Protocol; +import com.aventstack.extentreports.reporter.configuration.Theme; +import org.apache.commons.io.FileUtils; +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.utilities.SetupReport; +import org.testng.ITestContext; + +import java.io.*; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Properties; + +public class ExtentManager { + + private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; + private static ExtentReports extent; + private static ExtentHtmlReporter htmlReporter; + private static ExtentXReporter extentxReporter; + private static final String icon = "$(document).ready(function() {" + "\n" + + "$('.brand-logo').html('').prepend(\"<span><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQ4AAAB7CAYAAACFKW5jAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAABaAAAAWgBwI7h9AAAAB3RJTUUH3wwXFAQf1clFIAAANNxJREFUeNrtnXeYXVXV/z+n3To101ImvZFGQiCANKUoSBEFebEj1hcb2MWC+lpAbGD5CaKoiL2ggIgoRUIgQAohJCG9TTLJ9Dszt52y9++PfSeZTO6duXfmTkk4n+eZJ5Nbztn7zNnrrL32Wt8NPj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+PgOjjXYDhpX7WgkZMD2qY2qQFtDlSkSvjlsaGJpGUIeQAS1pyb60hMurRrv1Pj5jFnO0G1As9PvbmBiEDkeS8CSmpuEhCOi6FTW0sAYhiTRNTTM8JBoaGmDpSEODoK65EQM7YpLCCCVC97ciAUODuSU6UpO88Jpxo91NH58xwTHtcSx6vJ2DKUlTSlBVVqKVesnqlrSosaWcFTa0eXFX1nmSmrChjTc1qoCIKwlJ1W8NkDoITUPokAQ6U0I2uYL9FZZ+UNfYnvDkhoWlRnNdhIMP7HWcsqDOonKDsK7znzPLRvsS+PiMCsec4VjwWDvNaUFTh8eS8VbFvpSc4Qh5esJjKbBASDnDlZTqGmEpQQ7yPLoGSGxdIx4xtEZbyhdrA/pGIVk+ParveEt9qOH69d3i1AqTcbg8eE71aF8aH58RY8wbjresjbGiCTzpsb/JYUF9oKwpJZekhLzQkfJMIVnkCMoBY7BGIl90DQyNeEjXdhsaz4UN7V9TwvozK88p31Pzzza5uNykOqDzh2Wlo33ZfHyGlTFrOC58opMGT9DuCG6YGdG/ty0xxxby4pTgEkfKpa6gYrgNRX9ogKHhBHVta4WlPR4xtPtmRPXn/7U73XlGfYCoAf8+o2K0L6OPz7AwJg3H/Mc6aEoLFpUawe0J79RuV76525WXuYLpYrQblwUNCOh0Rk3tuQpL/119WHv4yS3O/lNnBji53OQnS6Kj3UQfn6IypgzHOcvb2ZWQnFRpWavbnDM6XfmelJCXOIKq0fQuCsHScKOmtqbE1H41K2r89Yl9qQPvmh3hnqX+9MXn+GHMGI4TH+vgX2eEtLOXJ09sscUHEx5XOUJWHysGoy+mhltmas9OCOl3/E998O9rO9yub82PMLf0uFkB93kFM+qG44HGNF/dnCSoU7s9Lt4bc+UHUp6cdqwajL6EdS01OaI/eOY469t3nxR9PuFJGTX10W6Wj8+QGFXDIaUE0M5d0XnW+k73pg5HnutJjNG+KMVG12Ba2NjzwWnB2z89O/xLDdoANG3U7baPz6AYlUeflLLHaES++nLius1d3m/bbHnB8Wg0AISEnXFvyv0H7Fu2x727gaU918HH51hkxA1Hr8EyrdkW31vZ7n67MSXqj/chJDXY3O1Zrba8HPgN8DYg2MuI+vgcM4yo4eg1QM4B7m1Kyw++2OlFRvsijEznoTaoMyGkA5wA/AT4IlDR59r4+Ix5Rsxw/L4hBWAAbwF+AZz5SprhmzpcPSnIpNChS14GfBa4HZjSYgu+uTkx2s308cmLETEc5yzvoMrSw2khrwN+AMwAmBrROXPc8b88qQNXTQxy3bQgxpHW0gLeCdxZFdAXfn5jguWtzmg318dnQIbdcLz26U7Chla+KuZ+xRbcAtT0vBc1NL4wJ8yp48zBV6ONZSSUmxrXzwzx/UURaoJZL7cGXPTPg/Yvrq4PvursPzT50xafMc+wGo4LVnRQH9LKG5LiyxNC+g0lpnZU7vXicpO7TyrhqkkBwoZ2fBgQCRFD47xai7uXlnDz/Ah1wf4v9ZOt7ikr2pw73v+qstO1n+z3jYfPmGbYwgyvf6aTqREt+uAB58uTw/rH/rSsNNhrfn8Una7kvkabn+5KsabDJeUNdwuLTGacjwtonFppcs3kIBfWBai0Bu5AhyO58rkuHm92mFFirHltrfXedTH3hWfOqRjtXvn4ZGVYhuWtWxK80CmsZ9rsT+9JiC9+bGYo/J2F0bzcm4NpwWPNDvc12qxsd9mXEoieyraxZER6OQSllsacEoPzqi0uGW+xtNyk1MyvsRL4xZ40H30xTsKT6BrMiBj/vaQu8J7tCXfHg6eXj3ZPfXyOouhD8SMvdHLj3BL99c90XrM17t2edGXpdxZG+OSscEHHSQvJ1m7Bs+0uT7Q4rIm57E4IEp7kCC9+JIxJn/OFdI1JYZ1ZUZ1lFSbnVFssLjOoCeoFN+fxFof3v9DN9m5xqC+mBnNLjL9cNSn4walhvfXaqaER6KSPT/4UdUlDSon221bWd3WdtyfpfS3pSVUSOojBHdQ1FpYZLCwzuGZKkH0pwY64x/pOj7Uxl21xwYGUoDktSAiJK6CYYQFNU0uoYV2jOqgxKaQzM2qwoFT9zIoa1Id1FZcZJI81O1y/Pn6E0QBwJWxPiDf+p9nZ8+mZoS883+4ml1Ue/6tPPscORX1ev3ZFDFfI2eu7vN+12PJkACR8dk6Ym+dHinYyiYoLtNmCVluyJynYkxQcTAmaMq/FHElaSBwJXsagmErBK/OvRkCHgK5haRDQIWRolJka5abGuIDG1IjBlLBOVUCjOqBTbmlF6UNaSP683+amTUl2xL2cf4VKS+u+bHzg479aWvJzQPq1LT5jhaLdiQ812fx2T7r0v63OHftT4m09gxUJ59da/PXUUsrynPcPlZQnSQpwhcRD1YqAKjbTAV3T0FEehaH1/CgDMtzsSgh+uCPJz3eniTmy37+ABiwsM3Z+aW7kf66aGFjlGw6fsULR/N/X11jaFzcm3tmUFld6fWICz7e7PN7icPn4wIh0KmRohIzMyccIHY7k/gM2P9ihVo1kHs2TwM6EmL4z7n0RuFZK2e4bD5+xQFHyOKSUfH5jYv7BlPh4WhDs+36nI7llS5It3d5gDn9ME3PUtOStq7r433VxVre7BaWqdDuS3UlxkSO4llGqZvbx6UuxbsRQxNA+1u7IWVnf1WBlu8snNyTYmxyLqqHF50Ba8Ku9af5nVRfXrOnm4YMOSU8OygnalxLBtJAfBZb4iWE+Y4EhT1UyN/IFC8uM/xnolv7HAZuPAN9eEGFOyfEnvZEW8HKXy0NNDvftt1nX6WJ7HN7+aZBICbrGNOB64DopZcKfsviMJkMyHBmjUQVcf3qlWbGk3OCZVjfnIJHA/QdsmtKCr5wQ4fwaixGKlw4bnoQ9ScEzbQ4PHHBY3uqwLyVUZ4doMHqYEtYJ6RrAG4G/PN5s3z/a/fZ5ZTOk2zpjON4P/BAIPnDA5n0vxGlKif6PLKEmpPOeKUHeOzXI7Oix5X2khVoCXtPh8Z9mm+WtLjsSHk6Pd1FEgrrGL5eW8JZJKrAsJI90OOLqXzekO26Y+cqQMvEZewz6Ns8YjQnAfcBpoJ6+9+xNc+PGBAcHMh4ZTigxuHpSgCsmBplXYmCNwfCfI6HdFmzu9lgT81je6rA25tGQ9NRUZEhXsh8kLKs0+ftppT0CQOxLitSdu1Mf+sbWxC/EG2qGeAIfn8ExVMPxQZS+xqF1Vk/CAwdsvrgpwYZOb+AzZFz6yWGdc6stLqixOL3SHHJW5mAREuKepM2WbI17bOzyeCHmsibmsjchaHN6bUg7zM0L6Ro/PjHKtVODh061Nuby4RfjK84cZ17+7QXRVj/W4TMaDCrGkTEa1cDb6WU0QCVTvXFCgFlRg1u2Jrmv0Sbh9rOakHl9b0Jwz540v9+XZmJI56Ryk6UVJovKDE4oMai0NEpMjUiRjIktIOFJ4p6kOS3ZnfTYHvfY1i3YFvfYnvBoSUs63SyGYgTGqga8tT7AVZMCR5zuYFqytds7pdLSzr9xY+KPw98SnwLp+XMd18tfgxoCpz3Zwcqzy98M3APkrF7rdiV/O2Dz4x0pVnW4uCLPM/a65BFTo9zSmBDUmRLRmRDUqQ3q1AY1qgIapaZOqan0L/Q+9R62kKQ96HKVAYi5klZb0pxWaelNaUFDStBqC5KeMiSMdAFdDi6tC/DjxVGmhI+cu31ra5IvbExwQqnxt1sXRt92SV0gOXqt9EEJUy0CFgNTgCjqzkkCDcALmZ+m0W5oMSnY45BS8udGO5ry5NUhQ+u35LXE1HhHfZDzqi3+2mhz7940L8Rc0gMFEXu9l/AkCU/SmBSs6Tj8uqEfrjnpSSXv7bXLjA0QEjzAkxJPcrhEP8f5RjXZVIKlw5snBbl5XuQoo9HpSh5rcfAkHEzLs//YkF4spFypj73pylnANeTOE4qjAupbBzjOFcAlo9D+DuA2YG8/n5kEvBV4MzAfKCH73dMNbAR+B/yW/AxIFfAZlFc/0vwX5RD0S8GG4/vbkzzR6i4bH9Bee1aVldd3JoZ0PjI9xJsnBHik2eEP+2yebXdoTWce7/nc930+4x0qXivQIxxzYyyDhPEhnQ/PCPGh6SHGZSmc+W+Lw8o2tdzd4YhxOxPiMg1WjnbT+2AC1wLvGeBzu4DvDfCZU/M4znDQDPya7IZDQ6n0fw04k4GTKEsy/VgKXAx8HliVx3feBtSPQt8FeRiOgtcw6sO6tqXLu+jZdrdghZnxIZ13TQ7yh1NK+PtpZXx+bpjTxvUSvTmuZ4U5kFBmalw1KcDvl5Vw4+xwVqPRlBb8YEeKTkddJE+i7Ut5F/xkZ2qsLa1MQw2sgbgYGGgn7tGqUXDIfTe+Dvg5cDaFjR8TeC1wF5kNuQbAHaW+53XNC/Y4VnV445psce7L3R5CZTQWTImpceY4kzPHmdwwQ/Bip8cTLQ6rOlw2dnkcSIvDy5wwdr2EwZJZSaoL6rym2uTt9UHO" + + "\n" + "})"; + private static String suiteName; + + public synchronized static ExtentReports setReporter(String filepath, String htmlFile, String dbIp, int dbPort, Boolean isAppend) { + if (extent == null) { + extentxReporter = new ExtentXReporter(dbIp, dbPort); + extent = new ExtentReports(); + initAndSetExtentHtmlReporter(filepath, htmlFile, isAppend); + + if (extentxReporter.config().getReportObjectId() != null) { + setExtentXReporter(isAppend); + } else { + extentxReporter.stop(); + } + } + return extent; + } + + + public synchronized static void setExtentXReporter(Boolean isAppend) { + extentxReporter.setAppendExisting(isAppend); + extent.attachReporter(extentxReporter); + } + + public synchronized static void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) { + setHtmlReportConfiguration(filePath, htmlFile); + htmlReporter.setAppendExisting(isAppend); + extent.attachReporter(htmlReporter); + } + + public synchronized static ExtentReports getReporter() { + return extent; + } + + public static void initReporter(Configuration config, ITestContext context) { + setSuiteName(context); + String envData = config.getUrl(); + String dbIp = config.getReportDBhost(); + int dbPort = config.getReportDBport(); + String filepath = config.getReportFolder(); + String htmlFile = config.getReportFileName(); + + + if (suiteName.equals(SetupReport.TESTNG_FAILED_XML_NAME)) { + if (config.isUseBrowserMobProxy()) { + setTrafficCaptue(config); + } + + setReporter(filepath, htmlFile, dbIp, dbPort, true); + suiteName = getKeyByValueFromPropertyFormatFile(filepath + VERSIONS_INFO_FILE_NAME, "suiteName"); + } else { + deleteDirectory(config.getReportFolder()); + createDirectory(filepath); + setReporter(filepath, htmlFile, dbIp, dbPort, false); + createVersionsInfoFile(filepath, VERSIONS_INFO_FILE_NAME, envData, suiteName); + } + reporterDataDefinition(envData, suiteName); + } + + private static void createVersionsInfoFile(String path, String file, String envData, String suiteName) { + File myFoo = new File(path + file); + FileOutputStream fooStream; + try { + fooStream = new FileOutputStream(myFoo, false); + String versions = ("env=\"" + envData + "\"\n" + "suiteName=\"" + suiteName + "\"\n"); + byte[] myBytes = versions.getBytes(); + fooStream.write(myBytes); + fooStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void reporterDataDefinition(String envData, String suiteNameFromVersionInfoFile) { + extent.setSystemInfo("Host Name Address", getExecutionHostAddress()); + extent.setSystemInfo("ExecutedOn", envData); + extent.setSystemInfo("SuiteName", suiteNameFromVersionInfoFile); + } + + private static void setSuiteName(ITestContext context) { + String suitePath = context.getSuite().getXmlSuite().getFileName(); + if (suitePath != null) { + File file = new File(suitePath); + suiteName = file.getName(); + } + } + + public static String getSuiteName() { + return suiteName; + } + + public synchronized static void setHtmlReportConfiguration(String filePath, String htmlFile) { + htmlReporter = new ExtentHtmlReporter(filePath + htmlFile); + htmlReporter.config().setTheme(Theme.STANDARD); + htmlReporter.config().setEncoding("UTF-8"); + htmlReporter.config().setProtocol(Protocol.HTTPS); + htmlReporter.config().setDocumentTitle("Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(true); + htmlReporter.config().setReportName("Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(false); + htmlReporter.config().setJS(icon); + } + + public static void closeReporter() { + extent.flush(); + } + + public static void setTrafficCaptue(Configuration config) { + config.setCaptureTraffic(true); + } + + + private static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) { + Properties prop = new Properties(); + InputStream input = null; + String value = null; + try { + input = new FileInputStream(fullPath); + prop.load(input); + value = (prop.getProperty(key)); + + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return value.replaceAll("\"",""); + } + + private static void deleteDirectory(String directoryPath) { + File dir = new File(directoryPath); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to delete " + dir); + } + } + + private static void createDirectory(String directoryPath) { + File directory = new File(String.valueOf(directoryPath)); + if (! directory.exists()){ + directory.mkdir(); + } + } + + private static String getExecutionHostAddress() { + + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·"); + System.out.println(computerName); + if (computerName.indexOf(".") > -1) + computerName = computerName.substring(0, + computerName.indexOf(".")).toUpperCase(); + } catch (UnknownHostException e) { + System.out.println("Uknown hostAddress"); + } + return computerName != null ? computerName : "Uknown hostAddress"; + } +} diff --git a/src/main/java/org/onap/dcae/ci/report/ExtentTestManager.java b/src/main/java/org/onap/dcae/ci/report/ExtentTestManager.java new file mode 100644 index 0000000..1b98001 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/report/ExtentTestManager.java @@ -0,0 +1,42 @@ +package org.onap.dcae.ci.report; + +import java.util.HashMap; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; + +public class ExtentTestManager { + + private static HashMap<Long, ExtentTest> extentTestMap = new HashMap<>(); + private static ExtentReports extent = ExtentManager.getReporter(); + + public static synchronized ExtentTest getTest() { + ExtentTest extentTest = extentTestMap.get(Thread.currentThread().getId()); + if (extentTest == null){ + extentTest = startTest("Automated setup/cleanup"); + } + return extentTest; + } + + public static synchronized void endTest() { + extent.flush(); + } + + public static synchronized ExtentTest startTest(String testName) { + return startTest(testName, ""); + } + + public static synchronized ExtentTest startTest(String testName, String desc) { + ExtentTest test = extent.createTest(testName, desc); + extentTestMap.put(Thread.currentThread().getId(), test); + return test; + } + + public static synchronized <T> void assignCategory(Class<T> clazz){ + String[] parts = clazz.getName().split("\\."); + String lastOne1 = parts[parts.length-1]; + String lastOne2 = parts[parts.length-2]; + getTest().assignCategory(lastOne2 + "-" + lastOne1); + } +} + diff --git a/src/main/java/org/onap/dcae/ci/report/Report.java b/src/main/java/org/onap/dcae/ci/report/Report.java new file mode 100644 index 0000000..bd74d49 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/report/Report.java @@ -0,0 +1,155 @@ +package org.onap.dcae.ci.report; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import com.aventstack.extentreports.markuputils.ExtentColor; +import com.aventstack.extentreports.markuputils.Markup; +import com.aventstack.extentreports.markuputils.MarkupHelper; +import org.onap.dcae.ci.report.ExtentManager; +import org.onap.dcae.ci.report.ExtentTestManager; +import org.onap.dcae.ci.utilities.SetupReport; +import org.testng.ITestResult; + +public class Report { + + private static String testName; + private static Throwable throwable; + private static int status; + + public static void log(Status status, String format, Object... args) { + log(status, String.format(format, args)); + } + + public static void logDebug(String message, Object obj) { + log(Status.DEBUG, "%s %s", message, wrapWithTextareaRO(obj.toString())); + } + + public static void fatal(String message, Exception err) { + log(Status.FATAL, "%s %s", message, wrapWithTextareaRO(err.toString())); + } + + + public static void log(Status logStatus, Markup mark){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, mark); + } + + public static void log(Status logStatus, String message){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message); + System.out.println(message); + } + + public static void log(Status logStatus, String message, String duration){ + log(logStatus, message + addDurationTag(duration)); + } + + public static void log(Status logStatus, Throwable throwable){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, throwable); + } + + public static void addTag(Status logStatus, String message){ + Markup m = null; + switch(logStatus){ + case PASS: + m = MarkupHelper.createLabel(message, ExtentColor.GREEN); + break; + case FAIL: + m = MarkupHelper.createLabel(message, ExtentColor.RED); + break; + case SKIP: + m = MarkupHelper.createLabel(message, ExtentColor.BLUE); + break; + case FATAL: + m = MarkupHelper.createLabel(message, ExtentColor.BROWN); + break; + default: + break; + } + + if (m != null){ + log(logStatus, m); + } + } + + + private static String addDurationTag(String duration){ + return "<td width=\"80px\">" + duration + "</td>"; + } + + public static void report(ITestResult result) { + + testName = result.getName(); + throwable = result.getThrowable(); + status = result.getStatus(); + String suiteName = ExtentManager.getSuiteName(); + + switch (status) { + case ITestResult.SUCCESS: + logSuccessAfterTest(); + break; + + case ITestResult.FAILURE: + if (suiteName.equals(SetupReport.TESTNG_FAILED_XML_NAME)) { + logFatalAfterTest(); + } else { + logFailAfterTest(); + } + break; + + case ITestResult.SKIP: + logSkipAfterTest(); + break; + + default: + break; + } + + } + + /* Private members */ + + private static String wrapWithTextareaRO(String str) { + return String.format("<textarea readonly style=\"height:100px\">%s</textarea>", str); + } + + private static void logSuccessAfterTest() { + final Status logStatus = Status.PASS; + addTag(logStatus, "Success"); + } + + private static void logFailAfterTest() { + addTag(Status.FAIL, "Failure"); + try { + log(Status.ERROR, "ERROR - The following exepction occured : "); + log(Status.ERROR, throwable); + } catch (Exception e) { + log(Status.ERROR, "ERROR - The following exepction occured : " + e.getMessage()); + } + } + + private static void logSkipAfterTest() { + final Status logStatus = Status.SKIP; + addTag(logStatus, "Skipped"); + try { + log(logStatus, "SKIP - The following exepction occured : "); + log(logStatus, throwable); + } catch (Exception e) { + log(logStatus, "SKIP - The following exepction occured : " + e.getMessage()); + } + } + + private static void logFatalAfterTest() { + final Status logStatus = Status.FATAL; + addTag(logStatus, "Fatal"); + try { + log(logStatus, "FATAL - The following exepction occured : "); + log(logStatus, throwable); + } catch (Exception e) { + log(logStatus, "FATAL - The following exepction occured : " + e.getMessage()); + } + } + + +} diff --git a/src/main/java/org/onap/dcae/ci/run/RunTestSuite.java b/src/main/java/org/onap/dcae/ci/run/RunTestSuite.java new file mode 100644 index 0000000..01c921c --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/run/RunTestSuite.java @@ -0,0 +1,28 @@ +package org.onap.dcae.ci.run; + +import org.testng.TestNG; + +import java.util.ArrayList; +import java.util.List; + +public class RunTestSuite { + + private RunTestSuite(){} + + public static void main(String[] args) { + TestNG testng = new TestNG(); + List<String> suites = new ArrayList<>(); + + String testSuite = System.getProperty("testSuite"); + if (testSuite == null){ + System.out.println("No test suite file was found, please provide test suite."); + System.exit(1); + } + suites.add(testSuite); + testng.setTestSuites(suites); + testng.setUseDefaultListeners(true); + testng.setOutputDirectory("target/"); + testng.run(); + } + +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/BaseRestUtils.java b/src/main/java/org/onap/dcae/ci/utilities/BaseRestUtils.java new file mode 100644 index 0000000..def25fd --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/BaseRestUtils.java @@ -0,0 +1,96 @@ +package org.onap.dcae.ci.utilities; + +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.enums.HttpHeaderEnum; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +public class BaseRestUtils { + + protected static final String acceptHeaderData = "application/json"; + protected static final String contentTypeHeaderData = "application/json"; + + public BaseRestUtils() { + } + + protected static String getApiUrl(String path) { + Configuration configuration = SetupReport.getConfiguration(); + return String.format("%s:%s/sdc2/rest/v1/catalog/%s", configuration.getBeHost(), configuration.getBePort(), path); + } + + protected static Map<String, String> prepareHeadersMap(String userId) { + return prepareHeadersMap(userId, acceptHeaderData); + } + + protected static Map<String, String> prepareHeadersMap(String userId, String accept) { + Map<String, String> headersMap = new HashMap<>(); + + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData); + + if (accept != null) { + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), accept); + } + + if (userId != null) { + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + } + + return headersMap; + } + + protected static RestResponse sendGet(String url, String userId) throws IOException { + return sendGet(url, userId, (Map) null); + } + + protected static RestResponse sendGet(String url, String userId, Map<String, String> additionalHeaders) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse getResourceResponse = http.httpSendGet(url, headersMap); + return getResourceResponse; + } + + protected static RestResponse sendPut(String url, String userBodyJson, String userId, String cont) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId, cont); + HttpRequest http = new HttpRequest(); + RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap); + return updateResourceResponse; + } + + public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept) throws IOException { + return sendPost(url, userBodyJson, userId, accept, (Map) null); + } + + protected static RestResponse sendPost(String url, String userBodyJson, String userId, String accept, Map<String, String> additionalHeaders) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId, accept); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse postResourceResponse = http.httpSendPost(url, userBodyJson, headersMap); + return postResourceResponse; + } + + protected static RestResponse sendDelete(String url, String userId) throws IOException { + return sendDelete(url, userId, (Map) null); + } + + protected static RestResponse sendDelete(String url, String userId, Map<String, String> additionalHeaders) throws IOException { + Map<String, String> headersMap = prepareHeadersMap(userId); + if (additionalHeaders != null) { + headersMap.putAll(additionalHeaders); + } + + HttpRequest http = new HttpRequest(); + RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap); + return deleteResourceResponse; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/ConfigurationReader.java b/src/main/java/org/onap/dcae/ci/utilities/ConfigurationReader.java new file mode 100644 index 0000000..c557194 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/ConfigurationReader.java @@ -0,0 +1,39 @@ +package org.onap.dcae.ci.utilities; + +import org.onap.dcae.ci.config.Configuration; + +import java.io.File; + +public class ConfigurationReader { + + private static Configuration config; + + public static Configuration getConfiguration() { + if (config == null){ + File file = getConfigFile(); + config = Configuration.loadConfigFile(file, Configuration.class); + } + return config; + } + + public static File getConfigFile() { + String configFile = System.getProperty("config.resource"); + if (configFile == null){ + configFile = configurationFile(); + } + File file = new File(configFile); + if (false == file.exists()) { + throw new RuntimeException("The config file " + configFile + " cannot be found."); + } + return file; + } + + private static String configurationFile() { + return confPath() + File.separator + "conf.yaml"; + } + + public static String confPath() { + return System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "conf" + File.separator ; + } +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/DcaeEntityClient.java b/src/main/java/org/onap/dcae/ci/utilities/DcaeEntityClient.java new file mode 100644 index 0000000..d6b267f --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/DcaeEntityClient.java @@ -0,0 +1,148 @@ +package org.onap.dcae.ci.utilities; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.model.Requirement; +import org.onap.sdc.dcae.composition.model.Value; +import org.onap.sdc.dcae.composition.model.deserializer.RequirementDeserializer; +import org.onap.sdc.dcae.composition.model.deserializer.ValueDeserializer; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; + +public class DcaeEntityClient { + + protected Gson gson; + + public DcaeEntityClient() { + super(); + GsonBuilder gsonBuilder = new GsonBuilder(); + gsonBuilder.registerTypeAdapter(Requirement.class, new RequirementDeserializer()); + gsonBuilder.registerTypeAdapter(Value.class, new ValueDeserializer()); + gson = gsonBuilder.create(); + } + + /* VFCMT */ + + /** + * + * @param name + * @param description + * @param userId + * @return + * @throws Exception + */ + public Vfcmt createVfcmt(String name, String description, String userId) throws Exception { + RestResponse response = DcaeRestClient.createVfcmt(name, description, userId); + Report.log(Status.DEBUG, "Create VFCMT Response: " + StringUtils.truncate(response)); + if (response.getStatusCode() != 200) { + throw new Exception("Response: " + StringUtils.truncate(response)); + } + return gson.fromJson(response.getResponse(), Vfcmt.class); + } + + /** + * + * @param userId + * @return + * @throws Exception + */ + public Vfcmt createVfcmt(String userId) throws Exception { + String name = StringUtils.randomString("CI-", 20); + String description = "This vfcmt was created by automated ci tests"; + Vfcmt createVfcmt = createVfcmt(name, description, userId); + Report.log(Status.INFO, "createVfcmt result="+createVfcmt); + return createVfcmt; + } + + /** + * + * @return + * @throws Exception + */ + public Vfcmt createVfcmt() throws Exception { + return createVfcmt(DcaeRestClient.getDefaultUserId()); + } + + /** + * + * @return + * @throws Exception + */ + public Vfcmt[] getAllVfcmts() throws Exception { + Report.log(Status.INFO, "Fetching all vfcmt resources"); + RestResponse response = DcaeRestClient.getAllVfcmts(); + return convertResponseToVfcmt(response); + } + + public Vfcmt[] getAllBaseVfcmts() throws Exception { + Report.log(Status.INFO, "Fetching all vfcmt resources"); + RestResponse response = DcaeRestClient.getAllMonitoringTemplatesVfcmts(); + return convertResponseToVfcmt(response); + } + + private Vfcmt[] convertResponseToVfcmt(RestResponse response) throws Exception { + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + if (response.getStatusCode() != 200) { + throw new Exception("Response: " + StringUtils.truncate(response)); + } + return gson.fromJson(response.getResponse(), Vfcmt[].class); + } + + /** + * + * @param userId + * @return + * @throws Exception + */ + public Vfcmt createCheckedoutVfcmt(String userId) throws Exception { + Report.log(Status.INFO, "Creating vfcmt..."); + Vfcmt vfcmt = createVfcmt(userId); + if (vfcmt.getLifecycleState().equals(DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()) == false) { + throw new Exception("created vfcmt is not in checkout state!"); + } + return vfcmt; + } + + /** + * + * @return + * @throws Exception + */ + public Vfcmt createCheckedoutVfcmt() throws Exception { + String userId = DcaeRestClient.getDefaultUserId(); + Report.log(Status.INFO, "Going to create checked out VFCMT with user="+userId); + return createCheckedoutVfcmt(userId); + } + + /** + * + * @param userId + * @return + * @throws Exception + */ + public Vfcmt createCheckedinVfcmt(String userId) throws Exception { + Report.log(Status.INFO, "Creating vfcmt"); + Vfcmt vfcmt = createVfcmt(userId); + Report.log(Status.INFO, "Checkin the vfcmt"); + RestResponse response = DcaeRestClient.checkinVfcmt(vfcmt.getUuid(), vfcmt.getLastUpdaterUserId()); + Report.log(Status.DEBUG, "Response: " + StringUtils.truncate(response)); + Vfcmt vfcmtAfterCheckin = gson.fromJson(response.getResponse(), Vfcmt.class); + if (response.getStatusCode() != 200) { + throw new Exception("Unable to checkin newly created vfcmt"); + } + return vfcmtAfterCheckin; + } + + /** + * + * @return + * @throws Exception + */ + public Vfcmt createCheckedinVfcmt() throws Exception { + String userId = DcaeRestClient.getDefaultUserId(); + return createCheckedinVfcmt(userId); + } +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/DcaeRestClient.java b/src/main/java/org/onap/dcae/ci/utilities/DcaeRestClient.java new file mode 100644 index 0000000..1e45829 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/DcaeRestClient.java @@ -0,0 +1,263 @@ +package org.onap.dcae.ci.utilities; + + +import com.aventstack.extentreports.Status; +import com.google.common.net.UrlEscapers; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import org.json.simple.JSONObject; +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; + + +import java.io.IOException; + +public class DcaeRestClient extends BaseRestUtils { + + private static String designerDefaultId = "cs0008"; + private static String designer2UserId = "me0009"; + private static String adminDefaultId = "jh0003"; + private static String testerDefaultId = "jm0007"; + + public static String getDefaultUserId() { + return designerDefaultId; + } + + public static String getDesigner2UserId() { + return designer2UserId; + } + + public static String getDefaultAdminId() { + return adminDefaultId; + } + + public static String getDefaultTesterId() { + return testerDefaultId; + } + + protected static String getApiUrl(String path) { + Configuration configuration = ConfigurationReader.getConfiguration(); + + String dcaeBePort = configuration.getDcaeBePort(); + String dcaeBeHost = configuration.getDcaeBeHost(); + String apiPath = configuration.getApiPath(); + if(System.getProperty("dcaeBeHost")!=null){ + dcaeBeHost = System.getProperty("dcaeBeHost"); + System.out.println("dcaeBeHost was configured via system property: "+dcaeBeHost); + } + if(System.getProperty("dcaeBePort")!=null){ + dcaeBePort = System.getProperty("dcaeBePort"); + System.out.println("dcaeBePort was configured via system property: "+dcaeBePort); + } + if(System.getProperty("apiPath")!=null){ + apiPath = System.getProperty("apiPath"); + System.out.println("apiPath was configured via system property: "+apiPath); + } + + return String.format("%s:%s%s%s", dcaeBeHost, dcaeBePort, apiPath, path); + } + + /* HealthCheck */ + + public static RestResponse getHealthcheck() throws IOException { + return sendGet(getApiUrl("/healthCheck"), null); + } + + /* VFCMT */ + + public static RestResponse getAllVfcmts() throws IOException { + return sendGet(getApiUrl("/getResourcesByCategory"), designerDefaultId); + } + + public static RestResponse getAllMonitoringTemplatesVfcmts() throws IOException { + return sendGet(getApiUrl("/getResourcesByMonitoringTemplateCategory"), designerDefaultId); + } + + public static RestResponse getVfcmtsForMigration(String contextType,String serviceUuid, String serviceVersion) throws IOException{ + + return sendGet(getApiUrl("/" + contextType + "/" + serviceUuid + "/" + serviceVersion + "/getVfcmtsForMigration"), designerDefaultId); + } + + public static RestResponse createVfcmt(String name, String description, String userId) throws IOException { + JSONObject newVfcmtJSON = newVfcmtJSON(name, description); + return sendPost(getApiUrl("/createVFCMT"), newVfcmtJSON.toString(), userId, "application/json"); + } + + public static RestResponse createMc(String request) throws IOException { + return sendPost(getApiUrl("/createMC"), request, designerDefaultId, "application/json"); + } + + public static RestResponse createMc(String request,String userId) throws IOException { + return sendPost(getApiUrl("/createMC"), request, userId, "application/json"); + } + + public static RestResponse createVfcmt(String name, String description) throws IOException{ + return createVfcmt(name, description, designerDefaultId); + } + + public static RestResponse importMc(String request) throws IOException { + return sendPost(getApiUrl("/importMC"), request, designerDefaultId, "application/json"); + } + + public static RestResponse getAttachedService(String vfcmtUuid) throws IOException { + Report.log(Status.INFO, "getAttachedService for VFCMT uuid="+vfcmtUuid); + RestResponse res = sendGet(getApiUrl("/" + vfcmtUuid + "/attachment"), designerDefaultId); + Report.log(Status.INFO, "getAttachedService result=%s", res); + return res; + } + + public static RestResponse getServiceExternalReferences(String serviceUuid, String version) throws IOException { + Report.log(Status.INFO, "getServiceExternalReferences for service uuid="+serviceUuid); + RestResponse res = sendGet(getApiUrl("/SERVICE/" + serviceUuid + "/" + version + "/monitoringComponents"), designerDefaultId); + Report.log(Status.INFO, "getServiceExternalReferences result=%s", res); + return res; + } + /* VF */ + + public static RestResponse getServices(String VFCMTId, String userId) throws IOException{ + return sendGet(getApiUrl("/services/"+VFCMTId), userId); + } + + public static RestResponse getServicesInstance(String uuid) throws IOException{ + return sendGet(getApiUrl("/service/"+uuid), designerDefaultId); + } + + public static RestResponse attachVfiRef(String vfcmtUuid, String serviceId, String vfiName) throws IOException{ + Report.log(Status.INFO, "attachVfiRef start"); + JSONObject jsonAttachObj = new JSONObject(); + jsonAttachObj.put("serviceUuid", serviceId); + jsonAttachObj.put("instanceName", vfiName); + + return sendPost(getApiUrl("/" + vfcmtUuid + "/attachment"), jsonAttachObj.toString(), designerDefaultId, "application/json"); + } + + public static RestResponse getResourceDetails(String componentId) throws IOException{ + return sendGet(getApiUrl("/resource/"+ componentId), designerDefaultId); + } + + public static RestResponse getElements() throws IOException{ + return sendGet(getApiUrl("/elements"), designerDefaultId); + } + public static RestResponse getItem(String element) throws IOException{ + return sendGet(getApiUrl("/"+ element +"/elements"), designerDefaultId); + } + public static RestResponse getItemModel(String elementId) throws IOException{ + return sendGet(getApiUrl("/"+ elementId +"/model"), designerDefaultId); + } + public static RestResponse getItemType(String elementId, String type) throws IOException{ + return sendGet(getApiUrl("/"+ elementId +"/type/"+ type +"/"), designerDefaultId); + } + public static RestResponse saveComposition(String componentId, String userId) throws IOException{ + JsonObject json = generateCdumpInput(componentId); + return saveComposition(componentId, userId, json.toString()); + } + + // edit composition new flow - service context + public static RestResponse saveComposition(String serviceUuid, String vfiName, String vfcmtUuid, String body) throws IOException{ + return sendPost(getApiUrl(String.format("/service/%s/%s/saveComposition/%s", serviceUuid, UrlEscapers.urlFragmentEscaper().escape(vfiName), vfcmtUuid)), body, designerDefaultId, "application/json"); + } + + // submit composition new flow - service context + public static RestResponse submitComposition(String serviceUuid, String vfiName, String vfcmtUuid) throws IOException { + return sendPost(getApiUrl(String.format("/service/createBluePrint/%s/%s/%s", vfcmtUuid, serviceUuid, UrlEscapers.urlFragmentEscaper().escape(vfiName))), "", designerDefaultId, "application/json"); + } + + public static RestResponse saveComposition(String componentId, String userId, String body) throws IOException{ + return sendPost(getApiUrl("/saveComposition/"+componentId), body, userId, "application/json"); + } + + public static RestResponse getComposition(String componentId) throws IOException{ + return sendGet(getApiUrl("/getComposition/"+ componentId), designerDefaultId); + } + public static RestResponse submitComposition(String componentId, String serviceUuid, String vnfiName, String monitoringType) throws IOException{ + return sendPost(getApiUrl("/createBluePrint/"+ componentId +"/"+ serviceUuid +"/"+ UrlEscapers.urlFragmentEscaper().escape(vnfiName) + "/"+ UrlEscapers.urlFragmentEscaper().escape(monitoringType)), "" ,designerDefaultId, "application/json"); + } + + /* Life Cycle */ + + public static RestResponse checkinVfcmt(String vfcmtUuid, String userId) throws IOException { + return checkinGeneral("vfcmt", vfcmtUuid, userId); + } + + public static RestResponse checkinGeneral(String assetType, String vfcmtUuid, String userId) throws IOException { + return sendPut(getApiUrl(String.format("/checkin/%s/%s", assetType, vfcmtUuid)), null, userId, null); + } + + public static RestResponse checkoutVfcmt(String vfcmtUuid, String userId) throws IOException { + return checkoutGeneral("vfcmt", vfcmtUuid, userId); + } + + private static RestResponse checkoutGeneral(String assetType, String vfcmtUuid, String userId) throws IOException { + return sendPut(getApiUrl(String.format("/checkout/%s/%s", assetType, vfcmtUuid)), null, userId, null); + } + + public static RestResponse certifyVfcmt(String vfcmtUuid, String userId) throws IOException { + return sendPut(getApiUrl(String.format("/certify/vfcmt/%s", vfcmtUuid)), null, userId, null); + } + + /* Rule Editor */ + + public static RestResponse getVesEventTypes() throws IOException { + return sendGet(getApiUrl("/rule-editor/list-events-by-versions"), designerDefaultId); + } + + public static RestResponse getVesDataTypes(String vesVersion, String eventType) throws IOException { + return sendGet(getApiUrl(String.format("/rule-editor/definition/%s/%s", vesVersion, eventType)), designerDefaultId); + } + + public static RestResponse saveRule(String vfcmtUid, String dcaeCompName, String nid, String configParam, String body) throws IOException { + return sendPost(getApiUrl(String.format("/rule-editor/rule/%s/%s/%s/%s", vfcmtUid, dcaeCompName, nid, configParam)), body, designerDefaultId, "application/json" ); + } + + public static RestResponse getRules(String vfcmtUid, String dcaeCompName, String nid, String configParam) throws IOException { + return sendGet(getApiUrl(String.format("/rule-editor/rule/%s/%s/%s/%s", vfcmtUid, dcaeCompName, nid, configParam)), designerDefaultId); + } + + public static RestResponse deleteRule(String vfcmtUid, String dcaeCompName, String nid, String configParam, String ruleUid) throws IOException { + return sendDelete(getApiUrl(String.format("/rule-editor/rule/%s/%s/%s/%s/%s", vfcmtUid, dcaeCompName, nid, configParam, ruleUid)), designerDefaultId); + } + + public static RestResponse translateRules(String vfcmtUid, String dcaeCompName, String nid, String configParam, String flowType) throws IOException { + return sendGet(getApiUrl(String.format("/rule-editor/rule/translate/%s/%s/%s/%s?flowType=%s", vfcmtUid, dcaeCompName, nid, configParam, flowType)), designerDefaultId); + } + + public static RestResponse getExistingRuleTargets(String vfcmtUuid, String dcaeCompName, String nid) throws IOException { + String url = getApiUrl(String.format("/rule-editor/getExistingRuleTargets/%s/%s/%s", vfcmtUuid, dcaeCompName, nid)); + return sendGet(url, designerDefaultId); + } + + + private static JSONObject newVfcmtJSON(String name, String description) { + JSONObject json = new JSONObject(); + json.put("name", name); + json.put("description", description); + return json; + } + + public static <T extends CreateVFCMTRequest> void fillCreateMcRequestMandatoryFields(T request) { + request.setFlowType("flowType_xxx"); + request.setContextType("SERVICE"); + request.setName(StringUtils.randomString("CI-", 20)); + request.setDescription("create test vfcmt"); + if(null == request.getVfiName()) { + request.setVfiName("whatsInAName"); + } + if(null == request.getServiceUuid()) { + request.setServiceUuid("service5659860"); + } + } + + public static JsonObject generateCdumpInput(String componentId) { + JsonObject json = new JsonObject(); + json.addProperty("cid", componentId); + json.addProperty("version", 0); + json.add("nodes", new JsonArray()); + json.add("relations", new JsonArray()); + json.add("inputs", new JsonArray()); + json.add("outputs", new JsonArray()); + return json; + + } +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/DcaeTestConstants.java b/src/main/java/org/onap/dcae/ci/utilities/DcaeTestConstants.java new file mode 100644 index 0000000..6bca647 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/DcaeTestConstants.java @@ -0,0 +1,19 @@ +package org.onap.dcae.ci.utilities; + +public class DcaeTestConstants { + + public class Composition{ + public static final String Microservice = "Microservice"; + public static final String EMPTY_OBJECT = "{}"; + } + + public class Sdc{ + public class State{ + public static final String NOT_CERTIFIED_CHECKOUT = "NOT_CERTIFIED_CHECKOUT"; + public static final String NOT_CERTIFIED_CHECKIN = "NOT_CERTIFIED_CHECKIN"; + public static final String CONFLICT = "Conflict"; + public static final String CERTIFIED = "CERTIFIED"; + + } + } +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/DcaeUtil.java b/src/main/java/org/onap/dcae/ci/utilities/DcaeUtil.java new file mode 100644 index 0000000..5d6eff4 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/DcaeUtil.java @@ -0,0 +1,205 @@ +package org.onap.dcae.ci.utilities; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import com.google.gson.*; +import org.apache.commons.lang3.RandomStringUtils; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.json.simple.parser.ParseException; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.entities.composition.items.DcaeComponents; +import org.onap.dcae.ci.report.Report; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.testng.Assert; + +import org.onap.sdc.dcae.composition.services.Resource; +import org.onap.sdc.dcae.composition.services.Service; +import org.onap.sdc.dcae.composition.services.ThinService; +import org.onap.sdc.dcae.composition.vfcmt.Vfcmt; +import com.aventstack.extentreports.Status; + + +public class DcaeUtil { + public static Gson gson = new Gson(); + + public static class CatalogReources { + public static Vfcmt[] getAllReourcesFromAsdc() throws IOException{ + RestResponse allResources = DcaeRestClient.getAllVfcmts(); + return gson.fromJson(allResources.getResponse(), Vfcmt[].class); + } + + public static Vfcmt getResourceByName(String resName) throws IOException{ + Vfcmt[] vfcmts = getAllReourcesFromAsdc(); + List<Vfcmt> vfcmtsStr = Arrays.stream(vfcmts). + filter(item -> item.getName().equals(resName)). + collect(Collectors.toList()); + + return vfcmtsStr.get(0); + } + + public static Vfcmt getOneResourceFromList(int index) throws IOException{ + Vfcmt[] vfcmtList = getAllReourcesFromAsdc(); + return vfcmtList[index]; + } + + public static String getComponentID(int index) throws IOException{ + Vfcmt vfcmt = getOneResourceFromList(0); + return vfcmt.getUuid(); + } + + public static Resource createNewVfcmtObject() throws IOException{ + Resource res = new Resource(); + res.setResourceInstanceName("LiavNewVFCMT" + RandomStringUtils.randomAlphanumeric(20)); + res.setDescription("This is a test VFCMT"); + return res; + } + + public static Vfcmt notCheckoutVFCMT() throws IOException{ /* TODO: remove this function and use instead in DcaeEntityClient.getCheckedoutVfcmt() */ + Vfcmt[] vfcmtList = getAllReourcesFromAsdc(); + List<Vfcmt> vfcmtsStr = Arrays.stream(vfcmtList). + filter(item -> (item.getLifecycleState().equals(DcaeTestConstants.Sdc.State.NOT_CERTIFIED_CHECKOUT) == false)). + collect(Collectors.toList()); + + return vfcmtsStr.get(0); + } + + public static Vfcmt vfcmtNotUserOwner(String user) throws IOException{ + Vfcmt[] vfcmtList = getAllReourcesFromAsdc(); + List<Vfcmt> vfcmtsStr = Arrays.stream(vfcmtList) + .filter(item -> (item.getLastUpdaterUserId().equals(user) == false)) + .collect(Collectors.toList()); + + return vfcmtsStr.get(0); + } + + } + + public static class Services{ + public static ThinService[] getServices(String VFCMTId, String userId) throws IOException{ + RestResponse services = null; + try{ + services = DcaeRestClient.getServices(VFCMTId, userId); + }catch(Exception e){ + System.err.println("Exception occurred while trying to fetch all resources from SDC: "+e); + return null; + } + Assert.assertTrue(services.getStatusCode().intValue() == 200); + String response = services.getResponse(); + ThinService[] serviceList = gson.fromJson(response, ThinService[].class); + return serviceList.length > 0 ? serviceList : null; + } + + public static ThinService getOneService(String VFCMTId,int index, String userId) throws IOException { + ThinService[] services = getServices(VFCMTId, userId); + return services[index]; + } + + + public static List<Resource> getVfListInstance(ThinService thinService) throws IOException { + RestResponse serviceInstancRes = null; + try{ + serviceInstancRes = DcaeRestClient.getServicesInstance(thinService.getUuid()); + }catch(Exception e){ + System.err.println("Exception occurred while trying to fetch List of VF instances from SDC service ("+thinService+"). Exception: "+e); + return null; + } + Assert.assertTrue(serviceInstancRes.getStatusCode().intValue() == 200); + String serviceInstancList = serviceInstancRes.getResponse(); + Service service = gson.fromJson(serviceInstancList, Service.class); + return service.getResources(); + } + + public static Resource getOneVfInstance(ThinService thinService,int index) throws IOException { + List<Resource> resources = getVfListInstance(thinService); + return resources.get(index); + } + + } + + + public static class SdcElementsModelType{ + public static RestResponse getMsElements() throws IOException{ + return DcaeRestClient.getItem(DcaeTestConstants.Composition.Microservice); + } + + + + public static JsonArray getSNMPModelItemFromSdc() throws Exception { + RestResponse resMsElements = getMsElements(); + JsonParser jsonParser = new JsonParser(); + JsonObject responseJson = (JsonObject)jsonParser.parse(resMsElements.getResponse()); + JsonArray itemJsonArray = responseJson.get("data").getAsJsonObject().get("element").getAsJsonObject().get("items").getAsJsonArray(); + Report.logDebug("DCAE Components items", itemJsonArray); + Service[] services = gson.fromJson(itemJsonArray, Service[].class); + Report.log(Status.DEBUG, "Trying to find a certified VF which its name starts with supplement/map/enrich"); + List<String> collectIds = Arrays.stream(services) + .filter(x -> DcaeBeConstants.LifecycleStateEnum.CERTIFIED == DcaeBeConstants.LifecycleStateEnum.valueOf(x.getLifecycleState())&& !x.getModels().isEmpty()) + .filter(x -> x.getName().toLowerCase().startsWith("supplement") || x.getName().toLowerCase().startsWith("map") || x.getName().toLowerCase().startsWith("enrich")) + .map(Service::getUuid) + .collect(Collectors.toList()); + if(collectIds.isEmpty()) { + Report.log(Status.WARNING, "Could not find any SNMP DCAE Component"); + } + JsonArray models = new JsonArray(); + for (String id : collectIds) { + RestResponse res = DcaeRestClient.getItemModel(id); + models.addAll(parseNodesFromDcaeModelAndAssignUiNid(res.getResponse())); + } + + return models; + } + + public static RestResponse getItemModelFromSdc(int itemNumber) throws IOException{ + String uuid = getItemUuid(itemNumber); + return DcaeRestClient.getItemModel(uuid); + } + + public static String getItemUuid(int itemNumber) throws IOException{ + DcaeComponents dcaeComponents = getDcaeComponents(); + return dcaeComponents.getData().getElement().getItems().get(itemNumber).getUuid(); + } + + public static DcaeComponents getDcaeComponents() throws IOException{ + RestResponse services = getMsElements(); + String response = services.getResponse(); + return gson.fromJson(response, DcaeComponents.class); + } + } + + public static JsonArray parseNodesFromDcaeModelAndAssignUiNid(String response) throws ParseException { + JsonParser parser = new JsonParser(); + JsonObject data = parser.parse(response).getAsJsonObject().get("data").getAsJsonObject(); + JsonObject model = data.get("model").getAsJsonObject(); + JsonArray nodes = model.get("nodes").getAsJsonArray(); + nodes.forEach((n) -> + n.getAsJsonObject().add("nid", n.getAsJsonObject().get("name")) + ); + Report.logDebug("nodes after adding ui nid", nodes); + return nodes; + } + + public static String generateCdumpFromSnmpModels(String vfcmtId) throws Exception { + JsonArray snmpModelItemFromSdc = SdcElementsModelType.getSNMPModelItemFromSdc(); + JsonObject cdump = DcaeRestClient.generateCdumpInput(vfcmtId); + cdump.add("nodes", snmpModelItemFromSdc); + Report.logDebug("cdump", cdump); + return cdump.toString(); + } + + public static String getValueFromJsonResponse(String response, String fieldName) { + try { + JSONObject jsonResp = (JSONObject) JSONValue.parse(response); + Object fieldValue = jsonResp.get(fieldName); + return fieldValue.toString(); + + } catch (Exception e) { + return null; + } + + } +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/HttpRequest.java b/src/main/java/org/onap/dcae/ci/utilities/HttpRequest.java new file mode 100644 index 0000000..3b58109 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/HttpRequest.java @@ -0,0 +1,305 @@ +package org.onap.dcae.ci.utilities; + +import org.apache.commons.io.IOUtils; +import org.onap.dcae.ci.entities.RestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +public class HttpRequest { + private static final Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName()); + + public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + url = url.replaceAll("\\s", "%20"); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + // optional default is GET + con.setRequestMethod("GET"); + // add request header + if (headers != null) { + for (Entry<String, String> header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + int responseCode = con.getResponseCode(); + logger.debug("Send GET http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + String result; + + try { + + result = IOUtils.toString(con.getInputStream()); + response.append(result); + + } catch (Exception e) { + } + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e) { + } + + logger.debug("Response body: {}" ,response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setStatusCode(responseCode); + Map<String, List<String>> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + + + public RestResponse httpSendByMethod(String url, String method, String body, Map<String, String> headers) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(method); + + // add request headers + if (headers != null) { + for (Entry<String, String> header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + if (body != null && !body.isEmpty() && !method.equals("DELETE")) { + // Send post request + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + + int responseCode = con.getResponseCode(); + logger.debug("Send {} http request, url: {}",method,url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + Map<String, List<String>> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + + + public RestResponse httpSendPost(String url, String body, Map<String, String> headers) throws IOException { + return httpSendPost(url, body, headers, "POST"); + } + + + public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType) + throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + // add request method + con.setRequestMethod(methodType); + + // add request headers + if (headers != null) { + for (Entry<String, String> header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + } + + // Send post request + if (body != null) { + con.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(con.getOutputStream()); + wr.writeBytes(body); + wr.flush(); + wr.close(); + } + + int responseCode = con.getResponseCode(); + logger.debug("Send POST http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + Map<String, List<String>> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + return restResponse; + + } + + + public RestResponse httpSendDelete(String url, Map<String, String> headers) throws IOException { + + RestResponse restResponse = new RestResponse(); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + if (headers != null) { + for (Entry<String, String> header : headers.entrySet()) { + String key = header.getKey(); + String value = header.getValue(); + con.setRequestProperty(key, value); + } + + } + + con.setDoOutput(true); + con.setRequestMethod("DELETE"); + int responseCode = con.getResponseCode(); + logger.debug("Send DELETE http request, url: {}",url); + logger.debug("Response Code: {}",responseCode); + + StringBuffer response = new StringBuffer(); + + try { + BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } catch (Exception e) { + logger.debug("response body is null"); + } + + String result; + + try { + + result = IOUtils.toString(con.getErrorStream()); + response.append(result); + + } catch (Exception e2) { + result = null; + } + logger.debug("Response body: {}",response); + + // print result + + restResponse.setStatusCode(responseCode); + + if (response != null) { + restResponse.setResponse(response.toString()); + } + + restResponse.setStatusCode(con.getResponseCode()); + Map<String, List<String>> headerFields = con.getHeaderFields(); + restResponse.setHeaderFields(headerFields); + String responseMessage = con.getResponseMessage(); + restResponse.setResponseMessage(responseMessage); + + con.disconnect(); + + return restResponse; + } + +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/SdcInternalApiClient.java b/src/main/java/org/onap/dcae/ci/utilities/SdcInternalApiClient.java new file mode 100644 index 0000000..3010de0 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/SdcInternalApiClient.java @@ -0,0 +1,107 @@ +package org.onap.dcae.ci.utilities; + +import com.aventstack.extentreports.Status; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.entities.RestResponse; +import org.onap.dcae.ci.entities.composition.services.Vfi; +import org.onap.dcae.ci.entities.sdc.*; +import org.onap.dcae.ci.report.Report; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SdcInternalApiClient extends BaseRestUtils { + + private static Gson gson = (new GsonBuilder()).create(); + private static String defaultUserId = DcaeRestClient.getDefaultUserId(); + private static String adminUserId = DcaeRestClient.getDefaultAdminId(); + private static Configuration configuration = ConfigurationReader.getConfiguration(); + + + public static SdcService createService() throws IOException { + String url = getApiUrl("services"); + SdcService service = SdcComponentFactory.getDefaultService(); + Report.log(Status.INFO, "Going to create service with name " + service.getName()); + String serviceBodyJson = gson.toJson(service); + RestResponse res = sendPost(url, serviceBodyJson, defaultUserId, acceptHeaderData); + Report.logDebug("Response:", res); + assertThat(res.getStatusCode()).isEqualTo(201); + return gson.fromJson(res.getResponse(), SdcService.class); + } + + + public static SdcResource createVf() throws IOException { + String url = getApiUrl("resources"); + SdcResource defaultVf = SdcComponentFactory.getDefaultResource(); + String resourceBodyJson = gson.toJson(defaultVf); + RestResponse res = sendPost(url, resourceBodyJson, defaultUserId, acceptHeaderData); + Report.logDebug("Response:", res); + assertThat(res.getStatusCode()).isEqualTo(201); + return gson.fromJson(res.getResponse(), SdcResource.class); + } + + + public static SdcResource checkinVf(SdcResource vf) throws IOException { + RestResponse response = changeResourceLifeCycleState(vf.getUniqueId(), "checkin"); + Report.logDebug("Response:", response); + assertThat(response.getStatusCode()).isEqualTo(200); + return gson.fromJson(response.getResponse(), SdcResource.class); + } + + + public static Vfi createVfi(SdcService service, SdcResource vf) throws IOException { + String url = getApiUrl(String.format("services/%s/resourceInstance", service.getUniqueId())); + SdcComponentInstance vfi = new SdcComponentInstance(vf); + String requestBodyJson = gson.toJson(vfi); + RestResponse createResourceInstance = sendPost(url, requestBodyJson, defaultUserId, acceptHeaderData); + Report.logDebug("Response:", createResourceInstance); + assertThat(createResourceInstance.getStatusCode()).isEqualTo(201); + return new Vfi(DcaeUtil.getValueFromJsonResponse(createResourceInstance.getResponse(), "name"), service); + } + + + public static RestResponse changeResourceLifeCycleState(String assetUniqueId, String lifeCycleOperation) throws IOException { + String url = getApiUrl(String.format("resources/%s/lifecycleState/%s", assetUniqueId, lifeCycleOperation)); + return sendPost(url, "{\"userRemarks\":\"Ci lifecycle operation\"}", defaultUserId, acceptHeaderData); + } + + + // DELETE - Clean up // + + public static RestResponse deleteAssetFromSdc(String context, String uniqueId) throws IOException { + String url = getApiUrl(String.format("%s/%s", context, uniqueId)); + return sendDelete(url, adminUserId); + } + + public static RestResponse deleteMarkedResources() throws IOException { + + String url = String.format("%s:%s/sdc2/rest/v1/inactiveComponents/resource", configuration.getBeHost(), configuration.getBePort()); + return sendDelete(url, adminUserId); + } + + public static RestResponse deleteMarkedServices() throws IOException { + String url = String.format("%s:%s/sdc2/rest/v1/inactiveComponents/service", configuration.getBeHost(), configuration.getBePort()); + return sendDelete(url, adminUserId); + } + + public static Map<String, List<SdcComponent>> getAssetsByUser(String userId) throws IOException { + String url = String.format("%s:%s/sdc2/rest/v1/followed", configuration.getBeHost(), configuration.getBePort()); + RestResponse restResponse = sendGet(url, userId); + return 200 == restResponse.getStatusCode() ? gson.fromJson(restResponse.getResponse(), new TypeToken<Map<String, List<SdcComponent>>>(){}.getType()) : new HashMap<>(); + } + + + public static SdcComponentMetadata getAssetMetadata(String context, String uniqueId, String userId) throws IOException { + String url = getApiUrl(String.format("%s/%s/filteredDataByParams?include=metadata", context, uniqueId)); + RestResponse restResponse = sendGet(url, userId); + return gson.fromJson(restResponse.getResponse(), SdcComponentMetadata.class); + } + +} diff --git a/src/main/java/org/onap/dcae/ci/utilities/SetupReport.java b/src/main/java/org/onap/dcae/ci/utilities/SetupReport.java new file mode 100644 index 0000000..dd797f2 --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/SetupReport.java @@ -0,0 +1,131 @@ +package org.onap.dcae.ci.utilities; + + +import org.onap.dcae.ci.config.Configuration; +import org.onap.dcae.ci.report.ExtentManager; +import org.onap.dcae.ci.report.ExtentTestManager; +import org.onap.dcae.ci.report.Report; +import org.testng.ITestContext; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; + +import java.lang.reflect.Method; + +public abstract class SetupReport { + public static final String TESTNG_FAILED_XML_NAME = "testng-failed.xml"; + private static Method myMethod; + private static Configuration configuration; + + public SetupReport() { + try { + configuration = this.getEnvConfiguration(); + } catch (Exception var2) { + var2.printStackTrace(); + } + + } + + protected abstract Configuration getEnvConfiguration(); + + @BeforeSuite( + alwaysRun = true + ) + public void beforeSuiteStarts(ITestContext context) { + this.initReport(context); + } + + @BeforeMethod( + alwaysRun = true + ) + public void beforeTestStarts(Method method, Object[] testArgs) { + myMethod = method; + this.initTestReporting(testArgs); + } + + @AfterMethod( + alwaysRun = true + ) + public void afterTestEnds(ITestResult result) { + this.reportTestResult(result); + this.closeTestReporting(); + this.closeReport(); + } + + public static Configuration getConfiguration() { + return configuration; + } + + private void initReport(ITestContext context) { + try { + ExtentManager.initReporter(this.getEnvConfiguration(), context); + } catch (Exception var3) { + var3.printStackTrace(); + } + + } + + private void initTestReporting(Object[] testArgs) { + if(this.isDataProviderEmpty(testArgs)) { + this.startTest(); + } else { + this.startTest(this.getDataProviderValues(testArgs)); + } + + } + + private boolean isDataProviderEmpty(Object[] testArgs) { + return testArgs.length == 0; + } + + private String getDataProviderValues(Object[] testArgs) { + StringBuilder sb = new StringBuilder(); + Object[] var3 = testArgs; + int var4 = testArgs.length; + + for(int var5 = 0; var5 < var4; ++var5) { + Object arg = var3[var5]; + sb.append(arg); + sb.append(" "); + } + + return sb.toString().trim(); + } + + private void reportTestResult(ITestResult result) { + Report.report(result); + } + + private void closeTestReporting() { + ExtentTestManager.endTest(); + } + + private void closeReport() { + ExtentManager.closeReporter(); + } + + private void startTest(String fromDataProvider) { + String suiteName = ExtentManager.getSuiteName(); + String methodName = this.getFullMethodName(fromDataProvider); + if(suiteName != null) { + if(suiteName.equals("testng-failed.xml")) { + ExtentTestManager.startTest("<html><font color=\"red\">ReRun - </font></html>" + methodName); + } else { + ExtentTestManager.startTest(methodName); + } + + ExtentTestManager.assignCategory(this.getClass()); + } + + } + + private void startTest() { + this.startTest(""); + } + + private String getFullMethodName(String fromDataProvider) { + return fromDataProvider.equals("")?myMethod.getName():myMethod.getName() + " " + fromDataProvider; + } +} + diff --git a/src/main/java/org/onap/dcae/ci/utilities/StringUtils.java b/src/main/java/org/onap/dcae/ci/utilities/StringUtils.java new file mode 100644 index 0000000..b57dcab --- /dev/null +++ b/src/main/java/org/onap/dcae/ci/utilities/StringUtils.java @@ -0,0 +1,16 @@ +package org.onap.dcae.ci.utilities; + +import org.apache.commons.lang3.RandomStringUtils; + +import com.google.common.base.Ascii; + +public class StringUtils { + + public static String randomString(String prefix, int length) { + return prefix + RandomStringUtils.randomAlphanumeric(length - prefix.length()); + } + + public static String truncate(Object obj) { + return Ascii.truncate(obj.toString(), 160, "..."); + } +} |