aboutsummaryrefslogtreecommitdiffstats
path: root/asdc-tests/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'asdc-tests/src/main/java')
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java348
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java763
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java202
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java348
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java584
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java63
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java135
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java226
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java272
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java332
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java145
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java58
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java89
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java116
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java220
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java337
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java91
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java267
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java57
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java75
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java42
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java51
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java40
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java37
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java93
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java64
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java36
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java95
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java75
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java66
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java55
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java105
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java56
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java60
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java40
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java37
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java76
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java166
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java90
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java151
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java79
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java179
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java88
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java121
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java142
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java300
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java98
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java114
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java38
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java58
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java883
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java84
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java135
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java656
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java1750
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java687
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java696
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java631
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java444
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java176
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java83
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java234
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java49
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java2289
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java147
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java2003
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java1907
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java1011
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java356
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java103
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java578
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java186
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java542
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java338
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java403
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java1388
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java104
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java430
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java333
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java1538
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java599
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java1431
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java416
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java2404
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java282
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java225
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java274
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java1478
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java195
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java199
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java146
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java1437
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java1710
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java2197
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java164
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java54
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java148
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java83
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java216
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java2021
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java1263
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java1796
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java383
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java52
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java1408
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java2199
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java580
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java326
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java366
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java41
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java102
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java2254
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java480
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java315
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java1792
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java1008
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java1300
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java350
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java322
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java684
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java1191
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java1624
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java1984
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java832
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java1451
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java354
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java141
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java177
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java125
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java96
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java82
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java94
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java293
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java410
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java220
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java126
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java25
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java74
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java78
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java59
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java25
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java83
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java54
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java53
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java72
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java77
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java113
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java133
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java59
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java48
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java74
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java43
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java306
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java62
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java630
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java267
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java233
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java213
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java172
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java627
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java309
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java873
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java136
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java56
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java689
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java510
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java256
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java75
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java298
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java276
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java62
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java206
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java255
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java61
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java339
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java122
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java360
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java185
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java310
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java575
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java541
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java262
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java282
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java228
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java1328
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java116
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java126
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java274
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java112
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java239
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java354
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java130
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java279
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java111
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java351
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java438
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java773
-rw-r--r--asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java69
210 files changed, 85857 insertions, 0 deletions
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
new file mode 100644
index 0000000000..370c195f53
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java
@@ -0,0 +1,348 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.api;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import com.thinkaurelius.titan.core.TitanGraphQuery;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.tinkerpop.gremlin.structure.Direction;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
+import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
+import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.ITestResult;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.BeforeSuite;
+
+import com.relevantcodes.extentreports.ExtentReports;
+import com.relevantcodes.extentreports.ExtentTest;
+import com.relevantcodes.extentreports.LogStatus;
+import com.thinkaurelius.titan.core.TitanFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.LoggerContext;
+
+public abstract class ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
+
+ // public ComponentBaseTest(TestName testName, String className) {
+ // super(testName, className);
+ // }
+
+ protected static ExtentReports extentReport;
+ protected static ExtentTest extendTest;
+ public static final String REPORT_FOLDER = "./ExtentReport/";
+ private static final String REPORT_FILE_NAME = "ASDC_CI_Extent_Report.html";
+ protected static TitanGraph titanGraph;
+ private static Config myconfig;
+ public static Config config;
+
+ public static enum ComponentOperationEnum {
+ CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
+ };
+
+ public ComponentBaseTest(TestName name, String name2) {
+ // TODO Auto-generated constructor stub
+ LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
+ lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
+ lc.getLogger("com.datastax").setLevel(Level.INFO);
+ lc.getLogger("io.netty").setLevel(Level.INFO);
+ lc.getLogger("c.d").setLevel(Level.INFO);
+ }
+
+ @BeforeSuite(alwaysRun = true)
+ public static void openTitan() throws FileNotFoundException {
+
+ File dir = new File(REPORT_FOLDER);
+ try {
+ FileUtils.deleteDirectory(dir);
+ } catch (IOException e) {
+ }
+ extentReport = new ExtentReports(REPORT_FOLDER + REPORT_FILE_NAME);
+
+ myconfig = Utils.getConfig();
+ config = Utils.getConfig();
+ logger.trace(config.toString());
+ String titanConfigFilePath = myconfig.getTitanPropertiesFile();
+ System.out.println("titan configuration path:\n"+titanConfigFilePath);
+ titanGraph = TitanFactory.open(titanConfigFilePath);
+ System.out.println("is open:\n"+titanGraph.isOpen());
+ assertNotNull(titanGraph);
+ }
+
+ @AfterSuite(alwaysRun = true)
+ public static void shutdownTitan() {
+ if (titanGraph.isOpen()) {
+ titanGraph.close();
+ }
+ CassandraUtils.close();
+ }
+
+ @BeforeMethod(alwaysRun = true)
+ public void beforeState(java.lang.reflect.Method method) throws Exception {
+
+ cleanComponents();
+ CassandraUtils.truncateAllKeyspaces();
+ extendTest = extentReport.startTest(method.getName());
+ extendTest.log(LogStatus.INFO, "Test started");
+
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void afterState(ITestResult result) throws Exception {
+ cleanComponents();
+ CassandraUtils.truncateAllKeyspaces();
+
+ if (result.isSuccess()) {
+ extendTest.log(LogStatus.PASS, "Test Result : <span class='label success'>Success</span>");
+ } else {
+ extendTest.log(LogStatus.ERROR, "ERROR - The following exepction occured");
+ extendTest.log(LogStatus.ERROR, result.getThrowable());
+ extendTest.log(LogStatus.FAIL, "<span class='label failure'>Failure</span>");
+ }
+
+ extentReport.endTest(extendTest);
+ extentReport.flush();
+
+ }
+
+ public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
+ assertNotNull("check response object is not null after " + action, response);
+ assertNotNull("check error code exists in response after " + action, response.getErrorCode());
+ assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
+ }
+
+ private void cleanComponents() throws Exception {
+
+ // Components to delete
+ List<String> vfResourcesToDelete = new ArrayList<String>();
+ List<String> nonVfResourcesToDelete = new ArrayList<String>();
+ List<String> servicesToDelete = new ArrayList<String>();
+ List<String> productsToDelete = new ArrayList<String>();
+
+ // Categories to delete
+ List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
+ List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
+ List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
+ List<String> productCategoriesToDelete = new ArrayList<>();
+ List<String> resourceCategoriesToDelete = new ArrayList<String>();
+ List<String> serviceCategoriesToDelete = new ArrayList<String>();
+
+ List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
+ List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
+ List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
+ TitanGraphQuery<? extends TitanGraphQuery> query = titanGraph.query();
+ query = query.has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName());
+ Iterable<TitanVertex> vertices=query.vertices();
+// Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex vertex = iter.next();
+ Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
+ // if (!isAbstract) {
+ String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
+ String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
+
+ if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
+ String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
+ // if (name.startsWith("ci")) {
+ if (resourceType.equals(ResourceTypeEnum.VF.name())) {
+ vfResourcesToDelete.add(id);
+ } else {
+ nonVfResourcesToDelete.add(id);
+ }
+ // }
+ } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
+ if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
+ vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
+ }
+ }
+ // }
+ }
+ }
+ vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex vertex = iter.next();
+ String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
+ // if (name.startsWith("ci")){
+ servicesToDelete.add(id);
+ // }
+ }
+ }
+
+ vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex vertex = iter.next();
+ String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
+ //if (name.startsWith("ci")) {
+ productsToDelete.add(id);
+ //}
+ }
+ }
+
+ // Getting categories
+
+ vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex category = iter.next();
+ String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
+ if (!resourceCategoriesNotToDelete.contains(name)) {
+ String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ resourceCategoriesToDelete.add(catId);
+ Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
+ while (subs.hasNext()) {
+ Vertex sub = subs.next();
+ String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
+ }
+ }
+ }
+ }
+
+ vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex category = iter.next();
+ String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
+ if (!serviceCategoriesNotToDelete.contains(name)) {
+ String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ serviceCategoriesToDelete.add(id);
+ }
+ }
+ }
+
+ vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
+ if (vertices != null) {
+ Iterator<TitanVertex> iter = vertices.iterator();
+ while (iter.hasNext()) {
+ Vertex category = iter.next();
+ String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ productCategoriesToDelete.add(catId);
+ Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
+ while (subs.hasNext()) {
+ Vertex sub = subs.next();
+ String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
+ Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
+ while (groupings.hasNext()) {
+ Vertex grouping = groupings.next();
+ String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
+ productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
+ }
+ }
+
+ }
+ }
+
+ titanGraph.tx().commit();
+
+ String adminId = UserRoleEnum.ADMIN.getUserId();
+ String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
+
+ // Component delete
+ for (String id : productsToDelete) {
+ RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
+
+ }
+ for (String id : servicesToDelete) {
+ RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
+
+ }
+ for (String id : vfResourcesToDelete) {
+ RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
+
+ }
+
+ for (String id : nonVfResourcesToDelete) {
+ RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
+
+ }
+
+ // Categories delete - product
+ String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
+ for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
+ CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
+ }
+ for (ImmutablePair<String, String> pair : productSubsToDelete) {
+ CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
+ }
+ for (String id : productCategoriesToDelete) {
+ CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
+ }
+
+ // Categories delete - resource
+ componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
+ for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
+ CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
+ }
+ for (String id : resourceCategoriesToDelete) {
+ CategoryRestUtils.deleteCategory(id, adminId, componentType);
+ }
+ // Categories delete - resource
+ componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
+ for (String id : serviceCategoriesToDelete) {
+ CategoryRestUtils.deleteCategory(id, adminId, componentType);
+ }
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
new file mode 100644
index 0000000000..2b0a35d472
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentInstanceBaseTest.java
@@ -0,0 +1,763 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.api;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.Assert;
+
+public class ComponentInstanceBaseTest extends ComponentBaseTest {
+ public static final String acceptHeaderData = "application/json";
+ // Req/cap of container component
+ protected Map<String, List<CapabilityDefinition>> expectedContainerCapabilities;
+ protected Map<String, List<RequirementDefinition>> expectedContainerRequirements;
+ protected Map<String, Map<String, List<RequirementDefinition>>> removedRequirements;
+ protected Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> expectedContInstReqCap;
+
+ protected User sdncPsDetails1;
+ protected User sdncPsDetails2;
+ protected User sdncPmDetails1;
+ protected User sdncPmDetails2;
+ protected User sdncDesignerDetails;
+ protected User sdncAdminDetails;
+ protected User sdncTesterDetails;
+ protected ResourceReqDetails resourceDetailsVFC_01;
+ protected ResourceReqDetails resourceDetailsVFC_02;
+ protected ResourceReqDetails resourceDetailsVF_01;
+ protected ResourceReqDetails resourceDetailsVF_02;
+ protected ResourceReqDetails resourceDetailsCP_01;
+ protected ResourceReqDetails resourceDetailsCP_02;
+ protected ResourceReqDetails resourceDetailsVL_01;
+ protected ResourceReqDetails resourceDetailsVL_02;
+ protected ServiceReqDetails serviceDetails_01;
+ protected ServiceReqDetails serviceDetails_02;
+ protected ServiceReqDetails serviceDetails_03;
+ protected ProductReqDetails productDetails_01;
+ protected ProductReqDetails productDetails_02;
+
+ public void init() {
+ // Req/caps of inner componentInstances
+ expectedContainerCapabilities = new LinkedHashMap<String, List<CapabilityDefinition>>();
+ expectedContainerRequirements = new LinkedHashMap<String, List<RequirementDefinition>>();
+ removedRequirements = new HashMap<>();
+ expectedContInstReqCap = new HashMap<>();
+
+ sdncPsDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+ sdncPsDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2);
+ sdncPmDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ sdncPmDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2);
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ resourceDetailsVFC_01 = ElementFactory.getDefaultResourceByType("ciVFC100", NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString()); // resourceType = VFC
+ resourceDetailsVFC_02 = ElementFactory.getDefaultResourceByType("ciVFC200", NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC.toString());
+ resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("ciVF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("ciVF200", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("ciCP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
+ resourceDetailsCP_02 = ElementFactory.getDefaultResourceByType("ciCP200", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_DATABASE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
+ resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("ciVL100", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
+ resourceDetailsVL_02 = ElementFactory.getDefaultResourceByType("ciVL200", NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VL.toString());
+ serviceDetails_01 = ElementFactory.getDefaultService("ciNewtestservice1", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId());
+ serviceDetails_02 = ElementFactory.getDefaultService("ciNewtestservice2", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId());
+ serviceDetails_03 = ElementFactory.getDefaultService("ciNewtestservice3", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId());
+ productDetails_01 = ElementFactory.getDefaultProduct("ciProduct01");
+ productDetails_02 = ElementFactory.getDefaultProduct("ciProduct02");
+ }
+
+ public ComponentInstanceBaseTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ public void verifyVFReqCap(String componentId) throws Exception {
+ RestResponse restResponse = ResourceRestUtils.getResource(componentId);
+ Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class);
+ verifyReqCap(resource);
+ }
+
+ public void verifyServiceReqCap(String componentId) throws Exception {
+ RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails);
+ Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class);
+ verifyReqCap(service);
+ }
+
+ public void verifyProductReqCap(String componentId) throws Exception {
+ RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId());
+ Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class);
+ verifyReqCap(product);
+ }
+
+ public void verifyReqCap(Component actualComponent) {
+ verifyContainerReqCap(actualComponent);
+ verifyCompInstReqCap(actualComponent);
+ }
+
+ public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel) throws Exception {
+ RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId, serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType);
+ if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) {
+ /*
+ * // Add RI Capabilities and Requirements to expected MAP --> expectedVfCapabilities and expectedVfRequirements
+ *
+ * ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper( changeResourceInstanceVersion.getResponse(), ComponentInstance.class); addCompInstReqCapToExpected(componentInstance, componentType);
+ */
+ }
+ return changeResourceInstanceVersion;
+ }
+
+ protected void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace, String newContainerUniqueId) {
+
+ // Update of container req/cap
+
+ Set<String> compInstKeysToChange = new HashSet<>();
+
+ for (String expKey : expectedContainerCapabilities.keySet()) {
+ List<CapabilityDefinition> expCapList = expectedContainerCapabilities.get(expKey);
+ for (CapabilityDefinition cap : expCapList) {
+ String ownerId = cap.getOwnerId();
+
+ if (ownerId.contains(oldContainerUniqueIdToReplace)) {
+ compInstKeysToChange.add(ownerId);
+ cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ }
+ }
+ }
+
+ for (String expKey : expectedContainerRequirements.keySet()) {
+ List<RequirementDefinition> expCapList = expectedContainerRequirements.get(expKey);
+ for (RequirementDefinition cap : expCapList) {
+ String ownerId = cap.getOwnerId();
+ if (ownerId.contains(oldContainerUniqueIdToReplace)) {
+ compInstKeysToChange.add(ownerId);
+ cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ }
+ }
+ }
+
+ // Update of internal comp instances req/cap
+ for (String oldKey : compInstKeysToChange) {
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> immutablePair = expectedContInstReqCap.get(oldKey);
+ if (immutablePair != null) {
+ expectedContInstReqCap.remove(oldKey);
+ String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
+ expectedContInstReqCap.put(newKey, immutablePair);
+ }
+ }
+
+ // Update of removed req
+ for (String oldKey : compInstKeysToChange) {
+ Map<String, List<RequirementDefinition>> map = removedRequirements.get(oldKey);
+ if (map != null) {
+ removedRequirements.remove(oldKey);
+ String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
+ Collection<List<RequirementDefinition>> values = map.values();
+ if (values != null) {
+ for (List<RequirementDefinition> list : values) {
+ for (RequirementDefinition reqDef : list) {
+ reqDef.setOwnerId(reqDef.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ }
+ }
+ }
+ removedRequirements.put(newKey, map);
+ }
+ }
+ }
+
+ private void verifyCompInstReqCap(Component actualComponent) {
+ List<ComponentInstance> componentInstances = actualComponent.getComponentInstances();
+ if (componentInstances != null) {
+ assertEquals(expectedContInstReqCap.size(), componentInstances.size());
+ for (ComponentInstance compInst : componentInstances) {
+ String uniqueId = compInst.getUniqueId();
+ // System.out.println("Verifying req/cap of component instance
+ // "+ uniqueId);
+ Map<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
+ if (actualCompInstReq == null) {
+ actualCompInstReq = new HashMap<>();
+ }
+ Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
+ if (actualCompInstCap == null) {
+ actualCompInstCap = new HashMap<>();
+ }
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> expReqCap = expectedContInstReqCap.get(uniqueId);
+ assertNotNull(expReqCap);
+ // System.out.println("expected instance requirements:
+ // "+expReqCap.right);
+ // System.out.println("expected instance capabilities:
+ // "+expReqCap.left);
+ // System.out.println("actual instance requirements:
+ // "+actualCompInstReq);
+ // System.out.println("actual instance capabilities:
+ // "+actualCompInstCap);
+
+ // REQ comparison
+ compareReqCapMaps(expReqCap.right, actualCompInstReq);
+
+ // CAP comparison
+ compareReqCapMaps(expReqCap.left, actualCompInstCap);
+ }
+
+ } else {
+ assertTrue(expectedContInstReqCap.isEmpty());
+ }
+ }
+
+ private void verifyContainerReqCap(Component actualComponent) {
+ Map<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
+ if (actualContainerRequirements == null) {
+ actualContainerRequirements = new HashMap<>();
+ }
+ Map<String, List<CapabilityDefinition>> actualContainerCapabilities = actualComponent.getCapabilities();
+ if (actualContainerCapabilities == null) {
+ actualContainerCapabilities = new HashMap<>();
+ }
+ // System.out.println("Verifying req/cap of container component "+
+ // actualComponent.getUniqueId());
+ // System.out.println("expected container requirements:
+ // "+expectedContainerRequirements);
+ // System.out.println("expected container capabilities:
+ // "+expectedContainerCapabilities);
+ // System.out.println("actual container requirements:
+ // "+actualContainerRequirements);
+ // System.out.println("actual container capabilities:
+ // "+actualContainerCapabilities);
+
+ // REQ comparison
+ compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements);
+
+ // CAP comparison
+ compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities);
+ }
+
+ private <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> actualMap) {
+ assertEquals(expectedMap.size(), actualMap.size());
+ for (String expKey : expectedMap.keySet()) {
+ List<?> expCapList = expectedMap.get(expKey);
+ List<?> actCapList = actualMap.get(expKey);
+ assertEquals(expCapList.size(), actCapList.size());
+ assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList));
+ }
+ }
+
+ public void addCompInstReqCapToExpected(ComponentInstance componentInstance, ComponentTypeEnum containerComponentType) throws Exception {
+ String uniqueId = componentInstance.getUniqueId();
+ String name = componentInstance.getName();
+ String originComponentId = componentInstance.getComponentUid();
+ RestResponse getResponse = null;
+ ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType);
+ Component component = null;
+ if (compInstType == ComponentTypeEnum.RESOURCE) {
+ getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId);
+ ResourceRestUtils.checkSuccess(getResponse);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (compInstType == ComponentTypeEnum.SERVICE) {
+ getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getResponse);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else {
+ Assert.fail("Unsupported type - " + containerComponentType);
+ }
+
+ Map<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
+ if (resourceRequirements == null) {
+ resourceRequirements = new HashMap<>();
+ }
+ Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
+ Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
+
+ Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
+ if (resourceCapabilities == null) {
+ resourceCapabilities = new HashMap<>();
+ }
+
+ Function<? super Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
+ Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
+
+ setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
+ if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE) && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
+ setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
+ }
+
+ // adding entry for expected componentInstance
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(capCopy, reqCopy);
+ expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
+ }
+
+ private void setupContainerExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
+ List<RequirementDefinition> reqListToAdd = resReq.getValue();
+ for (RequirementDefinition requirementDefinition : reqListToAdd) {
+ requirementDefinition.setOwnerId(uniqueId);
+ requirementDefinition.setOwnerName(name);
+ }
+ List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
+ if (expectedReqList == null) {
+ expectedReqList = reqListToAdd;
+ } else {
+ expectedReqList.addAll(reqListToAdd);
+ }
+ expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
+ List<CapabilityDefinition> capListToAdd = resCap.getValue();
+ for (CapabilityDefinition capDefinition : capListToAdd) {
+ capDefinition.setOwnerId(uniqueId);
+ capDefinition.setOwnerName(name);
+ }
+ List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
+ if (expectedCapList == null) {
+ expectedCapList = capListToAdd;
+ } else {
+ expectedCapList.addAll(capListToAdd);
+ }
+ expectedContainerCapabilities.put(resCap.getKey(), expectedCapList);
+ }
+ }
+
+ private void setupConstInstExpectedReqCap(String uniqueId, String name, Map<String, List<RequirementDefinition>> componentRequirements, Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
+ List<RequirementDefinition> reqListToAdd = resReq.getValue();
+ for (RequirementDefinition requirementDefinition : reqListToAdd) {
+ requirementDefinition.setOwnerId(uniqueId);
+ requirementDefinition.setOwnerName(name);
+ }
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
+ List<CapabilityDefinition> capListToAdd = resCap.getValue();
+ for (CapabilityDefinition capDefinition : capListToAdd) {
+ capDefinition.setOwnerId(uniqueId);
+ capDefinition.setOwnerName(name);
+ }
+ }
+ }
+
+ private ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) {
+ switch (componentType) {
+ case RESOURCE:
+ return ComponentTypeEnum.RESOURCE;
+ case SERVICE:
+ return ComponentTypeEnum.RESOURCE;
+ case PRODUCT:
+ return ComponentTypeEnum.SERVICE;
+ default:
+ break;
+ }
+ return null;
+ }
+
+ public void deleteCompInstReqCapFromExpected(String componentInstanceId) {
+ List<String> entriesRequirementsToRemove = new ArrayList<>();
+ List<String> entriesCapabilitiesToRemove = new ArrayList<>();
+ for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
+ List<RequirementDefinition> reqList = reqEntry.getValue();
+ List<RequirementDefinition> reqListToDelete = new ArrayList<>();
+ for (RequirementDefinition requirementDefinition : reqList) {
+ if (requirementDefinition.getOwnerId().equals(componentInstanceId)) {
+ reqListToDelete.add(requirementDefinition);
+ }
+ }
+ reqList.removeAll(reqListToDelete);
+ if (reqList.isEmpty()) {
+ entriesRequirementsToRemove.add(reqEntry.getKey());
+ }
+ }
+
+ for (String ekey : entriesRequirementsToRemove) {
+ expectedContainerRequirements.remove(ekey);
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
+ List<CapabilityDefinition> capList = capEntry.getValue();
+ List<CapabilityDefinition> capListToDelete = new ArrayList<>();
+ for (CapabilityDefinition capabilityDefinition : capList) {
+ if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) {
+ capListToDelete.add(capabilityDefinition);
+ }
+ }
+ capList.removeAll(capListToDelete);
+ if (capList.isEmpty()) {
+ entriesCapabilitiesToRemove.add(capEntry.getKey());
+ }
+ }
+ for (String ekey : entriesCapabilitiesToRemove) {
+ expectedContainerCapabilities.remove(ekey);
+ }
+
+ expectedContInstReqCap.remove(componentInstanceId);
+
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse createAtomicInstanceForVF(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse createAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse createVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse createServiceInstance(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse deleteAtomicInstanceForService(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse deleteVFInstance(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
+
+ }
+
+ // Automatically updates the expected req/cap of the container
+ protected RestResponse deleteServiceInstance(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse createAtomicInstanceForVFDuringSetup(ResourceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse createAtomicInstanceForServiceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse createVFInstanceDuringSetup(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse createServiceInstanceDuringSetup(ProductReqDetails containerDetails, ServiceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, ResourceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, ServiceReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
+
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ protected RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, ProductReqDetails containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false);
+ }
+
+ protected Component getComponentAndValidateRIs(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
+
+ RestResponse getResponse = null;
+ Component component = null;
+ if (componentDetails instanceof ResourceReqDetails) {
+ getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (componentDetails instanceof ServiceReqDetails) {
+ getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else if (componentDetails instanceof ProductReqDetails) {
+ getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
+ } else {
+ Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
+ }
+ ResourceRestUtils.checkSuccess(getResponse);
+ int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
+ int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
+ assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
+ assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
+ verifyReqCap(component);
+
+ return component;
+ }
+
+ protected void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace, ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws IOException, Exception {
+ updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
+ getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations);
+ }
+
+ private RestResponse createComponentInstance(ComponentReqDetails containerDetails, ComponentReqDetails compInstOriginDetails, User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel) throws IOException, Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(compInstOriginDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum);
+ if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) {
+ // Add RI Capabilities and Requirements to expected MAP -->
+ // expectedVfCapabilities and expectedVfRequirements
+ ComponentInstance componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum);
+ }
+ return createResourceInstanceResponse;
+ }
+
+ private RestResponse deleteComponentInstance(String compInstUniqueId, ComponentReqDetails containerDetails, User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception {
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier, containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum);
+ if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) {
+ deleteCompInstReqCapFromExpected(compInstUniqueId);
+ }
+ return deleteResourceInstanceResponse;
+ }
+
+ // Create Atomic resource ( VFC/CP/VL)
+ protected void createAtomicResource(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceResponse);
+
+ }
+
+ protected void createVF(ResourceReqDetails resourceDetails) throws Exception {
+ createVF(resourceDetails, sdncDesignerDetails);
+
+ }
+
+ protected void createVF(ResourceReqDetails resourceDetails, User sdncModifier) throws Exception {
+ RestResponse createVfResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifier);
+ ResourceRestUtils.checkCreateResponse(createVfResponse);
+ }
+
+ protected void createService(ServiceReqDetails serviceDetails) throws Exception {
+ createService(serviceDetails, sdncDesignerDetails);
+ }
+
+ protected void createService(ServiceReqDetails serviceDetails, User sdncModifier) throws Exception {
+ RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifier);
+ ResourceRestUtils.checkCreateResponse(createServiceResponse);
+ }
+
+ protected void createProduct(ProductReqDetails productDetails) throws Exception {
+ createProduct(productDetails, sdncPmDetails1);
+ }
+
+ protected void createProduct(ProductReqDetails productDetails, User sdncModifier) throws Exception {
+ RestResponse createProductResponse = ProductRestUtils.createProduct(productDetails, sdncModifier);
+ ResourceRestUtils.checkCreateResponse(createProductResponse);
+ }
+
+ protected RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException {
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ deleteAssociatedFromExpected(requirementDef);
+
+ return associateInstances;
+ }
+
+ private void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) {
+ // removing from requirements
+ RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0);
+ String type = relationship.getRelationship().getType();
+ String fromId = requirementDef.getFromNode();
+ List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
+ List<CapabilityDefinition> capList = expectedContainerCapabilities.get(type);
+ RequirementDefinition toDelete = null;
+ if (reqList != null) {
+ for (RequirementDefinition reqDef : reqList) {
+ if (reqDef.getOwnerId().equals(fromId)) {
+ toDelete = reqDef;
+ }
+ }
+ if (toDelete != null) {
+ reqList.remove(toDelete);
+ if (reqList.isEmpty()) {
+ expectedContainerRequirements.remove(type);
+ }
+ String ownerId = toDelete.getOwnerId();
+ Map<String, List<RequirementDefinition>> map = removedRequirements.get(ownerId);
+ if (map == null) {
+ map = new HashMap<>();
+ removedRequirements.put(ownerId, map);
+ }
+ List<RequirementDefinition> list = map.get(type);
+ if (list == null) {
+ list = new ArrayList<>();
+ map.put(type, list);
+ }
+ list.add(toDelete);
+ }
+ }
+
+ for (CapabilityDefinition capabilityDefinition : capList) {
+ if (capabilityDefinition.getType().equals(type)) {
+ int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) - 1;
+ if (minOccurrences < 0)
+ minOccurrences = 0;
+ String minOccurrencesString = Integer.toString(minOccurrences);
+ capabilityDefinition.setMinOccurrences(minOccurrencesString);
+ if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) {
+ int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) - 1;
+ if (maxOccurrences < 0)
+ maxOccurrences = 0;
+ String maxOccurrencesString = Integer.toString(maxOccurrences);
+ capabilityDefinition.setMaxOccurrences(maxOccurrencesString);
+ }
+ }
+ }
+ expectedContainerCapabilities.put(type, capList);
+ }
+
+ protected void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef, ComponentReqDetails containerDetails, User user) throws IOException {
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user, containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(dissociateInstances);
+ addDissociatedToExpected(requirementDef);
+ }
+
+ protected void fulfillCpRequirement(ComponentReqDetails component, String cpCompInstId, String cpReqFulfillerCompInstId, String cpReqFulfillerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException {
+ // Fulfilling cp's "binding" requirement - US626240
+ String requirementName = "binding";
+ String capType = "tosca.capabilities.network.Bindable";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(cpCompInstId, cpReqFulfillerCompInstId, cpCompInstId, cpReqFulfillerOwnerId, capType, requirementName, capList, reqList);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ }
+
+ protected void consumeVlCapability(ComponentReqDetails component, String vlCapConsumerCompInstId, String vlCompInstId, String vlCapConsumerOwnerId, User user, ComponentTypeEnum containerCompType) throws IOException {
+ // Consuming vl's "link" capability - US626240
+ String requirementName = "link";
+ String capType = "tosca.capabilities.network.Linkable";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(user, component);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef reqCapRelation = ElementFactory.getReqCapRelation(vlCapConsumerCompInstId, vlCompInstId, vlCapConsumerOwnerId, vlCompInstId, capType, requirementName, capList, reqList);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(reqCapRelation, user, component.getUniqueId(), containerCompType);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ }
+
+ private void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) {
+ // adding to requirements
+ RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0);
+ String type = relationship.getRelationship().getType();
+ String fromId = requirementDef.getFromNode();
+ Map<String, List<RequirementDefinition>> map = removedRequirements.get(fromId);
+ if (map != null) {
+ List<RequirementDefinition> list = map.get(type);
+ if (list != null && !list.isEmpty()) {
+ List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
+ if (reqList == null) {
+ reqList = new ArrayList<>();
+ expectedContainerRequirements.put(type, reqList);
+ }
+ reqList.add(list.remove(0));
+ }
+ }
+
+ List<CapabilityDefinition> capList = expectedContainerCapabilities.get(type);
+
+ for (CapabilityDefinition capabilityDefinition : capList) {
+ if (capabilityDefinition.getType().equals(type)) {
+ int minOccurrences = Integer.parseInt(capabilityDefinition.getMinOccurrences()) + 1;
+ String minOccurrencesString = Integer.toString(minOccurrences);
+ capabilityDefinition.setMinOccurrences(minOccurrencesString);
+ if (!capabilityDefinition.getMaxOccurrences().equals("UNBOUNDED")) {
+ int maxOccurrences = Integer.parseInt(capabilityDefinition.getMaxOccurrences()) + 1;
+ String maxOccurrencesString = Integer.toString(maxOccurrences);
+ capabilityDefinition.setMaxOccurrences(maxOccurrencesString);
+ }
+ }
+ }
+ expectedContainerCapabilities.put(type, capList);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java
new file mode 100644
index 0000000000..ebad749097
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/SdcTest.java
@@ -0,0 +1,202 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.api;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.junit.rules.TestWatcher;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.rules.MyTestWatcher;
+import org.openecomp.sdc.ci.tests.run.StartTest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public abstract class SdcTest {
+
+ public static StringBuilder doc = new StringBuilder();
+ public static String file = null;
+ public static Config config = null;
+ // protected Gson gson = new Gson();
+ protected Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
+
+ protected TestName testName = null;
+ protected Logger logger = null;
+
+ protected static boolean displayException = false;
+
+ public SdcTest(TestName testName, String className) {
+ super();
+
+ StartTest.enableLogger();
+
+ this.testName = testName;
+ this.logger = LoggerFactory.getLogger(className);
+
+ String displayEx = System.getProperty("displayException");
+ if (displayEx != null && Boolean.valueOf(displayEx).booleanValue()) {
+ displayException = true;
+ }
+
+ }
+
+ @Rule
+ public TestWatcher tw = new MyTestWatcher(this);
+
+ @BeforeClass
+ public static void beforeClass() {
+ doc = new StringBuilder();
+ doc.append(
+ "<Html><head><style>th{background-color: gray;color: white;height: 30px;}td {color: black;height: 30px;}.fail {background-color: #FF5555;width: 100px;text-align: center;}.success {background-color: #00FF00;width: 100px;text-align: center;}.name {width: 200px;background-color: #F0F0F0;}.message {width: 300px;background-color: #F0F0F0;}</style>");
+
+ doc.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
+ doc.append(
+ "<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">");
+
+ doc.append("</head><body>");
+
+ doc.append("<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>");
+ doc.append("<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js\"></script>");
+
+ doc.append("<table>");
+
+ doc.append("<tr>");
+ doc.append("<th>").append("Test Name").append("</th>");
+ doc.append("<th>").append("Status").append("</th>");
+ doc.append("<th>").append("Message").append("</th>");
+
+ if (displayException) {
+ doc.append("<th>").append("Exception").append("</th>");
+ }
+ doc.append("</tr>");
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ doc.append("<table>");
+ FileUtils.writeToFile(
+ Config.instance().getOutputFolder() + File.separator + file + StartTest.timeOfTest + ".html",
+ doc.toString());
+
+ }
+
+ @Before
+ public void beforeTest() throws FileNotFoundException {
+ file = FileUtils.getFileName(this.getClass().getName());
+ config = Utils.getConfig();
+ assertTrue(config != null);
+
+ // logger.info("Start running test " + testName.getMethodName());
+ }
+
+ @After
+ public void afterTest() throws FileNotFoundException {
+
+ // logger.info("Finish running test " + testName.getMethodName());
+ }
+
+ public void addTestSummary(String testName, boolean isSuccess) {
+ addTestSummary(testName, isSuccess, null);
+ }
+
+ public void addTestSummary(String testName, boolean isSuccess, Throwable exception) {
+
+ String message = exception == null ? "" : exception.getMessage();
+
+ String result = (isSuccess) ? "success" : "fail";
+ doc.append("<tr>");
+ doc.append("<td class=\"name\">").append(testName).append("</td>");
+ doc.append("<td class=\"" + result + "\">").append(result).append("</td>");
+ doc.append("<td class=\"message\">").append(message).append("</td>");
+
+ if (displayException) {
+ // doc.append("<td
+ // class=\"message\">").append(convertExceptionToString(exception)).append("</td>");
+ doc.append("<td class=\"message\">");
+
+ doc.append("<button type=\"button\" class=\"btn btn-info\" data-toggle=\"collapse\" data-target=\"#demo"
+ + testName + "\">Simple collapsible</button>");
+ doc.append("<div id=\"demo" + testName + "\" class=\"collapse out\">");
+
+ doc.append(convertExceptionToString(exception));
+
+ doc.append("</div>");
+ doc.append("</td>");
+ }
+
+ doc.append("</tr>");
+
+ if (isSuccess) {
+ logger.debug("Test {} succeeded.", testName);
+ } else {
+ logger.error("Test {} failed with error: {}", testName, message);
+ }
+ }
+
+ private String convertExceptionToString(Throwable exception) {
+
+ if (exception == null) {
+ return "";
+ }
+
+ StringWriter sw = new StringWriter();
+ exception.printStackTrace(new PrintWriter(sw));
+ String exceptionAsString = sw.toString();
+
+ return exceptionAsString;
+ }
+
+ public Logger getLogger() {
+ return logger;
+ }
+
+ protected boolean ignoreDueToBug(String bug) {
+
+ List<String> bugs = config.getBugs();
+
+ if (bugs != null && bugs.size() > 0) {
+ for (String bugNumber : bugs) {
+ if (bugNumber.startsWith(bug)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
new file mode 100644
index 0000000000..5aceb4fae3
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java
@@ -0,0 +1,348 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.api;
+
+public interface Urls {
+
+ final String UPLOAD_ZIP_URL = "http://%s:%s/sdc1/rest/v1/catalog/resources";
+ final String GET_IMAGE_DATA_FROM_ES = "http://%s:%s/resources/imagedata/_search?q=resourceName:%s&pretty=true&size=1000";
+ final String GET_SCRIPT_DATA_FROM_ES = "http://%s:%s/resources/artifactdata/_search?q=resourceName:%s&pretty=true&size=1000";
+ final String GET_ID_LIST_BY_INDEX_FROM_ES = "http://%s:%s/%s/%s/_search?fields=_id&size=1000";
+
+ final String ES_URL = "http://%s:%s";
+ final String GET_SERVICE_CSAR_API1 = "http://%s:%s/sdc2/rest/services/%s/%s";
+ final String GET_SERVICE_CSAR_API2 = "http://%s:%s/sdc2/rest/services/%s/%s/csar";
+
+ final String GET_SERVICE_CSAR_FE_PROXY_API1 = "http://%s:%s/sdc1/portal/rest/services/%s/%s";
+ final String GET_CSAR_USING_SIMULATOR = "http://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s";
+ final String COPY_CSAR_USING_SIMULATOR = "http://%s:%s/onboardingci/onbrest/onboarding-api/v1.0/vendor-software-products/packages/%s/%s";
+
+ final String GET_HEALTH_CHECK_VIA_PROXY = "http://%s:%s/sdc1/rest/healthCheck";
+
+ // Get back-end config http://172.20.43.132:8080/sdc2/rest/configmgr/get
+ final String GET_CONFIG_MANAGER = "http://%s:%s/sdc2/rest/configmgr/get";
+
+ // Get latest version of all non-abstract resources
+ final String GET_RESOURCE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/latestversion/notabstract";
+
+ final String GET_SERVICE_lATEST_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/latestversion/notabstract";
+
+ // Get resource artifact list:
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts
+ final String GET_RESOURCE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts";
+
+ // get resource artifact metadata (creation, MD5, etc):
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts/install_apache.sh/metadata
+ final String GET_RESOURCE_ARTIFACT_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s/metadata";
+
+ // resource artifact payload:
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/resources/alien.nodes.Apache/2.0.0-SNAPSHOT/artifacts/install_apache.sh
+ final String GET_RESOURCE_ARTIFACT_PAYLOAD = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s";
+
+ final String GET_RESOURCE_ARTIFACT_PAYLOAD_FE_PROXY = "http://%s:%s/sdc1/portal/rest/v1/catalog/resources/%s/%s/artifacts/%s";
+
+ // Get service list: http://172.20.43.124:8080/sdc2/rest/v1/catalog/services
+ final String GET_SERVICE_LIST = "http://%s:%s/sdc2/rest/v1/catalog/services";
+
+ // Get service versions:
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/MyService
+ final String GET_SERVICE_VERSIONS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s";
+
+ // Get service artifact list:
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts
+ final String GET_SERVICE_ARTIFACTS_LIST = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s/artifacts";
+
+ // get service artifact metadata (creation, MD5, etc):
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts/install_apache.sh/metadata
+ final String GET_SERVICE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s/metadata";
+
+ // service artifact payload:
+ // http://172.20.43.124:8080/sdc2/rest/v1/catalog/services/alien.nodes.Apache/0.0.1/artifacts/install_apache.sh
+ final String GET_SERVICE_ARTIFACT_PAYLOAD = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/artifacts/%s";
+
+ final String GET_SEARCH_DATA_FROM_ES = "http://%s:%s/%s";
+
+ // ****************************************************USER
+ // URLs********************************************************
+ final String GET_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+
+ final String GET_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role";
+
+ final String CREATE_USER = "http://%s:%s/sdc2/rest/v1/user";
+
+ final String UPDATE_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+
+ final String UPDATE_USER_ROLE = "http://%s:%s/sdc2/rest/v1/user/%s/role";
+
+ final String DELETE_USER = "http://%s:%s/sdc2/rest/v1/user/%s";
+
+ final String GET_ALL_ADMIN_USERS = "http://%s:%s/sdc2/rest/v1/user/admins";
+
+ final String AUTHORIZE_USER = "http://%s:%s/sdc2/rest/v1/user/authorize";
+
+ final String GET_ALL_TAGS = "http://%s:%s/sdc2/rest/v1/tags";
+
+ final String AUTH_USER = "http://%s:%s/sdc2/rest/v1/user/authorize";
+
+ final String GET_ALL_NOT_ABSTRACT_RESOURCES = "http://%s:%s/sdc2/rest/v1/catalog/resources/certified/notabstract";
+
+ final String GET_ALL_ABSTRACT_RESOURCES = "http://%s:%s/sdc2/rest/v1/catalog/resources/certified/abstract";
+
+ final String QUERY_NEO4J = "http://%s:%s/db/data/transaction";
+ final String CHANGE_IN_NEO4J = "http://%s:%s/db/data/transaction/commit";
+
+ final String GET_ALL_ADMINS = "http://%s:%s/sdc2/rest/v1/user/admins";
+
+ final String GET_USERS_BY_ROLES = "http://%s:%s/sdc2/rest/v1/user/users?roles=%s";
+
+ final String GET_ALL_USERS = "http://%s:%s/sdc2/rest/v1/user/users?roles/";
+
+ // *****************************************ECOMP User
+ // URL's*****************************************************
+ final String ECOMP_PUSH_USER = "http://%s:%s/api/user";
+
+ final String ECOMP_EDIT_USER = "http://%s:%s/api/user/%s";
+
+ final String ECOMP_GET_USER = "http://%s:%s/api/user/%s";
+
+ final String ECOMP_GET_ALL_USERS = "http://%s:%s/api/users";
+
+ final String ECOMP_GET_ALL_AVAILABLE_ROLES = "http://%s:%s/api/roles";
+
+ final String ECOMP_PUSH_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+
+ final String ECOMP_GET_USER_ROLES = "http://%s:%s/api/user/%s/roles";
+
+ // *****************************************Elements*************************************************************
+ final String GET_TAGS_LIST = "http://%s:%s/sdc2/rest/v1/tags";
+
+ final String GET_PROPERTY_SCOPES_LIST = "http://%s:%s/sdc2/rest/v1/propertyScopes";
+
+ final String GET_CONFIGURATION = "http://%s:%s/sdc2/rest/v1/configuration/ui";
+
+ final String GET_ALL_ARTIFACTS = "http://%s:%s/sdc2/rest/v1/artifactTypes";
+
+ final String GET_FOLLWED_LIST = "http://%s:%s/sdc2/rest/v1/followed";
+
+ final String GET_CATALOG_DATA = "http://%s:%s/sdc2/rest/v1/screen";
+
+ // *****************************************Resources
+ // **********************************************************************
+ final String GET_LIST_CERTIFIED_RESOURCE_TEMPLATES = "http://%s:%s/sdc2/rest/v1/resoourceTemplates";
+
+ final String CREATE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources";
+ final String UPDATE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s";
+
+ final String IMPORT_RESOURCE_NORMATIVE = "http://%s:%s/sdc2/rest/v1/catalog/upload/multipart";
+
+ final String IMPORT_USER_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/upload/user-resource";
+
+ final String IMPORT_CAPABILITY_TYPE = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/capability";
+ final String IMPORT_CATEGORIES = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/categories";
+ final String IMPORT_GROUP_TYPE = "http://%s:%s/sdc2/rest/v1/catalog/uploadType/grouptypes";
+
+ // last %s is resourceId, resourceId = resourceName.resourceVersion
+ final String GET_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s";
+ final String GET_RESOURCE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/resourceName/%s/resourceVersion/%s";
+ final String GET_RESOURCE_BY_CSAR_UUID = "http://%s:%s/sdc2/rest/v1/catalog/resources/csar/%s";
+ final String GET_COMPONENT_REQUIRMENTS_CAPABILITIES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/requirmentsCapabilities";
+
+ final String DELETE_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s";
+ final String DELETE_RESOURCE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s";
+ final String DELETE_SERVICE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/%s";
+
+ final String DELETE_MARKED_RESOURCES = "http://%s:%s/sdc2/rest/v1/inactiveComponents/resource";
+ final String DELETE_MARKED_SERVICES = "http://%s:%s/sdc2/rest/v1/inactiveComponents/service";
+
+ final String GET_FOLLOWED_RESOURCES = "http://%s:%s/sdc2/rest/v1/followed/resources/%s";
+ final String CHANGE_RESOURCE_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/lifecycleState/%s";
+ final String CHANGE_SERVICE_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/lifecycleState/%s";
+ final String CHANGE_PRODUCT_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/products/%s/lifecycleState/%s";
+ final String CHANGE_COMPONENT_LIFECYCLE_STATE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/lifecycleState/%s";
+
+ final String CREATE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties";
+
+ final String UPDATE_RESOURCE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/metadata";
+
+ // ***********************************External API's
+ // (AssetData)****************************************
+
+ final String POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/%s/%s/artifacts";
+
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/resources/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+
+ final String GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/resources/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+
+ final String GET_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s";
+ final String GET_FILTERED_ASSET_LIST = "http://%s:%s/asdc/v1/catalog/%s?%s";
+ final String GET_TOSCA_MODEL = "http://%s:%s/asdc/v1/catalog/%s/%s/toscaModel";
+ // https://{serverRoot}/asdc/v1/catalog/{assetType}/{uuid}/metadata, where
+ // assetType in {resources, services}
+ final String GET_ASSET_METADATA = "http://%s:%s/asdc/v1/catalog/%s/%s/metadata";
+ final String POST_AUTHORIZATION = "http://%s:%s/sdc2/rest/v1/consumers";
+ final String GET_DOWNLOAD_SERVICE_RI_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+ final String GET_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/asdc/v1/catalog/services/%s/artifacts/%s";
+
+ // *****************************************************************************************************
+
+ final String ADD_ARTIFACT_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts";
+ final String UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s";
+ final String ADD_ARTIFACT_TO_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts";
+ final String UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/%s";
+
+ final String UPLOAD_DELETE_ARTIFACT_OF_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts";
+ final String UPDATE_ARTIFACT_OF_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/artifacts/%s";
+ final String UPLOAD_HEAT_ENV_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/artifacts/%s";
+ // *****************************************************************************************************
+ final String UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/";
+ final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/%s";
+
+ final String UPLOAD_ARTIFACT_BY_INTERFACE_TO_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/";
+ final String UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_COMPONENT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/%s/%s/artifacts/%s";
+
+ // *****************************************************************************************************
+ // "/sdc2/v1/services/<serviceName>/<0.1>/artifacts/aaa.hh"
+ final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/artifacts/%s";
+ // "/sdc2/v1/services/<serviceName>/<0.1>/resources/{resourceName}/{resourceVersion}/artifacts/<opeartion_name>_aaa.hh"
+ final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT = "/sdc2/rest/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/artifacts/%s";
+ final String DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL = "/asdc/v1/catalog/services/%s/%s/resources/%s/%s/artifacts/%s";
+ final String DOWNLOAD_SERVICE_ARTIFACT_FULL_URL = "http://%s:%s%s";
+ final String DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL = "http://%s:%s%s";
+ // **********************************************************************************
+ final String UI_DOWNLOAD_RESOURCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/artifacts/%s";
+ final String UI_DOWNLOAD_SERVICE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/%s";
+
+ // **********************************************************************************************************
+ final String UPDATE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s";
+
+ final String DELETE_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s";
+
+ final String GET_PROPERTY = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/properties/%s";
+
+ // *****************************************************************************************************
+
+ final String VALIDATE_RESOURCE_NAME = "http://%s:%s/sdc2/rest/v1/catalog/resources/validate-name/%s";
+
+ final String CREATE_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services";
+ final String DELETE_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s";
+ final String GET_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s";
+ final String GET_SERVICE_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/services/serviceName/%s/serviceVersion/%s";
+
+ final String GET_SERVICES_REQUIRMENTS_CAPABILITIES = "http://%s:%s/sdc2/rest/v1/catalog/requirmentsCapabilities/services/%s";
+
+ final String CREATE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance";
+ final String DELETE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s";
+ final String UPDATE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s";
+ final String GET_COMPONENT_INSTANCES = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances";
+ // Tal New API
+ final String UPDATE_MULTIPLE_COMPONENT_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/multipleComponentInstance";
+
+ final String CHANGE__RESOURCE_INSTANCE_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/changeVersion";
+
+ final String CREATE_AND_ASSOCIATE_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/createAndAssociate";
+ final String ASSOCIATE__RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/associate";
+ final String DISSOCIATE__RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/dissociate";
+
+ final String DISTRIBUTION_INIT = "http://%s:%s/init";
+ final String DISTRIBUTION_INIT_RESET = "http://%s:%s/initReset";
+ final String APPROVE_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/approve";
+ final String REJECT_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution-state/reject";
+ final String DISTRIBUTION_DOWNLOAD_ARTIFACT = "http://%s:%s/download";
+ final String ACTIVATE_DISTRIBUTION = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/activate";
+
+ final String DEPLOY_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/distribution/%s/markDeployed";
+ final String UPDATE_SERVICE_METADATA = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/metadata";
+
+ // Andrey changed name from ADD_PROPERTY_TO_RESOURCE_INSTANCE to
+ // UPDATE_PROPERTY_TO_RESOURCE_INSTANCE
+ final String UPDATE_PROPERTY_TO_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/property";
+ final String DELETE_PROPERTY_FROM_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/property/%s";
+ final String UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s/heatParams";
+
+ // Actions on artifact in resource instance
+ final String ADD_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts";
+ final String UPDATE_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s";
+ final String DELETE_RESOURCE_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstance/%s/artifacts/%s";
+
+ // Attributes On Resource instance
+ public static final String UPDATE_ATTRIBUTE_ON_RESOURCE_INSTANCE = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/resourceInstance/%s/attribute";
+
+ // ("/services/{serviceId}/resourceInstances/{resourceInstanceId}/artifacts/{artifactId}")
+ final String DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s";
+
+ // -------------------------------service api
+ // artifact-----------------------------------------------------
+ final String UPDATE_DELETE_SERVICE_API_ARTIFACT = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/artifacts/api/%s";
+
+ final String CREATE_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo";
+ final String UPDATE_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo/%s";
+ final String DELETE_ADDITIONAL_INFORMATION_RESOURCE = UPDATE_ADDITIONAL_INFORMATION_RESOURCE;
+ final String GET_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo/%s";
+ final String GET_ALL_ADDITIONAL_INFORMATION_RESOURCE = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/additionalinfo";
+
+ final String CREATE_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo";
+ final String UPDATE_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo/%s";
+ final String DELETE_ADDITIONAL_INFORMATION_SERVICE = UPDATE_ADDITIONAL_INFORMATION_SERVICE;
+ final String GET_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo/%s";
+ final String GET_ALL_ADDITIONAL_INFORMATION_SERVICE = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/additionalinfo";
+
+ final String GET_COMPONENT_AUDIT_RECORDS = "http://%s:%s/sdc2/rest/v1/catalog/audit-records/%s/%s";
+
+ // CONSUMER
+ final String CREATE_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers";
+ final String GET_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers/%s";
+ final String DELETE_CONSUMER = "http://%s:%s/sdc2/rest/v1/consumers/%s";
+
+ // Categories
+ final String CREATE_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s";
+ final String GET_ALL_CATEGORIES = "http://%s:%s/sdc2/rest/v1/categories/%s";
+ final String GET_ALL_CATEGORIES_FE = "http://%s:%s/sdc1/feProxy/rest/v1/categories/%s";
+ final String DELETE_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s";
+ final String CREATE_SUB_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory";
+ final String DELETE_SUB_CATEGORY = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s";
+ final String CREATE_GROUPING = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s/grouping";
+ final String DELETE_GROUPING = "http://%s:%s/sdc2/rest/v1/category/%s/%s/subCategory/%s/grouping/%s";
+
+ // product
+ final String CREATE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products";
+ final String DELETE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s";
+ // last %s is resourceId, productId
+ final String GET_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s";
+ final String UPDATE_PRODUCT = "http://%s:%s/sdc2/rest/v1/catalog/products/%s/metadata";
+ final String GET_PRODUCT_BY_NAME_AND_VERSION = "http://%s:%s/sdc2/rest/v1/catalog/products/productName/%s/productVersion/%s";
+
+ // groups
+ final String GET_GROUP_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/groups/%s";
+
+ // modules
+ final String GET_MODULE_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s";
+
+ // inputs
+ final String ADD_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/create/inputs"; //{componentType}/{componentId}/create/inputs
+ final String DELETE_INPUT_BY_ID = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/delete/%s/input"; //{componentType}/{componentId}/delete/{inputId}/input
+ final String GET_COMPONENT_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/services/%s/inputs"; //services/{componentId}/inputs
+ final String GET_COMPONENT_INSTANCE_INPUTS = "http://%s:%s/sdc2/rest/v1/catalog/%s/%s/componentInstances/%s/%s/inputs"; //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs
+ final String GET_INPUTS_FOR_COMPONENT_INPUT = "http://%s:%s/sdc2/rest/v1/catalog/resources/%s/groups/%s"; //{componentType}/{componentId}/inputs/{inputId}/inputs
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
new file mode 100644
index 0000000000..ce025715fd
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/Config.java
@@ -0,0 +1,584 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.config;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.List;
+
+import org.yaml.snakeyaml.Yaml;
+
+public class Config {
+
+ private static String WINDOWS_CONFIG_FILE = "src/main/resources/ci/conf/sdc.yaml";
+
+ String catalogBeHost;
+ String esHost;
+ String esPort;
+ String neoHost;
+ String neoPort;
+ String disributionClientHost;
+ String disributionClientPort;
+
+ String errorConfigurationFile;
+ String resourceConfigDir;
+ String componentsConfigDir;
+ String importResourceConfigDir;
+ String importResourceTestsConfigDir;
+ String importTypesConfigDir;
+ String testSuites;
+
+ String catalogFeHost;
+ String catalogFePort;
+ String catalogBePort;
+ String catalogBeTlsPort;
+
+ String neoDBusername;
+ String neoDBpassword;
+
+ String titanPropertiesFile;
+ List<String> packages;
+ List<String> bugs;
+ List<String> resourcesNotToDelete;
+ List<String> resourceCategoriesNotToDelete;
+ List<String> serviceCategoriesNotToDelete;
+ Boolean stopOnClassFailure = false;
+
+ private String outputFolder;
+ private String reportName;
+ private String url;
+ private String remoteTestingMachineIP;
+ private String remoteTestingMachinePort;
+ private boolean remoteTesting;
+
+ private String cassandraHost;
+ private String cassandraAuditKeySpace;
+ private String cassandraArtifactKeySpace;
+ private Boolean cassandraAuthenticate;
+ private String cassandraUsername;
+ private String cassandraPassword;
+ private Boolean cassandraSsl;
+ private String cassandraTruststorePath;
+ private String cassandraTruststorePassword;
+
+ private static Config configIt = null;
+
+ private static Yaml yaml = new Yaml();
+
+ private Config() {
+ super();
+ }
+
+ public static class TestPackages {
+
+ List<String> packages;
+ List<String> bugs;
+
+ public List<String> getPackages() {
+ return packages;
+ }
+
+ public void setPackages(List<String> packages) {
+ this.packages = packages;
+ }
+
+ public List<String> getBugs() {
+ return bugs;
+ }
+
+ public void setBugs(List<String> bugs) {
+ this.bugs = bugs;
+ }
+
+ @Override
+ public String toString() {
+ return "TestPackages [packages=" + packages + ", bugs=" + bugs + "]";
+ }
+
+ }
+
+ public synchronized static Config instance() {
+ if (configIt == null) {
+ try {
+ configIt = init();
+ } catch (IOException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+ return configIt;
+ }
+
+ private static Config init() throws IOException {
+
+ Config config = null;
+
+ String configFile = System.getProperty("config.resource");
+ if (configFile == null) {
+ if (System.getProperty("os.name").contains("Windows")) {
+ configFile = WINDOWS_CONFIG_FILE;
+ } else {
+ throw new RuntimeException("Please Add Jvm Argument config.resource");
+ }
+ }
+
+ File file = new File(configFile);
+ if (false == file.exists()) {
+ throw new RuntimeException("The config file " + configFile + " cannot be found.");
+ }
+
+ InputStream in = null;
+ try {
+
+ in = Files.newInputStream(Paths.get(configFile));
+
+ config = yaml.loadAs(in, Config.class);
+
+ setPackagesAndBugs(configFile, config);
+
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ return config;
+ }
+
+ private static void setPackagesAndBugs(String path, Config config) throws IOException {
+
+ int separator = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/"));
+ String dirPath = path.substring(0, separator + 1);
+ String packagesFile = dirPath + File.separator + "sdc-packages.yaml";
+ File file = new File(packagesFile);
+ if (false == file.exists()) {
+ throw new RuntimeException("The config file " + packagesFile + " cannot be found.");
+ }
+
+ TestPackages testPackages = null;
+ InputStream in = null;
+ try {
+
+ in = Files.newInputStream(Paths.get(packagesFile));
+
+ testPackages = yaml.loadAs(in, TestPackages.class);
+
+ List<String> bugs = testPackages.getBugs();
+ List<String> packages = testPackages.getPackages();
+
+ config.setBugs(bugs);
+ config.setPackages(packages);
+
+ } finally {
+ if (in != null) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+ }
+
+ }
+
+ // public Config(String catalogBeHost, String esHost, String esPort, String
+ // resourceConfigDir, String componentsConfigDir, String catalogFeHost,
+ // String catalogFePort, String catalogBePort) {
+ // super();
+ // this.catalogBeHost = catalogBeHost;
+ // this.esHost = esHost;
+ // this.esPort = esPort;
+ // this.resourceConfigDir = resourceConfigDir;
+ // this.componentsConfigDir = componentsConfigDir;
+ // this.catalogFeHost = catalogFeHost;
+ // this.catalogFePort = catalogFePort;
+ // this.catalogBePort = catalogBePort;
+ // }
+
+ String configurationFile;
+
+ public String getConfigurationFile() {
+ return configurationFile;
+ }
+
+ public void setConfigurationFile(String configurationFile) {
+ this.configurationFile = configurationFile;
+ }
+
+ public String getCatalogBePort() {
+ return catalogBePort;
+ }
+
+ public String getDisributionClientHost() {
+ return disributionClientHost;
+ }
+
+ public void setDisributionClientHost(String disributionClientHost) {
+ this.disributionClientHost = disributionClientHost;
+ }
+
+ public String getDisributionClientPort() {
+ return disributionClientPort;
+ }
+
+ public void setDisributionClientPort(String disributionClientPort) {
+ this.disributionClientPort = disributionClientPort;
+ }
+
+ public void setCatalogBePort(String catalogBePort) {
+ this.catalogBePort = catalogBePort;
+ }
+
+ public String getCatalogFeHost() {
+ return catalogFeHost;
+ }
+
+ public void setCatalogFeHost(String catalogFeHost) {
+ this.catalogFeHost = catalogFeHost;
+ }
+
+ public String getCatalogFePort() {
+ return catalogFePort;
+ }
+
+ public void setCatalogFePort(String catalogFePort) {
+ this.catalogFePort = catalogFePort;
+ }
+
+ public String getCatalogBeHost() {
+ return catalogBeHost;
+ }
+
+ public void setCatalogBeHost(String catalogBeHost) {
+ this.catalogBeHost = catalogBeHost;
+ }
+
+ public String getEsHost() {
+ return esHost;
+ }
+
+ public void setEsHost(String esHost) {
+ this.esHost = esHost;
+ }
+
+ public String getEsPort() {
+ return esPort;
+ }
+
+ public void setEsPort(String esPort) {
+ this.esPort = esPort;
+ }
+
+ public String getResourceConfigDir() {
+ return resourceConfigDir;
+ }
+
+ public void setResourceConfigDir(String resourceConfigDir) {
+ this.resourceConfigDir = resourceConfigDir;
+ }
+
+ public String getComponentsConfigDir() {
+ return componentsConfigDir;
+ }
+
+ public void setComponentsConfigDir(String componentsConfigDir) {
+ this.componentsConfigDir = componentsConfigDir;
+ }
+
+ public String getOutputFolder() {
+ return outputFolder;
+ }
+
+ public void setOutputFolder(String outputFolder) {
+ this.outputFolder = outputFolder;
+ }
+
+ public String getReportName() {
+ return reportName;
+ }
+
+ public void setReportName(String reportName) {
+ this.reportName = reportName;
+ }
+
+ public String getNeoPort() {
+ return neoPort;
+ }
+
+ public void setNeoPort(String neoPort) {
+ this.neoPort = neoPort;
+ }
+
+ public String getNeoHost() {
+ return neoHost;
+ }
+
+ public void setNeoHost(String neoHost) {
+ this.neoHost = neoHost;
+ }
+
+ public String getNeoDBpassword() {
+ return neoDBpassword;
+ }
+
+ public String getNeoDBusername() {
+ return neoDBusername;
+ }
+
+ public void setNeoDBusername(String neoDBusername) {
+ this.neoDBusername = neoDBusername;
+ }
+
+ public void setNeoDBpassword(String neoDBpassword) {
+ this.neoDBpassword = neoDBpassword;
+ }
+
+ public String getTitanPropertiesFile() {
+ return titanPropertiesFile;
+ }
+
+ public void setTitanPropertiesFile(String titanPropertiesFile) {
+ this.titanPropertiesFile = titanPropertiesFile;
+ }
+
+ public List<String> getPackages() {
+ return packages;
+ }
+
+ public void setPackages(List<String> packages) {
+ this.packages = packages;
+ }
+
+ public List<String> getBugs() {
+ return bugs;
+ }
+
+ public void setBugs(List<String> bugs) {
+ this.bugs = bugs;
+ }
+
+ public Boolean isStopOnClassFailure() {
+ return stopOnClassFailure;
+ }
+
+ public void setStopOnClassFailure(Boolean stopOnClassFailure) {
+ this.stopOnClassFailure = stopOnClassFailure;
+ }
+
+ public String getImportResourceConfigDir() {
+ return importResourceConfigDir;
+ }
+
+ public void setImportResourceConfigDir(String importResourceConfigDir) {
+ this.importResourceConfigDir = importResourceConfigDir;
+ }
+
+ public String getImportResourceTestsConfigDir() {
+ return importResourceTestsConfigDir;
+ }
+
+ public void setImportResourceTestsConfigDir(String importResourceTestsConfigDir) {
+ this.importResourceTestsConfigDir = importResourceTestsConfigDir;
+ }
+
+ public String getErrorConfigurationFile() {
+ return errorConfigurationFile;
+ }
+
+ public void setErrorConfigurationFile(String errorConfigurationFile) {
+ this.errorConfigurationFile = errorConfigurationFile;
+ }
+
+ public String getCatalogBeTlsPort() {
+ return catalogBeTlsPort;
+ }
+
+ public void setCatalogBeTlsPort(String catalogBeTlsPort) {
+ this.catalogBeTlsPort = catalogBeTlsPort;
+ }
+
+ public List<String> getResourcesNotToDelete() {
+ return resourcesNotToDelete;
+ }
+
+ public void setResourcesNotToDelete(List<String> resourcesNotToDelete) {
+ this.resourcesNotToDelete = resourcesNotToDelete;
+ }
+
+ public List<String> getResourceCategoriesNotToDelete() {
+ return resourceCategoriesNotToDelete;
+ }
+
+ public void setResourceCategoriesNotToDelete(List<String> resourceCategoriesNotToDelete) {
+ this.resourceCategoriesNotToDelete = resourceCategoriesNotToDelete;
+ }
+
+ public List<String> getServiceCategoriesNotToDelete() {
+ return serviceCategoriesNotToDelete;
+ }
+
+ public void setServiceCategoriesNotToDelete(List<String> serviceCategoriesNotToDelete) {
+ this.serviceCategoriesNotToDelete = serviceCategoriesNotToDelete;
+ }
+
+ public String getImportTypesConfigDir() {
+ return importTypesConfigDir;
+ }
+
+ public void setImportTypesConfigDir(String importTypesConfigDir) {
+ this.importTypesConfigDir = importTypesConfigDir;
+ }
+
+ public String getCassandraHost() {
+ return cassandraHost;
+ }
+
+ public void setCassandraHost(String cassandraHost) {
+ this.cassandraHost = cassandraHost;
+ }
+
+ public String getCassandraAuditKeySpace() {
+ return cassandraAuditKeySpace;
+ }
+
+ public void setCassandraAuditKeySpace(String cassandraAuditKeySpace) {
+ this.cassandraAuditKeySpace = cassandraAuditKeySpace;
+ }
+
+ public String getCassandraArtifactKeySpace() {
+ return cassandraArtifactKeySpace;
+ }
+
+ public void setCassandraArtifactKeySpace(String cassandraArtifactKeySpace) {
+ this.cassandraArtifactKeySpace = cassandraArtifactKeySpace;
+ }
+
+ @Override
+ public String toString() {
+ return "Config [catalogBeHost=" + catalogBeHost + ", esHost=" + esHost + ", esPort=" + esPort + ", neoHost="
+ + neoHost + ", neoPort=" + neoPort + ", disributionClientHost=" + disributionClientHost
+ + ", disributionClientPort=" + disributionClientPort + ", errorConfigurationFile="
+ + errorConfigurationFile + ", resourceConfigDir=" + resourceConfigDir + ", componentsConfigDir="
+ + componentsConfigDir + ", importResourceConfigDir=" + importResourceConfigDir
+ + ", importResourceTestsConfigDir=" + importResourceTestsConfigDir + ", importTypesConfigDir="
+ + importTypesConfigDir + ", catalogFeHost=" + catalogFeHost + ", catalogFePort=" + catalogFePort
+ + ", catalogBePort=" + catalogBePort + ", catalogBeTlsPort=" + catalogBeTlsPort + ", neoDBusername="
+ + neoDBusername + ", neoDBpassword=" + neoDBpassword + ", titanPropertiesFile=" + titanPropertiesFile
+ + ", packages=" + packages + ", bugs=" + bugs + ", resourcesNotToDelete=" + resourcesNotToDelete
+ + ", resourceCategoriesNotToDelete=" + resourceCategoriesNotToDelete + ", serviceCategoriesNotToDelete="
+ + serviceCategoriesNotToDelete + ", stopOnClassFailure=" + stopOnClassFailure + ", outputFolder="
+ + outputFolder + ", reportName=" + reportName + ", configurationFile=" + configurationFile + "]";
+ }
+
+ public boolean isRemoteTesting() {
+ return remoteTesting;
+ }
+
+ public void setRemoteTesting(boolean remoteTesting) {
+ this.remoteTesting = remoteTesting;
+ }
+
+ public String getUrl() {
+ try {
+ return url;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getRemoteTestingMachineIP() {
+ return remoteTestingMachineIP;
+ }
+
+ public void setRemoteTestingMachineIP(String remoteTestingMachineIP) {
+ this.remoteTestingMachineIP = remoteTestingMachineIP;
+ }
+
+ public String getRemoteTestingMachinePort() {
+ return remoteTestingMachinePort;
+ }
+
+ public void setRemoteTestingMachinePort(String remoteTestingMachinePort) {
+ this.remoteTestingMachinePort = remoteTestingMachinePort;
+ }
+
+ public Boolean getCassandraAuthenticate() {
+ return cassandraAuthenticate;
+ }
+
+ public void setCassandraAuthenticate(Boolean cassandraAuthenticate) {
+ this.cassandraAuthenticate = cassandraAuthenticate;
+ }
+
+ public String getCassandraUsername() {
+ return cassandraUsername;
+ }
+
+ public void setCassandraUsername(String cassandraUsername) {
+ this.cassandraUsername = cassandraUsername;
+ }
+
+ public String getCassandraPassword() {
+ return cassandraPassword;
+ }
+
+ public void setCassandraPassword(String cassandraPassword) {
+ this.cassandraPassword = cassandraPassword;
+ }
+
+ public Boolean getCassandraSsl() {
+ return cassandraSsl;
+ }
+
+ public void setCassandraSsl(Boolean cassandraSsl) {
+ this.cassandraSsl = cassandraSsl;
+ }
+
+ public String getCassandraTruststorePath() {
+ return cassandraTruststorePath;
+ }
+
+ public void setCassandraTruststorePath(String cassandraTruststorePath) {
+ this.cassandraTruststorePath = cassandraTruststorePath;
+ }
+
+ public String getCassandraTruststorePassword() {
+ return cassandraTruststorePassword;
+ }
+
+ public void setCassandraTruststorePassword(String cassandraTruststorePassword) {
+ this.cassandraTruststorePassword = cassandraTruststorePassword;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java
new file mode 100644
index 0000000000..fbc493ffd6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/config/InvokedMethodListener.java
@@ -0,0 +1,63 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.config;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.testng.IInvokedMethod;
+import org.testng.IInvokedMethodListener;
+import org.testng.ITestResult;
+import org.testng.SkipException;
+import org.testng.internal.TestResult;
+
+public class InvokedMethodListener implements IInvokedMethodListener {
+
+ static Map<String, Integer> methodFailCount = new HashMap<String, Integer>();
+
+ @Override
+
+ public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
+
+ if (methodFailCount.get(method.getTestMethod().getMethodName()) != null
+ && methodFailCount.get(method.getTestMethod().getMethodName()) > 1)
+ throw new SkipException("Skipped due to failure count > 1");
+ ;
+
+ }
+
+ @Override
+
+ public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
+
+ if (testResult.getStatus() == TestResult.FAILURE) {
+ if (methodFailCount.get(method.getTestMethod().getMethodName()) == null)
+ methodFailCount.put(method.getTestMethod().getMethodName(), 1);
+ else {
+ methodFailCount.put(method.getTestMethod().getMethodName(),
+ methodFailCount.get(method.getTestMethod().getMethodName()) + 1);
+ }
+
+ }
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java
new file mode 100644
index 0000000000..41936e2c30
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactAssetStructure.java
@@ -0,0 +1,135 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class ArtifactAssetStructure {
+
+ String artifactName;
+ String artifactType;
+ String artifactURL;
+ String artifactDescription;
+ int artifactTimeout;// optional
+ String artifactChecksum;
+ String artifactUUID;
+ String artifactVersion;
+ String generatedFromUUID;// optional
+
+ public ArtifactAssetStructure(String artifactName, String artifactType, String artifactURL,
+ String artifactDescription, int artifactTimeout, String artifactChecksum, String artifactUUID,
+ String artifactVersion, String generatedFromUUID) {
+ super();
+ this.artifactName = artifactName;
+ this.artifactType = artifactType;
+ this.artifactURL = artifactURL;
+ this.artifactDescription = artifactDescription;
+ this.artifactTimeout = artifactTimeout;
+ this.artifactChecksum = artifactChecksum;
+ this.artifactUUID = artifactUUID;
+ this.artifactVersion = artifactVersion;
+ this.generatedFromUUID = generatedFromUUID;
+ }
+
+ public ArtifactAssetStructure() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(String artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ 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 int getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(int artifactTimeout) {
+ this.artifactTimeout = artifactTimeout;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ 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 getGeneratedFromUUID() {
+ return generatedFromUUID;
+ }
+
+ public void setGeneratedFromUUID(String generatedFromUUID) {
+ this.generatedFromUUID = generatedFromUUID;
+ }
+
+ @Override
+ public String toString() {
+ return "ArtifactAssetStructure [artifactName=" + artifactName + ", artifactType=" + artifactType
+ + ", artifactURL=" + artifactURL + ", artifactDescription=" + artifactDescription + ", artifactTimeout="
+ + artifactTimeout + ", artifactChecksum=" + artifactChecksum + ", artifactUUID=" + artifactUUID
+ + ", artifactVersion=" + artifactVersion + ", generatedFromUUID=" + generatedFromUUID + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java
new file mode 100644
index 0000000000..28606af14d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ArtifactReqDetails.java
@@ -0,0 +1,226 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.model.HeatParameterDefinition;
+
+public class ArtifactReqDetails {
+
+ public ArtifactReqDetails() {
+
+ }
+
+ public ArtifactReqDetails(String artifactName, String artifactType, String artifactDescription, String payloadData,
+ String artifactLable) {
+ super();
+ this.artifactName = artifactName;
+ this.artifactType = artifactType;
+ this.description = artifactDescription;
+ this.payloadData = payloadData;
+ this.artifactLabel = artifactLable;
+ }
+
+ public ArtifactReqDetails(String artifactLable, ArtifactReqDetails a) {
+ super();
+ this.artifactName = a.getArtifactName();
+ this.artifactType = a.getArtifactType();
+ this.description = a.getArtifactType();
+ this.payloadData = a.getPayload();
+ this.artifactLabel = artifactLable;
+ }
+
+ private String uniqueId;
+ private String artifactName;
+ private String artifactType;
+ private String description;
+ private String payloadData;
+ private String artifactLabel;
+ private String apiUrl;
+ private String artifactGroupType;
+ private Integer timeout;
+ private String userIdLastUpdater;
+ private String creatorFullName;
+ private String updaterFullName;
+ private String artifactChecksum;
+ private String artifactDisplayName;
+ private List<HeatParameterDefinition> heatParameters;
+
+ private boolean mandatory;
+ private boolean serviceApi;
+
+ public boolean isServiceApi() {
+ return serviceApi;
+ }
+
+ public void setServiceApi(boolean serviceApi) {
+ this.serviceApi = serviceApi;
+ }
+
+ public String getArtifactLabel() {
+ return artifactLabel;
+ }
+
+ public void setArtifactLabel(String artifactLabel) {
+ this.artifactLabel = artifactLabel;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(String artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getPayload() {
+ return payloadData;
+ }
+
+ public void setPayload(String payload) {
+ this.payloadData = payload;
+ }
+
+ public void setPayloadData(String payloadData) {
+ this.payloadData = payloadData;
+ }
+
+ public String getArtifactGroupType() {
+ return artifactGroupType;
+ }
+
+ public void setArtifactGroupType(String artifactGroupType) {
+ this.artifactGroupType = artifactGroupType;
+ }
+
+ public Integer getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(Integer timeout) {
+ this.timeout = timeout;
+ }
+
+ public boolean isMandatory() {
+ return mandatory;
+ }
+
+ public void setMandatory(boolean mandatory) {
+ this.mandatory = mandatory;
+ }
+
+ public String getUrl() {
+ return apiUrl;
+ }
+
+ public void setUrl(String url) {
+ this.apiUrl = url;
+ }
+
+ @Override
+ public String toString() {
+ if (!apiUrl.isEmpty()) {
+ return "ArtifactReqDetails [artifactName=" + artifactName + ", artifactType=" + artifactType
+ + ", description=" + description + ", payloadData=" + payloadData + ", artifactLabel="
+ + artifactLabel + ", mandatory=" + mandatory + ", url=" + apiUrl + "]";
+ }
+
+ return "ArtifactReqDetails [artifactName=" + artifactName + ", artifactType=" + artifactType + ", description="
+ + description + ", payloadData=" + payloadData + ", artifactLabel=" + artifactLabel
+ + ", artifactUniqueId=" + uniqueId + ", mandatory=" + mandatory + ", serviceApi=" + serviceApi + "]";
+
+ }
+
+ public String getArtifactDisplayName() {
+
+ return artifactDisplayName;
+ }
+
+ public void setArtifactDisplayName(String artifactDisplayName) {
+ this.artifactDisplayName = artifactDisplayName;
+ }
+
+ public String getUserIdLastUpdater() {
+ return userIdLastUpdater;
+ }
+
+ public void setUserIdLastUpdater(String userIdLastUpdater) {
+ this.userIdLastUpdater = userIdLastUpdater;
+ }
+
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
+
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
+
+ public String getUpdaterFullName() {
+ return updaterFullName;
+ }
+
+ public void setUpdaterFullName(String updaterFullName) {
+ this.updaterFullName = updaterFullName;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String artifactUniqueId) {
+ this.uniqueId = artifactUniqueId;
+ }
+
+ public List<HeatParameterDefinition> getHeatParameters() {
+ return heatParameters;
+ }
+
+ public void setHeatParameters(List<HeatParameterDefinition> heatParameters) {
+ this.heatParameters = heatParameters;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java
new file mode 100644
index 0000000000..8820b05772
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AssetStructure.java
@@ -0,0 +1,122 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class AssetStructure {
+
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
+ private String category;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+
+ public AssetStructure() {
+ super();
+ }
+
+ public AssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL,
+ String category, String lifecycleState, String lastUpdaterUserId) {
+ super();
+ this.uuid = uuid;
+ this.invariantUUID = invariantUUID;
+ this.name = name;
+ this.version = version;
+ this.toscaModelURL = toscaModelURL;
+ this.category = category;
+ this.lifecycleState = lifecycleState;
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ @Override
+ public String toString() {
+ return "AssetStructure [uuid=" + uuid + ", invariantUUID=" + invariantUUID + ", name=" + name + ", version="
+ + version + ", toscaModelURL=" + toscaModelURL + ", category=" + category + ", lifecycleState="
+ + lifecycleState + ", lastUpdaterUserId=" + lastUpdaterUserId + "]";
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getToscaModelURL() {
+ return toscaModelURL;
+ }
+
+ public void setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java
new file mode 100644
index 0000000000..549700f384
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentInstanceReqDetails.java
@@ -0,0 +1,121 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import org.openecomp.sdc.be.model.ComponentInstance;
+
+public class ComponentInstanceReqDetails {
+
+ String componentUid;
+ String description;
+ String posX;
+ String posY;
+ String name;
+ String uniqueId;
+
+ public ComponentInstanceReqDetails() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public ComponentInstanceReqDetails(ComponentInstance componentInstance) {
+ super();
+ this.setUniqueId(componentInstance.getUniqueId());
+ this.description = componentInstance.getDescription();
+ this.posX = componentInstance.getPosX();
+ this.posY = componentInstance.getPosY();
+ // this.name = "myResourceInstance";
+ this.name = componentInstance.getName();
+ }
+
+ public ComponentInstanceReqDetails(String resourceUid, String description, String posX, String posY, String name) {
+ super();
+ this.componentUid = resourceUid;
+ this.description = description;
+ this.posX = posX;
+ this.posY = posY;
+ // this.name = "myResourceInstance";
+ this.name = name;
+ }
+
+ public ComponentInstanceReqDetails(String resourceUid, String description, String posX, String posY) {
+ super();
+ this.componentUid = resourceUid;
+ this.description = description;
+ this.posX = posX;
+ this.posY = posY;
+ }
+
+ public String getComponentUid() {
+ return componentUid;
+ }
+
+ public void setComponentUid(String resourceUid) {
+ this.componentUid = resourceUid;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getPosX() {
+ return posX;
+ }
+
+ public void setPosX(String posX) {
+ this.posX = posX;
+ }
+
+ public String getPosY() {
+ return posY;
+ }
+
+ public void setPosY(String posY) {
+ this.posY = posY;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceInstanceReqDetails [resourceUid=" + componentUid + ", description=" + description + ", posX="
+ + posX + ", posY=" + posY + ", name=" + name + ", uniqueId=" + uniqueId + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java
new file mode 100644
index 0000000000..8546732414
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ComponentReqDetails.java
@@ -0,0 +1,272 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+
+public abstract class ComponentReqDetails {
+
+ protected String name;
+ protected String description;
+ protected List<String> tags = new ArrayList<>();
+ protected String contactId;
+ protected String icon;
+ protected String uniqueId;
+ protected String creatorUserId;
+ protected String creatorFullName;
+ protected String lastUpdaterUserId;
+ protected String lastUpdaterFullName;
+ protected Long creationDate;
+ protected Long lastUpdateDate;
+ protected LifecycleStateEnum lifecycleState;
+ protected String version;
+ protected String UUID;
+ protected List<CategoryDefinition> categories;
+ protected String projectCode;
+ protected String csarUUID;
+ protected String csarVersion;
+ protected String importedToscaChecksum;
+ protected String invariantUUID;
+
+ public String getCsarVersion() {
+ return csarVersion;
+ }
+
+ public void setCsarVersion(String csarVersion) {
+ this.csarVersion = csarVersion;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ tags.add(name);
+ }
+
+ public List<String> getTags() {
+ return tags;
+ }
+
+ public void setTags(List<String> tags) {
+ this.tags = tags;
+ }
+
+ // public String getCategory() {
+ // return category;
+ // }
+ //
+ 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 getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
+
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public void setCreationDate(Long creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public void setLastUpdateDate(Long lastUpdateDate) {
+ this.lastUpdateDate = lastUpdateDate;
+ }
+
+ public void setLifecycleState(LifecycleStateEnum lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public void setUUID(String uUID) {
+ this.UUID = uUID;
+ }
+
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
+
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public Long getCreationDate() {
+ return creationDate;
+ }
+
+ public Long getLastUpdateDate() {
+ return lastUpdateDate;
+ }
+
+ public LifecycleStateEnum getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public String getUUID() {
+ return UUID;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+
+ public void removeAllCategories() {
+ this.categories = new ArrayList<>();
+ }
+
+ public void addCategoryChain(String category, String subCategory) {
+ if (category != null || subCategory != null) {
+ if (categories == null) {
+ categories = new ArrayList<>();
+ }
+ CategoryDefinition selectedCategory = null;
+ for (CategoryDefinition categoryDef : categories) {
+ if (categoryDef.getName().equals(category)) {
+ selectedCategory = categoryDef;
+ }
+ }
+ if (selectedCategory == null) {
+ selectedCategory = new CategoryDefinition();
+ selectedCategory.setName(category);
+ categories.add(selectedCategory);
+ }
+ if (subCategory != null) {
+ List<SubCategoryDefinition> subcategories = selectedCategory.getSubcategories();
+ if (subcategories == null) {
+ subcategories = new ArrayList<>();
+ selectedCategory.setSubcategories(subcategories);
+ }
+ SubCategoryDefinition selectedSubcategory = null;
+ for (SubCategoryDefinition subcategory : subcategories) {
+ if (subcategory.getName().equals(subCategory)) {
+ selectedSubcategory = subcategory;
+ }
+ }
+ if (selectedSubcategory == null) {
+ selectedSubcategory = new SubCategoryDefinition();
+ selectedSubcategory.setName(subCategory);
+ subcategories.add(selectedSubcategory);
+ }
+ }
+ }
+ }
+
+ public void addCategory(String category) {
+ addCategoryChain(category, null);
+ }
+
+ public String getProjectCode() {
+ return projectCode;
+ }
+
+ public void setProjectCode(String projectCode) {
+ this.projectCode = projectCode;
+ }
+
+ public String getCsarUUID() {
+ return csarUUID;
+ }
+
+ public void setCsarUUID(String csarUUID) {
+ this.csarUUID = csarUUID;
+ }
+
+ public String getImportedToscaChecksum() {
+ return importedToscaChecksum;
+ }
+
+ public void setImportedToscaChecksum(String importedToscaChecksum) {
+ this.importedToscaChecksum = importedToscaChecksum;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java
new file mode 100644
index 0000000000..690f63955d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/GroupHeatMetaDefinition.java
@@ -0,0 +1,60 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class GroupHeatMetaDefinition {
+
+ int group = 0;
+ List<String> artifactList = new ArrayList<String>();
+ PropertyHeatMetaDefinition propertyHeatMetaDefinition;
+
+ public PropertyHeatMetaDefinition getPropertyHeatMetaDefinition() {
+ return propertyHeatMetaDefinition;
+ }
+
+ public void setPropertyHeatMetaDefinition(PropertyHeatMetaDefinition propertyHeatMetaDefinition) {
+ this.propertyHeatMetaDefinition = propertyHeatMetaDefinition;
+ }
+
+ public GroupHeatMetaDefinition() {
+ super();
+ }
+
+ public int getGroup() {
+ return group;
+ }
+
+ public void setGroup(int group) {
+ this.group = group;
+ }
+
+ public List<String> getArtifactList() {
+ return artifactList;
+ }
+
+ public void setArtifactList(List<String> artifactList) {
+ this.artifactList = artifactList;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java
new file mode 100644
index 0000000000..0089eec5a7
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ImportReqDetails.java
@@ -0,0 +1,332 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.yaml.snakeyaml.Yaml;
+
+public class ImportReqDetails extends ResourceReqDetails {
+
+ private String payloadName;
+ private String payloadData;
+
+ private Map<String, Object> requirements;
+ private Map<String, Object> capabilities;
+
+ private List<String> derivedList;
+ private String derivedFromField;
+
+ public ImportReqDetails(String resourceName, String description, List<String> tags, List<String> derivedFrom,
+ String vendorName, String vendorRelease, String contactId, String icon) {
+ super(resourceName, description, tags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ }
+
+ public String getPayloadName() {
+ return payloadName;
+ }
+
+ public void setPayloadName(String payloadName) {
+ this.payloadName = payloadName;
+ }
+
+ public String getPayloadData() {
+ return payloadData;
+ }
+
+ public void setPayloadData(String payloadData) {
+ this.payloadData = payloadData;
+ }
+
+ @Override
+ public String toString() {
+ return "ImportReqDetails [payloadName=" + payloadName + ", payloadData=" + payloadData + "]";
+ }
+
+ public void setReqirementsAndCapabilities(String path, String fileName, User user, String derivedFromSource)
+ throws Exception {
+ setRequirements(path, fileName, user, derivedFromSource);
+ setCapabilities(path, fileName, user, derivedFromSource);
+ }
+
+ public List<String> getDerivedList() {
+ return derivedList;
+ }
+
+ public void setDerivedList(List<String> derivedList) {
+ this.derivedList = derivedList;
+ }
+
+ public String getDerivedFromField() {
+ return derivedFromField;
+ }
+
+ public void setDerivedFromField(String derivedFromField) {
+ this.derivedFromField = derivedFromField;
+ }
+
+ public Map<String, Object> getRequirements() {
+ return requirements;
+ }
+
+ public void setRequirements(String path, String fileName, User user, String derivedFromSource) throws Exception {
+ Map<String, Object> requirementsFromFile = getRequirementsMapFromFile(path + File.separator + fileName,
+ toscaResourceName, "requirements");
+ Map<String, Object> requirements = organizeRequirementsMap(requirementsFromFile);
+ getDerivedReqCap(user, requirements, "requirements", derivedFromSource);
+ this.requirements = requirements;
+ }
+
+ private void getDerivedReqCap(User user, Map<String, Object> reqCapMap, String field, String derivedFromResource)
+ throws IOException, JSONException {
+
+ if (derivedFromResource == null) {
+ derivedFromResource = "Root";
+ }
+
+ RestResponse rest = getResourceSource(user, derivedFromResource);
+ Map<String, Object> parsedFieldFromResponseAsMap = ResponseParser.getJsonValueAsMap(rest, field);
+ Iterator<String> iterator = parsedFieldFromResponseAsMap.keySet().iterator();
+ Map<String, Object> convertListToMap = null;
+ while (iterator.hasNext()) {
+ String type = iterator.next();
+ List<Object> lst = (List<Object>) parsedFieldFromResponseAsMap.get(type);
+ convertListToMap = convertListToMap(lst);
+
+ if (field.equals("capabilities")) {
+ convertListToMap.replace("capabilitySources", derivedList);
+ lst = new ArrayList<Object>(Arrays.asList(convertListToMap));
+ }
+
+ Object existingValue = reqCapMap.get(type);
+ if (existingValue != null) {
+ Map<String, Object> convertedExistingValue = convertListToMap((List<Object>) existingValue);
+ if (convertedExistingValue.get("name").toString().toLowerCase()
+ .equals(convertListToMap.get("name").toString().toLowerCase())) {
+ lst = new ArrayList<Object>(Arrays.asList(convertedExistingValue));
+ } else {
+ lst.add(convertedExistingValue);
+ }
+ }
+
+ reqCapMap.put(type, lst);
+ }
+ }
+
+ private RestResponse getResourceSource(User user, String source) throws IOException, JSONException {
+ org.codehaus.jettison.json.JSONObject getResourceJSONObject = null;
+ RestResponse rest = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), source, "1.0");
+ if (rest.getErrorCode().intValue() == 200) {
+ JSONArray jArray = new JSONArray(rest.getResponse());
+ for (int i = 0; i < jArray.length(); i++) {
+ getResourceJSONObject = jArray.getJSONObject(i);
+ String resourceType = getResourceJSONObject.get("resourceType").toString();
+ if (!resourceType.equals("VF")) {
+ rest.setResponse(getResourceJSONObject.toString());
+ }
+ }
+ }
+ return rest;
+ }
+
+ public Map<String, Object> getCapabilities() {
+ return capabilities;
+ }
+
+ public void setCapabilities(String path, String fileName, User user, String derivedFromSource) throws Exception {
+ Map<String, Object> capabilitiesFromFile = getCapabilitiesMapFromFile(path + File.separator + fileName,
+ toscaResourceName, "capabilities");
+ Map<String, Object> capabilities = organizeCapabilitiesMap(capabilitiesFromFile);
+ getDerivedReqCap(user, capabilities, "capabilities", derivedFromSource);
+ this.capabilities = capabilities;
+ }
+
+ private Map<String, Object> organizeCapabilitiesMap(Map<String, Object> capabilitiesFromFile) {
+ Iterator<String> iterator = capabilitiesFromFile.keySet().iterator();
+ Map<String, Object> capMap = new HashMap<String, Object>();
+ while (iterator.hasNext()) {
+ List<Object> valueList = new ArrayList<Object>();
+ String next = iterator.next();
+ Map<String, Object> valuesMap = (Map<String, Object>) capabilitiesFromFile.get(next);
+ String key = valuesMap.remove("type").toString();
+ valuesMap.put("name", next);
+ valuesMap.put("capabilitySources", derivedList);
+ valuesMap.put("type", key);
+
+ if (!valuesMap.containsKey("occurrences")) {
+ valuesMap.put("minOccurrences", "1");
+ valuesMap.put("maxOccurrences", "UNBOUNDED");
+ }
+
+ Object tempValue = capMap.get(key);
+ if (tempValue == null) {
+ valueList.add(valuesMap);
+ } else {
+ Map<String, Object> convertValue = convertListToMap((List<Object>) tempValue);
+ valueList = new ArrayList<Object>(Arrays.asList(convertValue, valuesMap));
+ }
+ capMap.put(key, valueList);
+ }
+ return capMap;
+ }
+
+ private Map<String, Object> getCapabilitiesMapFromFile(String fileName, String toscaResourceName,
+ String fieldToTest) throws Exception {
+ Map<String, Object> resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName);
+ Object capMap = resourceToscaMap.get(fieldToTest);
+ if (capMap == null) {
+ return new HashMap<String, Object>();
+ }
+ return (Map<String, Object>) capMap;
+ }
+
+ private Map<String, Object> organizeRequirementsMap(Map<String, Object> requirementsFromFile) {
+ Map<String, Object> reqMap = new HashMap<String, Object>();
+ List<Object> valueList = new ArrayList<Object>();
+ Iterator<String> iterator = requirementsFromFile.keySet().iterator();
+ while (iterator.hasNext()) {
+ String key = iterator.next();
+ Map<String, Object> valuesMap = (Map<String, Object>) requirementsFromFile.get(key);
+ valuesMap.put("name", key);
+ String capability = valuesMap.get("capability").toString();
+
+ List<Object> occurencesList = (List<Object>) valuesMap.remove("occurrences");
+ if (occurencesList != null) {
+ valuesMap.put("minOccurrences", occurencesList.get(0).toString());
+ valuesMap.put("maxOccurrences", occurencesList.get(1).toString());
+ }
+
+ valueList.add(valuesMap);
+ reqMap.put(capability, valueList);
+ }
+
+ return reqMap;
+ }
+
+ private Map<String, Object> getRequirementsMapFromFile(String fileName, String toscaResourceName,
+ String fieldToTest) throws Exception {
+ Map<String, Object> resourceToscaMap = getToscaResourceFromFile(fileName, toscaResourceName);
+ List<Object> reqListFromFile = (List<Object>) resourceToscaMap.get(fieldToTest);
+ if (reqListFromFile == null) {
+ return new HashMap<String, Object>();
+ }
+ Map<String, Object> testedMapFromFile = convertListToMap(reqListFromFile);
+ return testedMapFromFile;
+ }
+
+ private Map<String, Object> getToscaResourceFromFile(String fullFileName, String toscaResourceName)
+ throws Exception {
+ Map<String, Object> nodesTypesMap = getNodesTypesMapFromFile(fullFileName);
+ Map<String, Object> resourceToscaMap = (Map<String, Object>) nodesTypesMap.get(toscaResourceName);
+
+ derivedFromField = resourceToscaMap.get("derived_from").toString();
+
+ return resourceToscaMap;
+ }
+
+ private Map<String, Object> getNodesTypesMapFromFile(String fullFileName) throws FileNotFoundException {
+ Yaml yaml = new Yaml();
+ File file = new File(fullFileName);
+ InputStream inputStream = new FileInputStream(file);
+ Map<?, ?> mapFromFile = (Map<?, ?>) yaml.load(inputStream);
+ Map<String, Object> nodesTypesMap = (Map<String, Object>) mapFromFile.get("node_types");
+ return nodesTypesMap;
+ }
+
+ private Map<String, Object> convertListToMap(List<Object> testedListFromFile) {
+ Map<String, Object> testedMapFromFile = new HashMap<String, Object>();
+ for (int i = 0; i < testedListFromFile.size(); i++) {
+ Object req = testedListFromFile.get(i);
+ ObjectMapper m = new ObjectMapper();
+ Map<? extends String, ? extends String> mappedObject = m.convertValue(req, Map.class);
+ testedMapFromFile.putAll(mappedObject);
+ }
+ return testedMapFromFile;
+ }
+
+ public void compareRequirementsOrCapabilities(Map<String, Object> exepectedReq, Map<String, Object> actualReq) {
+ Iterator<String> iterator = exepectedReq.keySet().iterator();
+ while (iterator.hasNext()) {
+ String key = iterator.next();
+ List<Object> expectedValues = (List<Object>) exepectedReq.get(key);
+ List<Object> actualValues = (List<Object>) actualReq.get(key);
+ assertNotNull(actualValues);
+
+ List<Map<String, Object>> expectedMapsList = convertListToMapList(expectedValues);
+ List<Map<String, Object>> actualMapsList = convertListToMapList(actualValues);
+ assertEquals(expectedMapsList.size(), actualMapsList.size());
+
+ for (int i = 0; i < expectedMapsList.size(); i++) {
+ Map<String, Object> expectedMap = expectedMapsList.get(i);
+ Map<String, Object> actualdMap = actualMapsList.get(i);
+ if (expectedMap.get("name").equals(actualdMap.get("name"))) {
+ Iterator<String> iterator2 = expectedMap.keySet().iterator();
+ while (iterator2.hasNext()) {
+ String innerKey = iterator2.next();
+ assertTrue(
+ "check " + innerKey + " in " + key + ":\nexpected: "
+ + expectedMap.get(innerKey).toString() + "\nactual: "
+ + actualdMap.get(innerKey).toString(),
+ expectedMap.get(innerKey).equals(actualdMap.get(innerKey)));
+
+ }
+
+ }
+ }
+ }
+ }
+
+ private List<Map<String, Object>> convertListToMapList(List<Object> testedListFromFile) {
+ List<Map<String, Object>> listOfMaps = new ArrayList<Map<String, Object>>();
+ for (int i = 0; i < testedListFromFile.size(); i++) {
+ Object req = testedListFromFile.get(i);
+ ObjectMapper m = new ObjectMapper();
+ Map<? extends String, ? extends String> mappedObject = m.convertValue(req, Map.class);
+ mappedObject.remove("uniqueId");
+ Map<String, Object> testedMapFromFile = new HashMap<String, Object>();
+ testedMapFromFile.putAll(mappedObject);
+ listOfMaps.add(testedMapFromFile);
+ }
+ return listOfMaps;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java
new file mode 100644
index 0000000000..f2484e274d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ProductReqDetails.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class ProductReqDetails extends ComponentReqDetails {
+
+ private String fullName;
+ private List<String> contacts;
+ private String isActive;
+
+ public ProductReqDetails(String name, List<CategoryDefinition> category) {
+ this.categories = category;
+ this.name = name;
+ }
+
+ public ProductReqDetails(String name) {
+ this.name = name;
+ }
+
+ public void addCategory(CategoryDefinition category) {
+ if (categories == null) {
+ categories = new ArrayList<>();
+ }
+ categories.add(category);
+ }
+
+ public void addContact(String contactUserId) {
+ if (contacts == null) {
+ contacts = new ArrayList<>();
+ }
+ contacts.add(contactUserId);
+ }
+
+ public List<String> getContacts() {
+ return contacts;
+ }
+
+ public void setContacts(List<String> contacts) {
+ this.contacts = contacts;
+ }
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public String getActive() {
+ return isActive;
+ }
+
+ public void setActive(String isActive) {
+ this.isActive = isActive;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java
new file mode 100644
index 0000000000..6271e1f59d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyHeatMetaDefinition.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class PropertyHeatMetaDefinition {
+
+ String name;
+ boolean value;
+
+ public PropertyHeatMetaDefinition() {
+ super();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean isValue() {
+ return value;
+ }
+
+ public void setValue(boolean value) {
+ this.value = value;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "PropertyHeatMetaDefinition [name=" + name + ", value=" + value + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java
new file mode 100644
index 0000000000..208e4aa3ea
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/PropertyReqDetails.java
@@ -0,0 +1,145 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+
+public class PropertyReqDetails {
+ String name;
+ String type;
+ Boolean required = false;
+ String defaultValue;
+ String description;
+ String propertyRangeMin;
+ String propertyRangeMax;
+ Boolean isPassword = false;
+ SchemaDefinition schema;
+
+ public PropertyReqDetails() {
+ super();
+ }
+
+ public PropertyReqDetails(String propertyName, String propertyType, Boolean propertyRequired,
+ String propertyDefaultValue, String propertyDescription, String propertyRangeMin, String propertyRangeMax,
+ Boolean propertyPassword) {
+ super();
+ this.name = propertyName;
+ this.type = propertyType;
+ this.required = propertyRequired;
+ this.defaultValue = propertyDefaultValue;
+ this.description = propertyDescription;
+ this.propertyRangeMin = propertyRangeMin;
+ this.propertyRangeMax = propertyRangeMax;
+ this.isPassword = propertyPassword;
+ }
+
+ public PropertyReqDetails(String propertyName, String propertyType, String propertyDefaultValue,
+ String propertyDescription, SchemaDefinition schema) {
+ super();
+ this.name = propertyName;
+ this.type = propertyType;
+ this.defaultValue = propertyDefaultValue;
+ this.description = propertyDescription;
+ this.schema = schema;
+ }
+
+ public SchemaDefinition getSchema() {
+ return schema;
+ }
+
+ public void setSchema(SchemaDefinition schema) {
+ this.schema = schema;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String propertyName) {
+ this.name = propertyName;
+ }
+
+ public String getPropertyType() {
+ return type;
+ }
+
+ public void setPropertyType(String propertyType) {
+ this.type = propertyType;
+ }
+
+ public Boolean getPropertyRequired() {
+ return required;
+ }
+
+ public void setPropertyRequired(Boolean propertyRequired) {
+ this.required = propertyRequired;
+ }
+
+ public String getPropertyDefaultValue() {
+ return defaultValue;
+ }
+
+ public void setPropertyDefaultValue(String propertyDefaultValue) {
+ this.defaultValue = propertyDefaultValue;
+ }
+
+ public String getPropertyDescription() {
+ return description;
+ }
+
+ public void setPropertyDescription(String propertyDescription) {
+ this.description = propertyDescription;
+ }
+
+ public String getPropertyRangeMin() {
+ return propertyRangeMin;
+ }
+
+ public void setPropertyRangeMin(String propertyRangeMin) {
+ this.propertyRangeMin = propertyRangeMin;
+ }
+
+ public String getPropertyRangeMax() {
+ return propertyRangeMax;
+ }
+
+ public void setPropertyRangeMax(String propertyRangeMax) {
+ this.propertyRangeMax = propertyRangeMax;
+ }
+
+ public Boolean getPropertyPassword() {
+ return isPassword;
+ }
+
+ public void setPropertyPassword(Boolean propertyPassword) {
+ this.isPassword = propertyPassword;
+ }
+
+ public String propertyToJsonString() {
+ String jsonString;
+ jsonString = "{\"" + this.getName() + "\":{" + "\"type\":\"" + this.getPropertyType() + "\"," + "\"required\":"
+ + this.getPropertyRequired() + "," + "\"defaultValue\":\"" + this.getPropertyDefaultValue() + "\","
+ + "\"description\":\"" + this.getPropertyDescription() + "\"," + "\"constraints\":[{\"inRange\":[\""
+ + this.getPropertyRangeMin() + "\",\"" + this.getPropertyRangeMax() + "\"]}]," + "\"isPassword\":"
+ + this.getPropertyPassword() + "}}";
+ return jsonString;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java
new file mode 100644
index 0000000000..d429d05a51
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceAssetStructure.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class ResourceAssetStructure extends AssetStructure {
+
+ private String subCategory;
+ private String resourceType;
+
+ public ResourceAssetStructure() {
+ super();
+ }
+
+ public ResourceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL,
+ String category, String lifecycleState, String lastUpdaterUserId) {
+ super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId);
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceAssetStructure [subCategory=" + subCategory + ", resourceType=" + resourceType + "]";
+ }
+
+ public String getSubCategory() {
+ return subCategory;
+ }
+
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java
new file mode 100644
index 0000000000..737343f24c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceDetailedAssetStructure.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+public class ResourceDetailedAssetStructure extends ResourceAssetStructure {
+
+ private String lastUpdaterFullName;
+ private String toscaResourceName;
+ private List<ResourceInstanceAssetStructure> resources;
+ private List<ArtifactAssetStructure> artifacts;
+
+ public ResourceDetailedAssetStructure() {
+ super();
+ }
+
+ public ResourceDetailedAssetStructure(String lastUpdaterFullName, String toscaResourceName,
+ List<ResourceInstanceAssetStructure> resources, List<ArtifactAssetStructure> artifacts) {
+ super();
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ this.toscaResourceName = toscaResourceName;
+ this.resources = resources;
+ this.artifacts = artifacts;
+ }
+
+ 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 List<ResourceInstanceAssetStructure> getResources() {
+ return resources;
+ }
+
+ public void setResources(List<ResourceInstanceAssetStructure> resources) {
+ this.resources = resources;
+ }
+
+ public List<ArtifactAssetStructure> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactAssetStructure> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", toscaResourceName="
+ + toscaResourceName + ", resources=" + resources + ", artifacts=" + artifacts + ", toString()="
+ + super.toString() + ", getSubCategory()=" + getSubCategory() + ", getResourceType()="
+ + getResourceType() + ", getUuid()=" + getUuid() + ", getInvariantUUID()=" + getInvariantUUID()
+ + ", getName()=" + getName() + ", getVersion()=" + getVersion() + ", getToscaModelURL()="
+ + getToscaModelURL() + ", getCategory()=" + getCategory() + ", getLifecycleState()="
+ + getLifecycleState() + ", getLastUpdaterUserId()=" + getLastUpdaterUserId() + ", getClass()="
+ + getClass() + ", hashCode()=" + hashCode() + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java
new file mode 100644
index 0000000000..6a69120a05
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceInstanceAssetStructure.java
@@ -0,0 +1,116 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+public class ResourceInstanceAssetStructure {
+
+ String resourceInstanceName;
+ String resourceName;
+ String resourceInvariantUUID;
+ String resourceVersion;
+ String resoucreType;
+ String resourceUUID;
+ List<ArtifactAssetStructure> artifacts;
+
+ public ResourceInstanceAssetStructure() {
+ super();
+ }
+
+ public ResourceInstanceAssetStructure(String resourceInstanceName, String resourceName,
+ String resourceInvariantUUID, String resourceVersion, String resoucreType, String resourceUUID,
+ List<ArtifactAssetStructure> artifacts) {
+ super();
+ this.resourceInstanceName = resourceInstanceName;
+ this.resourceName = resourceName;
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ this.resourceVersion = resourceVersion;
+ this.resoucreType = resoucreType;
+ this.resourceUUID = resourceUUID;
+ this.artifacts = artifacts;
+ }
+
+ public String getResourceInstanceName() {
+ return resourceInstanceName;
+ }
+
+ public void setResourceInstanceName(String resourceInstanceName) {
+ this.resourceInstanceName = resourceInstanceName;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceInvariantUUID() {
+ return resourceInvariantUUID;
+ }
+
+ public void setResourceInvariantUUID(String resourceInvariantUUID) {
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public String getResoucreType() {
+ return resoucreType;
+ }
+
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
+ }
+
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ public List<ArtifactAssetStructure> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactAssetStructure> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceInstanceAssetStructure [resourceInstanceName=" + resourceInstanceName + ", resourceName="
+ + resourceName + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion="
+ + resourceVersion + ", resoucreType=" + resoucreType + ", resourceUUID=" + resourceUUID + ", artifacts="
+ + artifacts + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
new file mode 100644
index 0000000000..8456e5b35b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java
@@ -0,0 +1,220 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+
+public class ResourceReqDetails extends ComponentReqDetails {
+ List<String> derivedFrom;
+ String vendorName;
+ String vendorRelease;
+
+ // Unsettable/unupdatable fields
+
+ Boolean isAbstract;
+ Boolean isHighestVersion;
+ String cost;
+ String licenseType;
+ String toscaResourceName;
+
+ private String resourceType = ResourceTypeEnum.VFC.toString(); // Default
+ // value
+
+ public ResourceReqDetails() {
+ super();
+ }
+
+ public ResourceReqDetails(Resource resource) {
+ super();
+ this.resourceType = resource.getResourceType().toString();
+ this.name = resource.getName();
+ this.description = resource.getDescription();
+ this.tags = resource.getTags();
+ // this.category = resource.getCategories();
+ this.derivedFrom = resource.getDerivedFrom();
+ this.vendorName = resource.getVendorName();
+ this.vendorRelease = resource.getVendorRelease();
+ this.contactId = resource.getContactId();
+ this.icon = resource.getIcon();
+ this.toscaResourceName = resource.getToscaResourceName();
+ this.uniqueId = resource.getUniqueId();
+ this.creatorUserId = resource.getCreatorUserId();
+ this.creatorFullName = resource.getCreatorFullName();
+ this.lastUpdaterUserId = resource.getLastUpdaterUserId();
+ this.lastUpdaterFullName = resource.getLastUpdaterFullName();
+ this.lifecycleState = resource.getLifecycleState();
+ this.version = resource.getVersion();
+ this.UUID = resource.getUUID();
+ this.categories = resource.getCategories();
+ this.importedToscaChecksum = resource.getImportedToscaChecksum();
+
+ }
+
+ public ResourceReqDetails(String resourceName, String description, List<String> tags, String category,
+ List<String> derivedFrom, String vendorName, String vendorRelease, String contactId, String icon) {
+ this(resourceName, description, tags, category, derivedFrom, vendorName, vendorRelease, contactId, icon,
+ ResourceTypeEnum.VFC.toString());
+ }
+
+ // new
+ public ResourceReqDetails(String resourceName, String description, List<String> tags, String category,
+ List<String> derivedFrom, String vendorName, String vendorRelease, String contactId, String icon,
+ String resourceType) {
+ super();
+ this.resourceType = resourceType;
+ this.name = resourceName;
+ this.description = description;
+ this.tags = tags;
+ // this.category = category;
+ this.derivedFrom = derivedFrom;
+ this.vendorName = vendorName;
+ this.vendorRelease = vendorRelease;
+ this.contactId = contactId;
+ this.icon = icon;
+ if (category != null) {
+ String[] arr = category.split("/");
+ if (arr.length == 2) {
+ addCategoryChain(arr[0], arr[1]);
+ }
+ }
+ this.toscaResourceName = resourceName;
+ }
+
+ public ResourceReqDetails(ResourceReqDetails originalResource, String version) {
+ super();
+ this.name = originalResource.getName();
+ this.description = originalResource.getDescription();
+ this.tags = originalResource.getTags();
+ // this.category = originalResource.getCategory();
+ this.derivedFrom = originalResource.getDerivedFrom();
+ this.vendorName = originalResource.getVendorName();
+ this.vendorRelease = originalResource.getVendorRelease();
+ this.contactId = originalResource.getContactId();
+ this.icon = originalResource.getIcon();
+ this.version = version;
+ this.uniqueId = originalResource.getUniqueId();
+ this.categories = originalResource.getCategories();
+ this.toscaResourceName = originalResource.getToscaResourceName();
+ this.resourceType = originalResource.getResourceType();
+ }
+
+ public ResourceReqDetails(String resourceName, List<String> derivedFrom, String vendorName, String vendorRelease,
+ String resourceVersion, Boolean isAbstract, Boolean isHighestVersion, String cost, String licenseType,
+ String resourceType) {
+ super();
+ this.name = resourceName;
+ this.derivedFrom = derivedFrom;
+ this.vendorName = vendorName;
+ this.vendorRelease = vendorRelease;
+ this.version = resourceVersion;
+ this.isAbstract = isAbstract;
+ this.isHighestVersion = isHighestVersion;
+ this.cost = cost;
+ this.licenseType = licenseType;
+ this.resourceType = resourceType;
+ this.toscaResourceName = resourceName;
+ }
+
+ public String getToscaResourceName() {
+ return toscaResourceName;
+ }
+
+ public void setToscaResourceName(String toscaResourceName) {
+ this.toscaResourceName = toscaResourceName;
+ }
+
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ 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;
+ }
+
+ public String getCost() {
+ return cost;
+ }
+
+ public void setCost(String cost) {
+ this.cost = cost;
+ }
+
+ public String getLicenseType() {
+ return licenseType;
+ }
+
+ public void setLicenseType(String licenseType) {
+ this.licenseType = licenseType;
+ }
+
+ // Unupdatable fields - to check that they are not updated
+ public void setIsAbstract(Boolean isAbstract) {
+ this.isAbstract = isAbstract;
+ }
+
+ public void setIsHighestVersion(Boolean isHighestVersion) {
+ this.isHighestVersion = isHighestVersion;
+ }
+
+ public Boolean getIsAbstract() {
+ return isAbstract;
+ }
+
+ public Boolean getIsHighestVersion() {
+ return isHighestVersion;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceReqDetails [name=" + name + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName
+ + ", vendorRelease=" + vendorRelease + ", version=" + version + ", isAbstract=" + isAbstract
+ + ", isHighestVersion=" + isHighestVersion + ", cost=" + cost + ", licenseType=" + licenseType
+ + ", resourceType=" + resourceType + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java
new file mode 100644
index 0000000000..eb473ab39f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceRespJavaObject.java
@@ -0,0 +1,337 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class ResourceRespJavaObject {
+ String uniqueId;
+ String name;
+ String version;
+ String creatorUserId;
+ String creatorFullName;
+ String lastUpdaterUserId;
+ String lastUpdaterFullName;
+ String description;
+ String icon;
+ List<String> tags;
+ String isHighestVersion;
+ String creationDate;
+ String lastUpdateDate;
+ // String category;
+ String lifecycleState;
+ List<String> derivedFrom;
+ String vendorName;
+ String vendorRelease;
+ String contactId;
+ String abstractt;
+ String highestVersion;
+ List<String> artifacts;
+ List<String> interfaces;
+ String uuid;
+ String cost;
+ String licenseType;
+ String resourceType;
+ List<CategoryDefinition> categories;
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public ResourceRespJavaObject(String uniqueId, String resourceName, String resourceVersion, String creatorUserId,
+ String creatorFullName, String lastUpdaterUserId, String lastUpdaterFullName, String description,
+ String icon, List<String> tags, String isHighestVersion, String creationDate, String lastUpdateDate,
+ String category, String lifecycleState, List<String> derivedFrom, String vendorName, String vendorRelease,
+ String contactId, String abstractt, String highestVersion, List<String> artifacts, List<String> interfaces,
+ String uuid, String cost, String licenseType, String resourceType) {
+ super();
+ this.uniqueId = uniqueId;
+ this.name = resourceName;
+ this.version = resourceVersion;
+ this.creatorUserId = creatorUserId;
+ this.creatorFullName = creatorFullName;
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ this.description = description;
+ this.icon = icon;
+ this.tags = tags;
+ this.isHighestVersion = isHighestVersion;
+ this.creationDate = creationDate;
+ this.lastUpdateDate = lastUpdateDate;
+ // this.category = category;
+ this.lifecycleState = lifecycleState;
+ this.derivedFrom = derivedFrom;
+ this.vendorName = vendorName;
+ this.vendorRelease = vendorRelease;
+ this.contactId = contactId;
+ this.abstractt = abstractt;
+ this.highestVersion = highestVersion;
+ this.artifacts = artifacts;
+ this.interfaces = interfaces;
+ this.uuid = uuid;
+ this.cost = cost;
+ this.licenseType = licenseType;
+ this.resourceType = resourceType;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getCost() {
+ return cost;
+ }
+
+ public void setCost(String cost) {
+ this.cost = cost;
+ }
+
+ public String getLicenseType() {
+ return licenseType;
+ }
+
+ public void setLicenseType(String licenseType) {
+ this.licenseType = licenseType;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public String setUuid() {
+ return uuid;
+ }
+
+ public List<String> getInterfaces() {
+ return interfaces;
+ }
+
+ public void setInterfaces(List<String> interfaces) {
+ this.interfaces = interfaces;
+ }
+
+ public List<String> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<String> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public ResourceRespJavaObject() {
+ super();
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String resourceName) {
+ this.name = resourceName;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String resourceVersion) {
+ this.version = resourceVersion;
+ }
+
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
+
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
+
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
+
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ public List<String> getTags() {
+ return tags;
+ }
+
+ public void setTags(List<String> tags) {
+ this.tags = tags;
+ }
+
+ public String getIsHighestVersion() {
+ return isHighestVersion;
+ }
+
+ public void setIsHighestVersion(String isHighestVersion) {
+ this.isHighestVersion = isHighestVersion;
+ }
+
+ public String getCreationDate() {
+ return creationDate;
+ }
+
+ public void setCreationDate(String creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public String getLastUpdateDate() {
+ return lastUpdateDate;
+ }
+
+ public void setLastUpdateDate(String lastUpdateDate) {
+ this.lastUpdateDate = lastUpdateDate;
+ }
+
+ // public String getCategory() {
+ // return category;
+ // }
+ // public void setCategory(String category) {
+ // this.category = category;
+ // }
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public List<String> getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(List<String> derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ 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;
+ }
+
+ public String getContactId() {
+ return contactId;
+ }
+
+ public void setContactId(String contactId) {
+ this.contactId = contactId;
+ }
+
+ public String getAbstractt() {
+ return abstractt;
+ }
+
+ public void setAbstractt(String abstractt) {
+ this.abstractt = abstractt;
+ }
+
+ public String getHighestVersion() {
+ return highestVersion;
+ }
+
+ public void setHighestVersion(String highestVersion) {
+ this.highestVersion = highestVersion;
+ }
+
+ public List<CategoryDefinition> getCategories() {
+ return categories;
+ }
+
+ public void setCategories(List<CategoryDefinition> categories) {
+ this.categories = categories;
+ }
+
+ @Override
+ public String toString() {
+ return "ResourceRespJavaObject [uniqueId=" + uniqueId + ", resourceName=" + name + ", resourceVersion="
+ + version + ", creatorUserId=" + creatorUserId + ", creatorFullName=" + creatorFullName
+ + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName=" + lastUpdaterFullName
+ + ", description=" + description + ", icon=" + icon + ", tags=" + tags + ", isHighestVersion="
+ + isHighestVersion + ", creationDate=" + creationDate + ", lastUpdateDate=" + lastUpdateDate
+ + ", lifecycleState=" + lifecycleState + ", derivedFrom=" + derivedFrom + ", vendorName=" + vendorName
+ + ", vendorRelease=" + vendorRelease + ", contactId=" + contactId + ", abstractt=" + abstractt
+ + ", highestVersion=" + highestVersion + ", artifacts=" + artifacts + ", interfaces=" + interfaces
+ + ", uuid=" + uuid + ", cost=" + cost + ", licenseType=" + licenseType + ", resourceType="
+ + resourceType + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java
new file mode 100644
index 0000000000..015d228acf
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceAssetStructure.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+public class ServiceAssetStructure extends AssetStructure {
+
+ private String distributionStatus;
+
+ public ServiceAssetStructure() {
+ super();
+ }
+
+ public ServiceAssetStructure(String uuid, String invariantUUID, String name, String version, String toscaModelURL,
+ String category, String lifecycleState, String lastUpdaterUserId) {
+ super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId);
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceAssetStructure [distributionStatus=" + distributionStatus + "]";
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java
new file mode 100644
index 0000000000..cc283a3169
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceDetailedAssetStructure.java
@@ -0,0 +1,78 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+public class ServiceDetailedAssetStructure extends ServiceAssetStructure {
+
+ String lastUpdaterFullName;
+ List<ResourceInstanceAssetStructure> resources;
+ List<ArtifactAssetStructure> artifacts;
+
+ public ServiceDetailedAssetStructure() {
+ super();
+ }
+
+ public ServiceDetailedAssetStructure(String uuid, String invariantUUID, String name, String version,
+ String toscaModelURL, String category, String lifecycleState, String lastUpdaterUserId) {
+ super(uuid, invariantUUID, name, version, toscaModelURL, category, lifecycleState, lastUpdaterUserId);
+ }
+
+ public ServiceDetailedAssetStructure(String lastUpdaterFullName, List<ResourceInstanceAssetStructure> resources,
+ List<ArtifactAssetStructure> artifacts) {
+ super();
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ this.resources = resources;
+ this.artifacts = artifacts;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public List<ResourceInstanceAssetStructure> getResources() {
+ return resources;
+ }
+
+ public void setResources(List<ResourceInstanceAssetStructure> resources) {
+ this.resources = resources;
+ }
+
+ public List<ArtifactAssetStructure> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<ArtifactAssetStructure> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceDetailedAssetStructure [lastUpdaterFullName=" + lastUpdaterFullName + ", resources=" + resources
+ + ", artifacts=" + artifacts + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
new file mode 100644
index 0000000000..e33183ca94
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java
@@ -0,0 +1,91 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+
+public class ServiceReqDetails extends ComponentReqDetails {
+
+ public ServiceReqDetails(String serviceName, String category, ArrayList<String> tags, String description,
+ String contactId, String icon) {
+ this.name = serviceName;
+ // this.category = category;
+ this.tags = tags;
+ this.description = description;
+ this.contactId = contactId;
+ this.icon = icon;
+ projectCode = "12345";
+ CategoryDefinition categoryDefinition = new CategoryDefinition();
+ categoryDefinition.setName(category);
+ categories = new ArrayList<>();
+ categories.add(categoryDefinition);
+
+ }
+
+ public ServiceReqDetails(Service service) {
+ this.contactId = service.getContactId();
+ this.categories = service.getCategories();
+ this.creatorUserId = service.getCreatorUserId();
+ this.creatorFullName = service.getCreatorFullName();
+ this.description = service.getDescription();
+ this.icon = service.getIcon();
+ this.name = service.getName();
+ this.projectCode = service.getProjectCode();
+ this.tags = service.getTags();
+ this.uniqueId = service.getUniqueId();
+ this.UUID = service.getUUID();
+ this.version = service.getVersion();
+
+ }
+
+ public ServiceReqDetails() {
+ contactId = "aa1234";
+ projectCode = "12345";
+ }
+
+ public ServiceReqDetails(ServiceReqDetails a, String newServiceName) {
+ a.setName(newServiceName);
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceDetails [name=" + name + ", category=" + getCategory() + ", tags=" + tags + ", description="
+ + description + ", contactId=" + contactId + ", icon=" + icon + "]";
+ }
+
+ public ServiceReqDetails(ServiceReqDetails aService) {
+ this(aService.getName(), aService.getCategory(), (ArrayList<String>) aService.getTags(),
+ aService.getDescription(), aService.getContactId(), aService.getIcon());
+ uniqueId = aService.getUniqueId();
+ version = aService.getVersion();
+ }
+
+ public String getCategory() {
+ if (categories != null && categories.size() >= 1) {
+ return categories.get(0).getName();
+ }
+ return null;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java
new file mode 100644
index 0000000000..4aeb0ce589
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceRespJavaObject.java
@@ -0,0 +1,267 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.ArrayList;
+
+public class ServiceRespJavaObject {
+
+ String category;
+ String creatorUserId;
+ String creatorFullName;
+ String lastUpdaterUserId;
+ String lastUpdaterFullName;
+ String serviceName;
+ String version;
+ String creationDate;
+ String icon;
+ String name;
+ String description;
+ ArrayList<String> tags;
+ String uniqueId;
+ String lastUpdateDate;
+ String contactId;
+ String vendorName;
+ String vendorRelease;
+ String lifecycleState;
+ String highestVersion;
+ ArrayList<String> artifacts;
+ ArrayList<String> ResourceInstances;
+ ArrayList<String> ResourceInstancesRelations;
+
+ public ServiceRespJavaObject() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public ServiceRespJavaObject(String category, String creatorUserId, String creatorFullName,
+ String lastUpdaterUserId, String lastUpdaterFullName, String serviceName, String version,
+ String creationDate, String icon, String name, String description, ArrayList<String> tags, String uniqueId,
+ String lastUpdateDate, String contactId, String vendorName, String vendorRelease, String lifecycleState,
+ String highestVersion, ArrayList<String> artifacts, ArrayList<String> resourceInstances,
+ ArrayList<String> resourceInstancesRelations) {
+ super();
+ this.category = category;
+ this.creatorUserId = creatorUserId;
+ this.creatorFullName = creatorFullName;
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ this.serviceName = serviceName;
+ this.version = version;
+ this.creationDate = creationDate;
+ this.icon = icon;
+ this.name = name;
+ this.description = description;
+ this.tags = tags;
+ this.uniqueId = uniqueId;
+ this.lastUpdateDate = lastUpdateDate;
+ this.contactId = contactId;
+ this.vendorName = vendorName;
+ this.vendorRelease = vendorRelease;
+ this.lifecycleState = lifecycleState;
+ this.highestVersion = highestVersion;
+ this.artifacts = artifacts;
+ ResourceInstances = resourceInstances;
+ ResourceInstancesRelations = resourceInstancesRelations;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
+
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
+
+ public String getCreatorFullName() {
+ return creatorFullName;
+ }
+
+ public void setCreatorFullName(String creatorFullName) {
+ this.creatorFullName = creatorFullName;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getCreationDate() {
+ return creationDate;
+ }
+
+ public void setCreationDate(String creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ 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 ArrayList<String> getTags() {
+ return tags;
+ }
+
+ public void setTags(ArrayList<String> tags) {
+ this.tags = tags;
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public void setUniqueId(String uniqueId) {
+ this.uniqueId = uniqueId;
+ }
+
+ public String getLastUpdateDate() {
+ return lastUpdateDate;
+ }
+
+ public void setLastUpdateDate(String lastUpdateDate) {
+ this.lastUpdateDate = lastUpdateDate;
+ }
+
+ public String getContactId() {
+ return contactId;
+ }
+
+ public void setContactId(String contactId) {
+ this.contactId = contactId;
+ }
+
+ 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;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getHighestVersion() {
+ return highestVersion;
+ }
+
+ public void setHighestVersion(String highest) {
+ this.highestVersion = highest;
+ }
+
+ public ArrayList<String> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(ArrayList<String> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ public ArrayList<String> getResourceInstances() {
+ return ResourceInstances;
+ }
+
+ public void setResourceInstances(ArrayList<String> resourceInstances) {
+ ResourceInstances = resourceInstances;
+ }
+
+ public ArrayList<String> getResourceInstancesRelations() {
+ return ResourceInstancesRelations;
+ }
+
+ public void setResourceInstancesRelations(ArrayList<String> resourceInstancesRelations) {
+ ResourceInstancesRelations = resourceInstancesRelations;
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceRespJavaObject [category=" + category + ", creatorUserId=" + creatorUserId + ", creatorFullName="
+ + creatorFullName + ", lastUpdaterUserId=" + lastUpdaterUserId + ", lastUpdaterFullName="
+ + lastUpdaterFullName + ", serviceName=" + serviceName + ", version=" + version + ", creationDate="
+ + creationDate + ", icon=" + icon + ", name=" + name + ", description=" + description + ", tags=" + tags
+ + ", uniqueId=" + uniqueId + ", lastUpdateDate=" + lastUpdateDate + ", contactId=" + contactId
+ + ", vendorName=" + vendorName + ", vendorRelease=" + vendorRelease + ", lifecycleState="
+ + lifecycleState + ", lifecycleState=" + lifecycleState + ", artifacts=" + artifacts
+ + ", ResourceInstances=" + ResourceInstances + ", ResourceInstancesRelations="
+ + ResourceInstancesRelations + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java
new file mode 100644
index 0000000000..d0f029242f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/TypeHeatMetaDefinition.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes;
+
+import java.util.List;
+
+public class TypeHeatMetaDefinition {
+
+ String typeName;
+
+ List<GroupHeatMetaDefinition> groupHeatMetaDefinition;
+
+ public TypeHeatMetaDefinition() {
+ super();
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+
+ public void setTypeName(String typeName) {
+ this.typeName = typeName;
+ }
+
+ public List<GroupHeatMetaDefinition> getGroupHeatMetaDefinition() {
+ return groupHeatMetaDefinition;
+ }
+
+ public void setGroupHeatMetaDefinition(List<GroupHeatMetaDefinition> groupHeatMetaDefinition) {
+ this.groupHeatMetaDefinition = groupHeatMetaDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "TypeHeatMetaDefinition [typeName=" + typeName + ", groupHeatMetaDefinition=" + groupHeatMetaDefinition
+ + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java
new file mode 100644
index 0000000000..1e6b06a6c8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ArtifactTypeEnum.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Enum That Represents possible Artifacts Types.
+ *
+ */
+public enum ArtifactTypeEnum {
+ CHEF("CHEF"), PUPPET("PUPPET"), YANG("YANG"), SHELL_SCRIPT("SHELL_SCRIPT"), ICON("ICON"), UNKNOWN("UNKNOWN"), HEAT("HEAT"), DG_XML("DG_XML"), MURANO_PKG("MURANO_PKG"),
+ HEAT_ENV("HEAT_ENV"), YANG_XML("YANG_XML"), HEAT_VOL("HEAT_VOL"), HEAT_NET("HEAT_NET"), OTHER("OTHER"), WORKFLOW("WORKFLOW"), NETWORK_CALL_FLOW("NETWORK_CALL_FLOW"),
+ TOSCA_TEMPLATE("TOSCA_TEMPLATE"), TOSCA_CSAR("TOSCA_CSAR"), VNF_CATALOG("VNF_CATALOG"), VF_LICENSE("VF_LICENSE"), VENDOR_LICENSE("VENDOR_LICENSE"),
+ MODEL_INVENTORY_PROFILE("MODEL_INVENTORY_PROFILE"), MODEL_QUERY_SPEC("MODEL_QUERY_SPEC"), APPC_CONFIG("APPC_CONFIG"), HEAT_NESTED("HEAT_NESTED"),
+ HEAT_ARTIFACT("HEAT_ARTIFACT"), VF_MODULES_METADATA("VF_MODULES_METADATA"),
+ // DCAE Artifacts
+ DCAE_TOSCA("DCAE_TOSCA"), DCAE_JSON("DCAE_JSON"), DCAE_POLICY("DCAE_POLICY"), DCAE_DOC("DCAE_DOC"), DCAE_EVENT("DCAE_EVENT"), DCAE_INVENTORY_TOSCA("DCAE_INVENTORY_TOSCA"),
+ DCAE_INVENTORY_JSON("DCAE_INVENTORY_JSON"), DCAE_INVENTORY_POLICY("DCAE_INVENTORY_POLICY"), DCAE_INVENTORY_DOC("DCAE_INVENTORY_DOC"),
+ DCAE_INVENTORY_BLUEPRINT("DCAE_INVENTORY_BLUEPRINT"), DCAE_INVENTORY_EVENT("DCAE_INVENTORY_EVENT"),
+ // AAI Artifacts
+ AAI_SERVICE_MODEL("AAI_SERVICE_MODEL"), AAI_VF_MODEL("AAI_VF_MODEL"), AAI_VF_MODULE_MODEL("AAI_VF_MODULE_MODEL"), AAI_VF_INSTANCE_MODEL("AAI_VF_INSTANCE_MODEL")
+ ;
+
+ ArtifactTypeEnum(String type) {
+ this.type = type;
+ }
+
+ private String type;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public static ArtifactTypeEnum findType(final String type) {
+ for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) {
+ // According to Pavel/Ella
+ if (ate.getType().equalsIgnoreCase(type)) {
+ return ate;
+ }
+ }
+ return null;
+ }
+
+ public static List<String> getAllTypes() {
+ List<String> types = new ArrayList<String>();
+ for (ArtifactTypeEnum ate : ArtifactTypeEnum.values()) {
+ types.add(ate.getType());
+ }
+ return types;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
new file mode 100644
index 0000000000..b0da1f987d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AssocType.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum AssocType {
+
+ BINDABLE("tosca.capabilities.network.Bindable"),
+ HOSTEDON("tosca.relationships.HostedOn"),
+ LINKABLE("tosca.capabilities.network.Linkable"),
+ CONTAINER("tosca.capabilities.Container"),
+ NODE("tosca.capabilities.Node");
+
+ private String assocType;
+
+ private AssocType(String assocType) {
+ this.assocType = assocType;
+
+ }
+
+ public String getAssocType() {
+ return assocType;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
new file mode 100644
index 0000000000..a73cff9373
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditEnum.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum AuditEnum {
+
+ ACTION("ACTION"),
+ RESOURCE_NAME("RESOURCE_NAME"),
+ RESOURCE_TYPE("RESOURCE_TYPE"),
+ PREV_VERSION("PREV_VERSION"),
+ CURR_VERSION("CURR_VERSION"),
+ MODIFIER("MODIFIER"),
+ PREV_STATE("PREV_STATE"),
+ CURR_STATE("CURR_STATE"),
+ STATUS("STATUS-Type"),
+ DESC("DESC"),
+ URL("URL"),
+ USER("USER"),
+ AUTH_STATUS("AUTH_STATUS"),
+ REALM("REALM");
+
+ String value;
+
+ private AuditEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+
+ return value.toLowerCase();
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java
new file mode 100644
index 0000000000..c1b9fd4747
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/AuditJsonKeysEnum.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum AuditJsonKeysEnum {
+
+ ACTION("ACTION"), RESOURCE_NAME("RESOURCE_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), PREV_VERSION("PREV_VERSION"), CURR_VERSION("CURR_VERSION"), PREV_STATE("PREV_STATE"), CURR_STATE("CURR_STATE"),
+ DPREV_STATUS("DPREV_STATUS"), DCURR_STATUS("DCURR_STATUS"), STATUS("STATUS"), DESCRIPTION("DESCRIPTION"), ARTIFACT_DATA("ARTIFACT_DATA"), CONSUMER_ID("CONSUMER_ID"), RESOURCE_URL("RESOURCE_URL"),
+ COMMENT("COMMENT"), DID("DID"), TOPIC_NAME("TOPIC_NAME"), TOSCA_NODE_TYPE("TOSCA_NODE_TYPE"), CURR_ARTIFACT_UUID("CURR_ARTIFACT_UUID"), PREV_ARTIFACT_UUID("PREV_ARTIFACT_UUID"), DETAILS("DETAILS"),
+ MODIFIER("MODIFIER"), SERVICE_INSTANCE_ID("SERVICE_INSTANCE_ID");
+
+ private String auditJsonKeyName;
+
+ private AuditJsonKeysEnum(String auditJsonKeyName) {
+ this.auditJsonKeyName = auditJsonKeyName;
+ }
+
+ public String getAuditJsonKeyName() {
+ return auditJsonKeyName.toLowerCase();
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java
new file mode 100644
index 0000000000..3d242e8c52
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ComponentType.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ComponentType {
+
+ RESOURCE("Resource"), SERVICE("Service"), ARTIFACT("Artifact");
+
+ String value;
+
+ private ComponentType(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+
+ return value;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java
new file mode 100644
index 0000000000..c2a28a1edf
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ErrorInfo.java
@@ -0,0 +1,93 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public class ErrorInfo {
+
+ private Integer code;
+ private String message;
+ private String messageId;
+
+ public ErrorInfo() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public ErrorInfo(Integer code, String message, String messageId) {
+ super();
+ this.code = code;
+ this.message = message;
+ this.messageId = messageId;
+ }
+
+ public ErrorInfo(Integer code, String message) {
+ super();
+ this.code = code;
+ this.message = message;
+ }
+
+ public Integer getCode() {
+ return code;
+ }
+
+ public void setCode(Integer code) {
+ this.code = code;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getMessageAndReplaceVariables(Object... variables) {
+ String formatReadyString = message.replaceAll("%[\\d]+", "%s");
+ formatReadyString = String.format(formatReadyString, variables);
+ return formatReadyString;
+ }
+
+ public String getAuditDesc(Object... variables) {
+ String messageAndReplaceVariables = getMessageAndReplaceVariables(variables);
+ String res;
+ if (messageId != null) {
+ res = messageId + ": " + messageAndReplaceVariables;
+ } else {
+ res = messageAndReplaceVariables;
+ }
+ return res;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getMessageId() {
+ return messageId;
+ }
+
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
+
+ @Override
+ public String toString() {
+ return "ErrorInfo [code=" + code + ", message=" + message + ", messageId=" + messageId + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java
new file mode 100644
index 0000000000..6bfbd8af7d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/EsIndexTypeIdToDelete.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public class EsIndexTypeIdToDelete {
+
+ String index;
+ String type;
+ String id;
+
+ public EsIndexTypeIdToDelete() {
+ super();
+ }
+
+ public EsIndexTypeIdToDelete(String index, String type, String id) {
+ super();
+ this.index = index;
+ this.type = type;
+ this.id = id;
+ }
+
+ public String getIndex() {
+ return index;
+ }
+
+ public void setIndex(String index) {
+ this.index = index;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java
new file mode 100644
index 0000000000..59d1dec453
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ExceptionEnumType.java
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ExceptionEnumType {
+
+ SERVICE_EXCEPTION("serviceException"), POLICY_EXCPTION("policyException");
+
+ String value;
+
+ private ExceptionEnumType(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java
new file mode 100644
index 0000000000..21901e4635
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ImportTestTypesEnum.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+
+public enum ImportTestTypesEnum {
+
+ MISSING_CONTACT("tosca.nodes.missing_contact", "missing_contact", ActionStatus.COMPONENT_MISSING_CONTACT, Arrays.asList("Resource"), true),
+ MISSING_RESOURCE_NAME("tosca.nodes.missing_resource_name", "missing_resource_name", ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Resource"), true),
+ MISSING_DESC("tosca.nodes.missing_desc", "missing_desc", ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Resource"), true),
+ MISSING_ICON("tosca.nodes.missing_icon", "missing_icon", ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Resource"), true),
+ MISSING_TAGS("tosca.nodes.missing_tags", "missing_tags", ActionStatus.COMPONENT_MISSING_TAGS, null, true),
+ MISSING_CATEGORY("tosca.nodes.missing_category", "missing_category", ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Resource"), true),
+ // MISSING_PAYLOADNAME("tosca.nodes.missing_payloadName",
+ // "missing_payloadName", ActionStatus.INVALID_TOSCA_FILE_EXTENSION, null,
+ // true),
+
+ EMPTY_RESOURCE_NAME("tosca.nodes.empty_resource_name", "missing_resource_name"/* "empty_resource_name" */, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Resource"), false),
+ EMPTY_CONTACT("tosca.nodes.empty_contact", "missing_contact"/* "empty_contact" */, ActionStatus.COMPONENT_MISSING_CONTACT, Arrays.asList("Resource"), false),
+ EMPTY_CATEGORY("tosca.nodes.empty_category", "missing_category"/* "empty_category" */, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Resource"), false),
+ EMPTY_DESC("tosca.nodes.empty_desc", "missing_desc"/* "empty_desc" */, ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Resource"), false),
+ EMPTY_ICON("tosca.nodes.empty_icon", "missing_icon"/* "empty_icon" */, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Resource"), false),
+ EMPTY_PAYLOADNAME("tosca.nodes.empty_payloadName", "missing_payloadName"/* "empty_payloadName" */, ActionStatus.INVALID_TOSCA_FILE_EXTENSION, null, false),
+ EMPTY_TAG("tosca.nodes.empty_tag", "empty_tag", ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Resource", "tag"), false),
+ VALIDATE_PROPORTIES_1("tosca.nodes.validateProporties_typeBoolean_valueInit", "validateProporties_typeBoolean_valueInit", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "boolean", "123456"), false),
+ VALIDATE_PROPORTIES_2("tosca.nodes.validateProporties_typeBoolean_valueString", "validateProporties_typeBoolean_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "boolean", "abcd"), false),
+ VALIDATE_PROPORTIES_3("tosca.nodes.validateProporties_typeFloat_valueBoolean", "validateProporties_typeFloat_valueBoolean", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "float", "true"), false),
+ VALIDATE_PROPORTIES_4("tosca.nodes.validateProporties_typeFloat_valueString", "validateProporties_typeFloat_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "float", "abcd"), false),
+ VALIDATE_PROPORTIES_5("tosca.nodes.validateProporties_typeInit_valueBoolean", "validateProporties_typeInit_valueBoolean", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "true"), false),
+ VALIDATE_PROPORTIES_6("tosca.nodes.validateProporties_typeInit_valueFloat", "validateProporties_typeInit_valueFloat", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "0.123"), false),
+ VALIDATE_PROPORTIES_7("tosca.nodes.validateProporties_typeInit_valueString", "validateProporties_typeInit_valueString", ActionStatus.INVALID_DEFAULT_VALUE, Arrays.asList("validation_test", "integer", "abcd"), false);
+ // VALIDATE_PROPORTIES_8("tosca.nodes.validateProporties_happyScenarios","validateProporties_happyScenarios", ActionStatus.OK, null, false);
+
+ private String normativeName;
+ private String folderName;
+ private ActionStatus actionStatus;
+ private Boolean validateAudit;
+ private List<String> errorParams;
+ private Boolean validateYaml;
+
+ // private enum ActionStatus;
+
+ private ImportTestTypesEnum(String resourceName, String folderName, ActionStatus actionStatus,
+ List<String> errorParams, Boolean validateAudit) {
+ this.normativeName = resourceName;
+ this.folderName = folderName;
+ this.actionStatus = actionStatus;
+ this.errorParams = errorParams;
+ this.validateAudit = validateAudit;
+
+ }
+
+ public String getNormativeName() {
+ return normativeName;
+ }
+
+ public String getFolderName() {
+ return folderName;
+ }
+
+ public ActionStatus getActionStatus() {
+ return actionStatus;
+ }
+
+ public Boolean getvalidateAudit() {
+ return validateAudit;
+ }
+
+ public List<String> getErrorParams() {
+ return errorParams;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java
new file mode 100644
index 0000000000..7c330a3d10
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/LifeCycleStatesEnum.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum LifeCycleStatesEnum {
+
+ CHECKOUT("checkout", "NOT_CERTIFIED_CHECKOUT"),
+ CHECKIN("checkin", "NOT_CERTIFIED_CHECKIN"),
+ CERTIFICATIONREQUEST("certificationRequest", "READY_FOR_CERTIFICATION"),
+ UNDOCHECKOUT("undoCheckout", ""),
+ CANCELCERTIFICATION("cancelCertification", ""),
+ STARTCERTIFICATION("startCertification", "CERTIFICATION_IN_PROGRESS"),
+ FAILCERTIFICATION("failCertification", ""),
+ CERTIFY("certify", "CERTIFIED");
+
+ private String state;
+ private String componentState;
+
+ private LifeCycleStatesEnum(String state, String componentState) {
+ this.state = state;
+ this.componentState = componentState;
+
+ }
+
+ public String getState() {
+ return state;
+ }
+
+ public String getComponentState() {
+ return componentState;
+ }
+
+ public static LifeCycleStatesEnum findByCompState(String compState) {
+
+ for (LifeCycleStatesEnum lifeCycleStatesEnum : LifeCycleStatesEnum.values()) {
+ if (lifeCycleStatesEnum.getComponentState().equals(compState)) {
+ return lifeCycleStatesEnum;
+ }
+ }
+
+ return null;
+
+ }
+
+ public static LifeCycleStatesEnum findByState(String state) {
+
+ for (LifeCycleStatesEnum lifeCycleStatesEnum : LifeCycleStatesEnum.values()) {
+ if (lifeCycleStatesEnum.name().equals(state)) {
+ return lifeCycleStatesEnum;
+ }
+ }
+
+ return null;
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java
new file mode 100644
index 0000000000..7769d19802
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryResourceArtifactTypeEnum.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
+public enum MandatoryResourceArtifactTypeEnum {
+
+ TEST_SCRIPTS(null, "testscripts"),
+ FEATURES(null, "features"),
+ CAPACITY(null, "capacity"),
+ VENDOR_TEST_RESULT(null,"vendortestresult"),
+ CLOUD_QUESTIONNAIRE(null, "cloudquestionnaire");
+
+ String artifactName;
+ String logicalName;
+
+ private MandatoryResourceArtifactTypeEnum(String artifactName, String logicalName) {
+ this.artifactName = artifactName;
+ this.logicalName = logicalName;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public String getLogicalName() {
+ return logicalName;
+ }
+
+ public ArtifactGroupTypeEnum getGroupType() {
+ return ArtifactGroupTypeEnum.INFORMATIONAL;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java
new file mode 100644
index 0000000000..b73d5a8fee
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/MandatoryServiceArtifactTypeEnum.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum MandatoryServiceArtifactTypeEnum {
+
+ MESSAGE_FLOWS(null, "messageflows".toLowerCase(), "Message Flows"),
+ INSTANT_FLOWS(null, "instantiationflows".toLowerCase(), "Management Flows"),
+ SERVICE_ART_PLAN(null, "serviceartifactplan".toLowerCase(), "Service Artifact Plan"),
+ SUM_OF_ELEMENTS(null, "summaryofimpactstoecompelements".toLowerCase(), "Summary of impacts to ECOMP elements,OSSs, BSSs"),
+ CONTROL_LOOP_FUN(null, "controlloopfunctions".toLowerCase(), "Control Loop Functions"),
+ DIMENSIONNING_INFO(null, "dimensioninginfo".toLowerCase(), "Dimensioning Info"),
+ AFFINITY_RULES(null, "affinityrules".toLowerCase(), "Affinity Rules"),
+ OPERATIONAL_POLICIES(null, "operationalpolicies".toLowerCase(), "Operational Policies"),
+ SERVICE_SPECIFIC_POLICIES(null, "servicespecificpolicies".toLowerCase(), "Service-specific Policies"),
+ ENGINEERING_RULES(null, "engineeringrules".toLowerCase(), "Engineering Rules (ERD)"),
+ DISTRIB_INSTRUCTIONS(null, "distributioninstructions".toLowerCase(), "Distribution Instructions"),
+ DEPLOYMENT_VOTING_REC(null, "deploymentvotingrecord".toLowerCase(), "Deployment Voting Record"),
+ CERTIFICATION_TEST_RESULT(null, "certificationtestresults".toLowerCase(), "TD Certification Test Results");
+ // SERVICE_QUESTIONNAIRE(null, "serviceQuestionnaire".toLowerCase());
+
+ String artifactName;
+ String logicalName;
+ String artifactDisplayName;
+
+ private MandatoryServiceArtifactTypeEnum(String artifactName, String logicalName, String artifactDisplayName) {
+ this.artifactName = artifactName;
+ this.logicalName = logicalName;
+ this.artifactDisplayName = artifactDisplayName;
+ }
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public String getLogicalName() {
+ return logicalName;
+ }
+
+ public String getArtifactDisplayName() {
+ return artifactDisplayName;
+ }
+
+ public void setArtifactDisplayName(String artifactDisplayName) {
+ this.artifactDisplayName = artifactDisplayName;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java
new file mode 100644
index 0000000000..f1cfcf0c98
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/NormativeTypesEnum.java
@@ -0,0 +1,55 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum NormativeTypesEnum {
+ ROOT("tosca.nodes.Root", "root"),
+ COMPUTE("tosca.nodes.Compute", "compute"),
+ BLOCK_STORAGE("tosca.nodes.BlockStorage", "blockStorage"),
+ CONTAINER_APPLICATION("tosca.nodes.Container.Application", "containerApplication"),
+ CONTAINER_RUNTIME("tosca.nodes.Container.Runtime", "containerRuntime"),
+ DATABASE("tosca.nodes.Database", "database"),
+ DBMS("tosca.nodes.DBMS", "DBMS"),
+ LOAD_BALANCER("tosca.nodes.LoadBalancer", "loadBalancer"),
+ OBJECT_STORAGE("tosca.nodes.ObjectStorage", "objectStorage"),
+ NETWORK("tosca.nodes.network.Network", "network"),
+ PORT("tosca.nodes.network.Port", "port"),
+ SOFTWARE_COMPONENT("tosca.nodes.SoftwareComponent", "softwareComponent"),
+ WEB_APPLICATION("tosca.nodes.webapplication", "webApplication"),
+ WEB_SERVER("tosca.nodes.WebServer", "webServer");
+
+ public String normativeName;
+ private String folderName;
+
+ private NormativeTypesEnum(String resourceName, String folderName) {
+ this.normativeName = resourceName;
+ this.folderName = folderName;
+ }
+
+ public String getNormativeName() {
+ return normativeName;
+ }
+
+ public String getFolderName() {
+ return folderName;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java
new file mode 100644
index 0000000000..5dac326c70
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/PropertyTypeEnum.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+
+public enum PropertyTypeEnum {
+ INTEGER("defaultIntegerPropName1", "integer", "125", "default integer type property description", null),
+ STRING("defaultStringPropName1", "string", "string", "default string type property description", null),
+ BOOLEAN("defaultBooleanPropName1", "boolean", "true", "default boolean type property description", null),
+ STRING_LIST("defaultStringListPropName", "list", "[a,b]", "outer description", getDefaultStringSchema(ToscaPropertyType.STRING.getType())),
+ INTEGER_LIST("defaultIntegerListPropName", "list", "[1,2]", "outer description", getDefaultStringSchema(ToscaPropertyType.INTEGER.getType())),
+ BOOLEAN_LIST("defaultBooleanListPropName", "list", "[true,false]", "outer description", getDefaultStringSchema(ToscaPropertyType.BOOLEAN.getType())),
+ FLOAT_LIST("defaultFloatMapPropName", "list", "[1.0,2.0]", "outer description", getDefaultStringSchema(ToscaPropertyType.FLOAT.getType())),
+ STRING_MAP("defaultStringMapPropName", "map", "{\"key1\":val1 , \"key2\":val2}", "outer description", getDefaultStringSchema(ToscaPropertyType.STRING.getType())),
+ INTEGER_MAP("defaultIntegerMapPropName", "map", "{\"key1\":123 , \"key2\":-456}", "outer description", getDefaultStringSchema(ToscaPropertyType.INTEGER.getType())),
+ BOOLEAN_MAP("defaultBooleanMapPropName", "map", "{\"key1\":true , \"key2\":false}", "outer description", getDefaultStringSchema(ToscaPropertyType.BOOLEAN.getType())),
+ FLOAT_MAP("defaultFloatMapPropName", "map", "{\"key1\":0.2123 , \"key2\":43.545f}", "outer description", getDefaultStringSchema(ToscaPropertyType.FLOAT.getType()));
+
+ private String name;
+ private String type;
+ private String value;
+ private String description;
+ private SchemaDefinition schemaDefinition;
+
+ private PropertyTypeEnum(String name, String type, String value, String description,
+ SchemaDefinition schemaDefinition) {
+ this.name = name;
+ this.type = type;
+ this.value = value;
+ this.description = description;
+ this.schemaDefinition = schemaDefinition;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public SchemaDefinition getSchemaDefinition() {
+ return schemaDefinition;
+ }
+
+ public void setSchemaDefinition(SchemaDefinition schemaDefinition) {
+ this.schemaDefinition = schemaDefinition;
+ }
+
+ private static SchemaDefinition getDefaultStringSchema(String innerType) {
+ SchemaDefinition schema = new SchemaDefinition();
+ String description = "inner description";
+ PropertyDefinition property = new PropertyDefinition();
+ property.setType(innerType);
+ property.setDescription(description);
+ schema.setProperty(property);
+ return schema;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java
new file mode 100644
index 0000000000..3ece77b8ec
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ResourceCategoryEnum.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ResourceCategoryEnum {
+
+ NETWORK_L2_3_ROUTERS("Network L2-3", "Router"), NETWORK_L2_3_GETEWAY("Network L2-3","Gateway"), NETWORK_L2_3_WAN_CONNECTORS("Network L2-3", "WAN Connectors"), NETWORK_L2_3_LAN_CONNECTORS("Network L2-3", "LAN Connectors"),
+ NETWORK_L2_3_INFRASTRUCTURE("Network L2-3", "Infrastructure"), NETWORK_L4("Network L4+", "Common Network Resources"), APPLICATION_L4_BORDER("Application L4+", "Border Element"),
+ APPLICATION_L4_APP_SERVER("Application L4+", "Application Server"), APPLICATION_L4_WEB_SERVERS("Application L4+", "Web Server"), APPLICATION_L4_CALL_CONTROL("Application L4+","Call Control"),
+ APPLICATION_L4_MEDIA_SERVER("Application L4+", "Media Servers"), APPLICATION_L4_LOAD_BALANCER("Application L4+", "Load Balancer"), APPLICATION_L4_DATABASE("Application L4+","Database"),
+ APPLICATION_L4_FIREWALL("Application L4+", "Firewall"), GENERIC_INFRASTRUCTURE("Generic", "Infrastructure"), GENERIC_ABSTRACT("Generic", "Abstract"), GENERIC_NETWORK_ELEMENTS("Generic","Network Elements"),
+ GENERIC_DATABASE("Generic", "Database"), NETWORK_CONNECTIVITY_CON_POINT("Network Connectivity", "Connection Points"), NETWORK_CONNECTIVITY_VIRTUAL_LINK("Network Connectivity","Virtual Links");
+
+ private String category;
+ private String subCategory;
+
+ ResourceCategoryEnum(String category, String subCategory) {
+ this.category = category;
+ this.subCategory = subCategory;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getSubCategory() {
+ return subCategory;
+ }
+
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java
new file mode 100644
index 0000000000..4350cba105
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/RespJsonKeysEnum.java
@@ -0,0 +1,60 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum RespJsonKeysEnum {
+
+ IS_ABSTRACT("abstract"),
+ UNIQUE_ID("uniqueId"),
+ RESOURCE_NAME("name"),
+ RESOURCE_VERSION("version"),
+ TAGS("tags"),
+ LIFE_CYCLE_STATE("lifecycleState"),
+ DERIVED_FROM("derivedFrom"),
+ RESOURCE_DESC("description"),
+ VENDOR_NAME("vendorName"),
+ VENDOR_RELEASE("vendorRelease"),
+ CONTACT_ID("contactId"),
+ ICON("icon"),
+ HIGHEST_VERSION("highestVersion"),
+ CREATOR_USER_ID("creatorUserId"),
+ CREATOR_FULL_NAME("creatorFullName"),
+ LAST_UPDATER_ATT_UID("lastUpdaterUserId"),
+ LAST_UPDATER_FULL_NAME("lastUpdaterFullName"),
+ ARTIFACTS("artifacts"),
+ DESCRIPTION("description"),
+ UUID("uuid"),
+ COST("cost"),
+ LICENSE_TYPE("licenseType"),
+ RESOURCE_TYPE("resourceType"),
+ CATEGORIES("categories");
+
+ private String respJsonKeyName;
+
+ private RespJsonKeysEnum(String respJsonKeyName) {
+ this.respJsonKeyName = respJsonKeyName;
+ }
+
+ public String getRespJsonKeyName() {
+ return respJsonKeyName;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java
new file mode 100644
index 0000000000..675e1d7502
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceApiArtifactEnum.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ServiceApiArtifactEnum {
+ CONFIGURATION("Configuration".toLowerCase()),
+ INSTANTIATION("Instantiation".toLowerCase()),
+ MONITORING("Monitoring".toLowerCase()),
+ REPORTING("Reporting".toLowerCase()),
+ LOGGING("Logging".toLowerCase()),
+ TESTING("Testing".toLowerCase());
+
+ String logicalName;
+
+ private ServiceApiArtifactEnum(String logicalName) {
+ this.logicalName = logicalName;
+ }
+
+ public String getLogicalName() {
+ return logicalName;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java
new file mode 100644
index 0000000000..61d4e487e2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ServiceCategoriesEnum.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ServiceCategoriesEnum {
+
+ VOIP("VoIP Call Control"), MOBILITY("Mobility"), NETWORK_L4("Network L4+"), NETWORK_L3("Network L1-3");
+ String value;
+
+ private ServiceCategoriesEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+
+ return value;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java
new file mode 100644
index 0000000000..f8479e912c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/ToscaKeysEnum.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum ToscaKeysEnum {
+
+ TOSCA_DEFINITION_VERSION("tosca_definitions_version"),
+ METADATA("metadata"), IMPORTS("imports"),
+ NODE_TYPES("node_types"),
+ TOPOLOGY_TEMPLATE("topology_template");
+
+ private String toscaKey;
+
+ public String getToscaKey() {
+ return toscaKey;
+ }
+
+ private ToscaKeysEnum(String toscaKey) {
+ this.toscaKey = toscaKey;
+ }
+
+ public static ToscaKeysEnum findToscaKey(final String toscaKey) {
+ for (ToscaKeysEnum toscaKeyEnum : ToscaKeysEnum.values()) {
+ if (toscaKeyEnum.getToscaKey().equalsIgnoreCase(toscaKey)) {
+ return toscaKeyEnum;
+ }
+ }
+ return null;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java
new file mode 100644
index 0000000000..399779fefe
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/enums/UserRoleEnum.java
@@ -0,0 +1,76 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.enums;
+
+public enum UserRoleEnum {
+
+ ADMIN("jh0003","Jimmy", "Hendrix"), DESIGNER("cs0008","Carlos", "Santana"), DESIGNER2("me0009","Melissa", "Etheridge"), TESTER("jm0007","Joni", "Mitchell"),ADMIN4("km2000","Kot", "May"), GOVERNOR("gv0001","David", "Shadmi"),
+ OPS("op0001","Steve", "Regev"),PRODUCT_STRATEGIST1("ps0001","Eden", "Rozin"),PRODUCT_STRATEGIST2("ps0002","Ella", "Kvetny"),PRODUCT_STRATEGIST3("ps0003","Geva", "Alon"), PRODUCT_MANAGER1("pm0001","Teddy", "Isashar"),
+ PRODUCT_MANAGER2("pm0002","Sarah", "Bettens");
+
+ private String userId;
+ private String firstName;
+ private String lastName;
+ private String userName;
+ private UserRoleEnum(String userId, String userName) {
+ this.userId = userId;
+ this.userName = userName;
+ }
+
+ private UserRoleEnum(String userId, String firstName, String lastName) {
+ this.userId = userId;
+ this.firstName =firstName;
+ this.lastName = lastName;
+ this.userName = firstName+" " + lastName;
+ }
+ public String getUserId() {
+ return userId;
+ }
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+ public String getUserName() {
+ return userName;
+ }
+ public void setUserName(String userName) {
+ this.userName = userName;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+
+}
+
+
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java
new file mode 100644
index 0000000000..344f353348
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedArtifactAudit.java
@@ -0,0 +1,166 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedArtifactAudit {
+
+ private String action;
+ private String resourceName;
+ private String resourceType;
+ private String prevVersion;
+ private String currVersion;
+ private String modifier;
+ private String prevState;
+ private String currState;
+ private String prevArtifactUuid;
+ private String currArtifactUuid;
+ private String artifactData;
+ private String status;
+ private String desc;
+
+ public ExpectedArtifactAudit(String action, String resourceName, String resourceType, String prevVersion,
+ String currVersion, String modifier, String prevState, String currState, String prevArtifactUuid,
+ String currArtifactUuid, String artifactData, String status, String desc) {
+ super();
+ this.action = action;
+ this.resourceName = resourceName;
+ this.resourceType = resourceType;
+ this.prevVersion = prevVersion;
+ this.currVersion = currVersion;
+ this.modifier = modifier;
+ this.prevState = prevState;
+ this.currState = currState;
+ this.prevArtifactUuid = prevArtifactUuid;
+ this.currArtifactUuid = currArtifactUuid;
+ this.artifactData = artifactData;
+ this.status = status;
+ this.desc = desc;
+ }
+
+ public ExpectedArtifactAudit() {
+ super();
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getPrevVersion() {
+ return prevVersion;
+ }
+
+ public void setPrevVersion(String prevVersion) {
+ this.prevVersion = prevVersion;
+ }
+
+ public String getCurrVersion() {
+ return currVersion;
+ }
+
+ public void setCurrVersion(String currVersion) {
+ this.currVersion = currVersion;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getPrevState() {
+ return prevState;
+ }
+
+ public void setPrevState(String prevState) {
+ this.prevState = prevState;
+ }
+
+ public String getCurrState() {
+ return currState;
+ }
+
+ public void setCurrState(String currState) {
+ this.currState = currState;
+ }
+
+ public String getPrevArtifactUuid() {
+ return prevArtifactUuid;
+ }
+
+ public void setPrevArtifactUuid(String prevArtifactUuid) {
+ this.prevArtifactUuid = prevArtifactUuid;
+ }
+
+ public String getCurrArtifactUuid() {
+ return currArtifactUuid;
+ }
+
+ public void setCurrArtifactUuid(String currArtifactUuid) {
+ this.currArtifactUuid = currArtifactUuid;
+ }
+
+ public String getArtifactData() {
+ return artifactData;
+ }
+
+ public void setArtifactData(String artifactData) {
+ this.artifactData = artifactData;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java
new file mode 100644
index 0000000000..0d6a5f3b3c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedAuthenticationAudit.java
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedAuthenticationAudit {
+
+ private String url;
+ private String realm;
+ private String user;
+ private String action;
+ private String authStatus;
+
+ public ExpectedAuthenticationAudit(String url, String user, String action, String authStatus) {
+ super();
+ this.url = url;
+ this.user = user;
+ this.action = action;
+ this.authStatus = authStatus;
+ this.realm = "ASDC";
+ }
+
+ public ExpectedAuthenticationAudit() {
+
+ }
+
+ public String getUrl() {
+ return url;
+ }
+
+ public void setUrl(String url) {
+ this.url = url;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public void setRealm(String realm) {
+ this.realm = realm;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getAuthStatus() {
+ return authStatus;
+ }
+
+ public void setAuthStatus(String authStatus) {
+ this.authStatus = authStatus;
+ }
+
+ @Override
+ public String toString() {
+ return "ExpectedAuthenticationAudit [url=" + url + ", realm=" + realm + ", user=" + user + ", action=" + action
+ + ", authStatus=" + authStatus + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java
new file mode 100644
index 0000000000..b11f7f585a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedCategoryAudit.java
@@ -0,0 +1,151 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedCategoryAudit {
+ String action;
+ String modifier;
+ String modifierUid;
+ String modifierName;
+ String categoryName;
+ String subCategoryName;
+ String groupingName;
+ String resourceType;
+ String status;
+ String desc;
+ String details;
+
+ public ExpectedCategoryAudit(String action, String modifier, String categoryName, String subCategoryName,
+ String groupingName, String resourceType, String status, String desc) {
+ super();
+ this.action = action;
+ this.modifier = modifier;
+ this.categoryName = categoryName;
+ this.subCategoryName = subCategoryName;
+ this.groupingName = groupingName;
+ this.resourceType = resourceType;
+ this.status = status;
+ this.desc = desc;
+ }
+
+ public ExpectedCategoryAudit() {
+ action = null;
+ modifier = null;
+ categoryName = null;
+ subCategoryName = null;
+ groupingName = null;
+ resourceType = null;
+ status = null;
+ desc = null;
+ details = null;
+ modifierName = null;
+ modifierUid = null;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getCategoryName() {
+ return categoryName;
+ }
+
+ public void setCategoryName(String categoryName) {
+ this.categoryName = categoryName;
+ }
+
+ public String getSubCategoryName() {
+ return subCategoryName;
+ }
+
+ public void setSubCategoryName(String subCategoryName) {
+ this.subCategoryName = subCategoryName;
+ }
+
+ public String getGroupingName() {
+ return groupingName;
+ }
+
+ public void setGroupingName(String groupingName) {
+ this.groupingName = groupingName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+ public String getModifierUid() {
+ return modifierUid;
+ }
+
+ public void setModifierUid(String modifierUid) {
+ this.modifierUid = modifierUid;
+ }
+
+ public String getModifierName() {
+ return modifierName;
+ }
+
+ public void setModifierName(String modifierName) {
+ this.modifierName = modifierName;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java
new file mode 100644
index 0000000000..4b135f66f6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedDistDownloadAudit.java
@@ -0,0 +1,79 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedDistDownloadAudit {
+
+ String action;
+ String consumerId;
+ String resourceUrl;
+ String status;
+ String desc;
+
+ public ExpectedDistDownloadAudit(String action, String consumerId, String resourceUrl, String status, String desc) {
+ super();
+ this.action = action;
+ this.consumerId = consumerId;
+ this.resourceUrl = resourceUrl;
+ this.status = status;
+ this.desc = desc;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getConsumerId() {
+ return consumerId;
+ }
+
+ public void setConsumerId(String consumerId) {
+ this.consumerId = consumerId;
+ }
+
+ public String getResourceUrl() {
+ return resourceUrl;
+ }
+
+ public void setResourceUrl(String resourceUrl) {
+ this.resourceUrl = resourceUrl;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java
new file mode 100644
index 0000000000..1414742423
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedEcomConsumerAudit.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedEcomConsumerAudit {
+
+ String action;
+ String modifier;
+ String ecomUser;
+ String status;
+ String desc;
+
+ public ExpectedEcomConsumerAudit(String action, String modifier, String ecomUser, String status, String desc) {
+ super();
+ this.action = action;
+ this.modifier = modifier;
+ this.ecomUser = ecomUser;
+ this.status = status;
+ this.desc = desc;
+ }
+
+ public ExpectedEcomConsumerAudit() {
+ action = null;
+ modifier = null;
+ ecomUser = null;
+ status = null;
+ desc = null;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getEcomUser() {
+ return ecomUser;
+ }
+
+ public void setEcomUser(String ecomUser) {
+ this.ecomUser = ecomUser;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java
new file mode 100644
index 0000000000..e689a3921b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedExternalAudit.java
@@ -0,0 +1,179 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedExternalAudit {
+
+ String ACTION;
+ String CONSUMER_ID;
+ String RESOURCE_URL;
+ String STATUS;
+ String DESC;
+ String RESOURCE_NAME;
+ String RESOURCE_TYPE;
+ String SERVICE_INSTANCE_ID;// resource/ service UUID
+ String MODIFIER;
+ String PREV_ARTIFACT_UUID;
+ String CURR_ARTIFACT_UUID;
+ String ARTIFACT_DATA;
+
+ public ExpectedExternalAudit() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public String getRESOURCE_NAME() {
+ return RESOURCE_NAME;
+ }
+
+ public void setRESOURCE_NAME(String rESOURCE_NAME) {
+ RESOURCE_NAME = rESOURCE_NAME;
+ }
+
+ public String getRESOURCE_TYPE() {
+ return RESOURCE_TYPE;
+ }
+
+ public void setRESOURCE_TYPE(String rESOURCE_TYPE) {
+ RESOURCE_TYPE = rESOURCE_TYPE;
+ }
+
+ public String getSERVICE_INSTANCE_ID() {
+ return SERVICE_INSTANCE_ID;
+ }
+
+ public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) {
+ SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID;
+ }
+
+ public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC,
+ String rESOURCE_NAME, String rESOURCE_TYPE, String sERVICE_INSTANCE_ID) {
+ super();
+ ACTION = aCTION;
+ CONSUMER_ID = cONSUMER_ID;
+ RESOURCE_URL = rESOURCE_URL;
+ STATUS = sTATUS;
+ DESC = dESC;
+ RESOURCE_NAME = rESOURCE_NAME;
+ RESOURCE_TYPE = rESOURCE_TYPE;
+ SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID;
+ }
+
+ public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC) {
+ super();
+ ACTION = aCTION;
+ CONSUMER_ID = cONSUMER_ID;
+ RESOURCE_URL = rESOURCE_URL;
+ STATUS = sTATUS;
+ DESC = dESC;
+ }
+
+ public ExpectedExternalAudit(String aCTION, String cONSUMER_ID, String rESOURCE_URL, String sTATUS, String dESC,
+ String rESOURCE_NAME, String rESOURCE_TYPE, String sERVICE_INSTANCE_ID, String mODIFIER,
+ String pREV_ARTIFACT_UUID, String cURR_ARTIFACT_UUID, String aRTIFACT_DATA) {
+ super();
+ ACTION = aCTION;
+ CONSUMER_ID = cONSUMER_ID;
+ RESOURCE_URL = rESOURCE_URL;
+ STATUS = sTATUS;
+ DESC = dESC;
+ RESOURCE_NAME = rESOURCE_NAME;
+ RESOURCE_TYPE = rESOURCE_TYPE;
+ SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID;
+ MODIFIER = mODIFIER;
+ PREV_ARTIFACT_UUID = pREV_ARTIFACT_UUID;
+ CURR_ARTIFACT_UUID = cURR_ARTIFACT_UUID;
+ ARTIFACT_DATA = aRTIFACT_DATA;
+ }
+
+ public String getACTION() {
+ return ACTION;
+ }
+
+ public void setACTION(String aCTION) {
+ ACTION = aCTION;
+ }
+
+ public String getCONSUMER_ID() {
+ return CONSUMER_ID;
+ }
+
+ public void setCONSUMER_ID(String cONSUMER_ID) {
+ CONSUMER_ID = cONSUMER_ID;
+ }
+
+ public String getRESOURCE_URL() {
+ return RESOURCE_URL;
+ }
+
+ public void setRESOURCE_URL(String rESOURCE_URL) {
+ RESOURCE_URL = rESOURCE_URL;
+ }
+
+ public String getSTATUS() {
+ return STATUS;
+ }
+
+ public void setSTATUS(String sTATUS) {
+ STATUS = sTATUS;
+ }
+
+ public String getDESC() {
+ return DESC;
+ }
+
+ public void setDESC(String dESC) {
+ DESC = dESC;
+ }
+
+ public String getMODIFIER() {
+ return MODIFIER;
+ }
+
+ public void setMODIFIER(String mODIFIER) {
+ MODIFIER = mODIFIER;
+ }
+
+ public String getPREV_ARTIFACT_UUID() {
+ return PREV_ARTIFACT_UUID;
+ }
+
+ public void setPREV_ARTIFACT_UUID(String pREV_ARTIFACT_UUID) {
+ PREV_ARTIFACT_UUID = pREV_ARTIFACT_UUID;
+ }
+
+ public String getCURR_ARTIFACT_UUID() {
+ return CURR_ARTIFACT_UUID;
+ }
+
+ public void setCURR_ARTIFACT_UUID(String cURR_ARTIFACT_UUID) {
+ CURR_ARTIFACT_UUID = cURR_ARTIFACT_UUID;
+ }
+
+ public String getARTIFACT_DATA() {
+ return ARTIFACT_DATA;
+ }
+
+ public void setARTIFACT_DATA(String aRTIFACT_DATA) {
+ ARTIFACT_DATA = aRTIFACT_DATA;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java
new file mode 100644
index 0000000000..561b92a317
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGetUserListAudit.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedGetUserListAudit {
+
+ String action;
+ String modifier;
+ String status;
+ String desc;
+ String details;
+
+ public ExpectedGetUserListAudit(String action, String modifier, String status, String desc, String details) {
+ super();
+ this.action = action;
+ this.modifier = modifier;
+ this.status = status;
+ this.desc = desc;
+ this.details = details;
+ }
+
+ public ExpectedGetUserListAudit() {
+ action = null;
+ modifier = null;
+ details = null;
+ status = null;
+ desc = null;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getDetails() {
+ return details;
+ }
+
+ public void setDetails(String details) {
+ this.details = details;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java
new file mode 100644
index 0000000000..b481cb77af
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedGroupingAudit.java
@@ -0,0 +1,121 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedGroupingAudit {
+ String action;
+ String modifier;
+ String categoryName;
+ String subCategoryName;
+ String groupingName;
+ String resourceType;
+ String status;
+ String desc;
+
+ public ExpectedGroupingAudit(String action, String modifier, String categoryName, String subCategoryName,
+ String groupingName, String resourceType, String status, String desc) {
+ super();
+ this.action = action;
+ this.modifier = modifier;
+ this.categoryName = categoryName;
+ this.subCategoryName = subCategoryName;
+ this.groupingName = groupingName;
+ this.resourceType = resourceType;
+ this.status = status;
+ this.desc = desc;
+ }
+
+ public ExpectedGroupingAudit() {
+ action = null;
+ modifier = null;
+ categoryName = null;
+ subCategoryName = null;
+ groupingName = null;
+ resourceType = null;
+ status = null;
+ desc = null;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getCategoryName() {
+ return categoryName;
+ }
+
+ public void setCategoryName(String categoryName) {
+ this.categoryName = categoryName;
+ }
+
+ public String getSubCategoryName() {
+ return subCategoryName;
+ }
+
+ public void setSubCategoryName(String subCategoryName) {
+ this.subCategoryName = subCategoryName;
+ }
+
+ public String getGroupingName() {
+ return groupingName;
+ }
+
+ public void setGroupingName(String groupingName) {
+ this.groupingName = groupingName;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java
new file mode 100644
index 0000000000..40b86fa528
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedProductAudit.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedProductAudit {
+
+ String ACTION;
+ String MODIFIER;
+ String STATUS;
+ String DESC;
+ String RESOURCE_NAME;
+ String RESOURCE_TYPE;
+ String PREV_VERSION;
+ String CURR_VERSION;
+ String PREV_STATE;
+ String CURR_STATE;
+ String TIMESTAMP;
+ String SERVICE_INSTANCE_ID;
+ String COMMENT;
+
+ public String getCOMMENT() {
+ return COMMENT;
+ }
+
+ public void setCOMMENT(String cOMMENT) {
+ COMMENT = cOMMENT;
+ }
+
+ public String getSERVICE_INSTANCE_ID() {
+ return SERVICE_INSTANCE_ID;
+ }
+
+ public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) {
+ SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID;
+ }
+
+ public String getACTION() {
+ return ACTION;
+ }
+
+ public void setACTION(String aCTION) {
+ ACTION = aCTION;
+ }
+
+ public String getMODIFIER() {
+ return MODIFIER;
+ }
+
+ public void setMODIFIER(String mODIFIER) {
+ MODIFIER = mODIFIER;
+ }
+
+ public String getSTATUS() {
+ return STATUS;
+ }
+
+ public void setSTATUS(String sTATUS) {
+ STATUS = sTATUS;
+ }
+
+ public String getDESC() {
+ return DESC;
+ }
+
+ public void setDESC(String dESC) {
+ DESC = dESC;
+ }
+
+ public String getRESOURCE_NAME() {
+ return RESOURCE_NAME;
+ }
+
+ public void setRESOURCE_NAME(String rESOURCE_NAME) {
+ RESOURCE_NAME = rESOURCE_NAME;
+ }
+
+ public String getRESOURCE_TYPE() {
+ return RESOURCE_TYPE;
+ }
+
+ public void setRESOURCE_TYPE(String rESOURCE_TYPE) {
+ RESOURCE_TYPE = rESOURCE_TYPE;
+ }
+
+ public String getPREV_VERSION() {
+ return PREV_VERSION;
+ }
+
+ public void setPREV_VERSION(String pREV_VERSION) {
+ PREV_VERSION = pREV_VERSION;
+ }
+
+ public String getCURR_VERSION() {
+ return CURR_VERSION;
+ }
+
+ public void setCURR_VERSION(String cURR_VERSION) {
+ CURR_VERSION = cURR_VERSION;
+ }
+
+ public String getPREV_STATE() {
+ return PREV_STATE;
+ }
+
+ public void setPREV_STATE(String pREV_STATE) {
+ PREV_STATE = pREV_STATE;
+ }
+
+ public String getCURR_STATE() {
+ return CURR_STATE;
+ }
+
+ public void setCURR_STATE(String cURR_STATE) {
+ CURR_STATE = cURR_STATE;
+ }
+
+ public String getTIMESTAMP() {
+ return TIMESTAMP;
+ }
+
+ public void setTIMESTAMP(String tIMESTAMP) {
+ TIMESTAMP = tIMESTAMP;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java
new file mode 100644
index 0000000000..cc78709888
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedResourceAuditJavaObject.java
@@ -0,0 +1,300 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedResourceAuditJavaObject {
+
+ String ACTION;
+ String MODIFIER_NAME;
+ String MODIFIER_UID;
+ String STATUS;
+ String DESC;
+ String RESOURCE_NAME;
+ String RESOURCE_TYPE;
+ String PREV_VERSION;
+ String CURR_VERSION;
+ String PREV_STATE;
+ String CURR_STATE;
+ String TIMESTAMP;
+ String ARTIFACT_DATA;
+ String DPREV_STATUS;
+ String DCURR_STATUS;
+ String COMMENT;
+ String DID;
+ String TOPIC_NAME;
+ String TOSCA_NODE_TYPE;
+ String CURR_ARTIFACT_UUID;
+ String PREV_ARTIFACT_UUID;
+ String ARTIFACT_TIMEOUT;
+ String MODIFIER;
+ String SERVICE_INSTANCE_ID;
+ String CONSUMER_ID;
+ String RESOURCE_URL;
+
+ public String getCONSUMER_ID() {
+ return CONSUMER_ID;
+ }
+
+ public void setCONSUMER_ID(String consumer_id) {
+ CONSUMER_ID = consumer_id;
+ }
+
+ public String getRESOURCE_URL() {
+ return RESOURCE_URL;
+ }
+
+ public void setRESOURCE_URL(String resource_url) {
+ RESOURCE_URL = resource_url;
+ }
+
+ public String getSERVICE_INSTANCE_ID() {
+ return SERVICE_INSTANCE_ID;
+ }
+
+ public void setSERVICE_INSTANCE_ID(String sERVICE_INSTANCE_ID) {
+ SERVICE_INSTANCE_ID = sERVICE_INSTANCE_ID;
+ }
+
+ public String getMODIFIER() {
+ return MODIFIER;
+ }
+
+ public void setMODIFIER(String mODIFIER) {
+ MODIFIER = mODIFIER;
+ }
+
+ public String getArtifactTimeout() {
+ return ARTIFACT_TIMEOUT;
+ }
+
+ public void setArtifactTimeout(String artifactTimeout) {
+ this.ARTIFACT_TIMEOUT = artifactTimeout;
+ }
+
+ public String getCurrArtifactUuid() {
+ return CURR_ARTIFACT_UUID;
+ }
+
+ public void setCurrArtifactUuid(String currArtifactUuid) {
+ this.CURR_ARTIFACT_UUID = currArtifactUuid;
+ }
+
+ public String getPrevArtifactUuid() {
+ return PREV_ARTIFACT_UUID;
+ }
+
+ public void setPrevArtifactUuid(String prevArtifactUuid) {
+ this.PREV_ARTIFACT_UUID = prevArtifactUuid;
+ }
+
+ public String getToscaNodeType() {
+ return TOSCA_NODE_TYPE;
+ }
+
+ public void setToscaNodeType(String ToscaNodeType) {
+ this.TOSCA_NODE_TYPE = ToscaNodeType;
+ }
+
+ public String getTopicName() {
+ return TOPIC_NAME;
+ }
+
+ public void setTopicName(String topicName) {
+ this.TOPIC_NAME = topicName;
+ }
+
+ public String getDistributionId() {
+ return DID;
+ }
+
+ public void setDistributionId(String did) {
+ this.DID = did;
+ }
+
+ public ExpectedResourceAuditJavaObject() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public ExpectedResourceAuditJavaObject(String action, String modifierName, String modifierUid, String status,
+ String desc, String resourceName, String resourceType, String prevVersion, String currVersion,
+ String prevState, String currState, String timestamp, String toscaNodesType, String timeout,
+ String modifier, String serviceInstanceId) {
+ super();
+ this.ACTION = action;
+ this.MODIFIER_NAME = modifierName;
+ this.MODIFIER_UID = modifierUid;
+ this.STATUS = status;
+ this.DESC = desc;
+ this.RESOURCE_NAME = resourceName;
+ this.RESOURCE_TYPE = resourceType;
+ this.PREV_VERSION = prevVersion;
+ this.CURR_VERSION = currVersion;
+ this.PREV_STATE = prevState;
+ this.CURR_STATE = currState;
+ this.TIMESTAMP = timestamp;
+ this.TOSCA_NODE_TYPE = toscaNodesType;
+ this.ARTIFACT_TIMEOUT = timeout;
+ this.MODIFIER = modifier;
+ this.SERVICE_INSTANCE_ID = serviceInstanceId;
+ }
+
+ public String getAction() {
+ return ACTION;
+ }
+
+ public void setAction(String action) {
+ this.ACTION = action;
+ }
+
+ public String getModifierName() {
+ return MODIFIER_NAME;
+ }
+
+ public void setModifierName(String modifierName) {
+ this.MODIFIER_NAME = modifierName;
+ }
+
+ public String getModifierUid() {
+ return MODIFIER_UID;
+ }
+
+ public void setModifierUid(String modifierUid) {
+ this.MODIFIER_UID = modifierUid;
+ }
+
+ public String getStatus() {
+ return STATUS;
+ }
+
+ public void setStatus(String status) {
+ this.STATUS = status;
+ }
+
+ public String getDesc() {
+ return DESC;
+ }
+
+ public void setDesc(String desc) {
+ this.DESC = desc;
+ }
+
+ public String getResourceName() {
+ return RESOURCE_NAME;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.RESOURCE_NAME = resourceName;
+ }
+
+ public String getResourceType() {
+ return RESOURCE_TYPE;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.RESOURCE_TYPE = resourceType;
+ }
+
+ public String getPrevVersion() {
+ return PREV_VERSION;
+ }
+
+ public void setPrevVersion(String prevVersion) {
+ this.PREV_VERSION = prevVersion;
+ }
+
+ public String getCurrVersion() {
+ return CURR_VERSION;
+ }
+
+ public void setCurrVersion(String currVersion) {
+ this.CURR_VERSION = currVersion;
+ }
+
+ public String getPrevState() {
+ return PREV_STATE;
+ }
+
+ public void setPrevState(String prevState) {
+ this.PREV_STATE = prevState;
+ }
+
+ public String getCurrState() {
+ return CURR_STATE;
+ }
+
+ public void setCurrState(String currState) {
+ this.CURR_STATE = currState;
+ }
+
+ public String getTimestamp() {
+ return TIMESTAMP;
+ }
+
+ public void setTimestamp(String timestamp) {
+ this.TIMESTAMP = timestamp;
+ }
+
+ public String getArtifactData() {
+ return ARTIFACT_DATA;
+ }
+
+ public void setArtifactData(String artifactData) {
+ this.ARTIFACT_DATA = artifactData;
+ }
+
+ public String getDprevStatus() {
+ return DPREV_STATUS;
+ }
+
+ public void setDprevStatus(String dprevStatus) {
+ this.DPREV_STATUS = dprevStatus;
+ }
+
+ public String getDcurrStatus() {
+ return DCURR_STATUS;
+ }
+
+ public void setDcurrStatus(String dcurrStatus) {
+ this.DCURR_STATUS = dcurrStatus;
+ }
+
+ public String getComment() {
+ return COMMENT;
+ }
+
+ public void setComment(String comment) {
+ this.COMMENT = comment;
+ }
+
+ @Override
+ public String toString() {
+ return "ExpectedResourceAuditJavaObject [ACTION=" + ACTION + ", STATUS=" + STATUS + ", DESC=" + DESC
+ + ", RESOURCE_NAME=" + RESOURCE_NAME + ", RESOURCE_TYPE=" + RESOURCE_TYPE + ", PREV_VERSION="
+ + PREV_VERSION + ", CURR_VERSION=" + CURR_VERSION + ", PREV_STATE=" + PREV_STATE + ", CURR_STATE="
+ + CURR_STATE + ", TIMESTAMP=" + TIMESTAMP + ", ARTIFACT_DATA=" + ARTIFACT_DATA + ", DPREV_STATUS="
+ + DPREV_STATUS + ", DCURR_STATUS=" + DCURR_STATUS + ", COMMENT=" + COMMENT + ", DID=" + DID
+ + ", TOPIC_NAME=" + TOPIC_NAME + ", TOSCA_NODE_TYPE=" + TOSCA_NODE_TYPE + ", CURR_ARTIFACT_UUID="
+ + CURR_ARTIFACT_UUID + ", PREV_ARTIFACT_UUID=" + PREV_ARTIFACT_UUID + ", ARTIFACT_TIMEOUT="
+ + ARTIFACT_TIMEOUT + ", MODIFIER=" + MODIFIER + ", SERVICE_INSTANCE_ID=" + SERVICE_INSTANCE_ID + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java
new file mode 100644
index 0000000000..2bc8625057
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/expected/ExpectedUserCRUDAudit.java
@@ -0,0 +1,98 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.expected;
+
+public class ExpectedUserCRUDAudit {
+ String action;
+ String modifier;
+ String status;
+ String desc;
+ String userBefore;
+ String userAfter;
+
+ public ExpectedUserCRUDAudit(String action, String modifier, String status, String desc, String userBefore,
+ String userAfter) {
+ super();
+ this.action = action;
+ this.modifier = modifier;
+ this.status = status;
+ this.desc = desc;
+ this.userBefore = userBefore;
+ this.userAfter = userAfter;
+ }
+
+ public ExpectedUserCRUDAudit() {
+ action = null;
+ modifier = null;
+ userBefore = null;
+ userAfter = null;
+ status = null;
+ desc = null;
+ }
+
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public String getModifier() {
+ return modifier;
+ }
+
+ public void setModifier(String modifier) {
+ this.modifier = modifier;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getDesc() {
+ return desc;
+ }
+
+ public void setDesc(String desc) {
+ this.desc = desc;
+ }
+
+ public String getUserBefore() {
+ return userBefore;
+ }
+
+ public void setUserBefore(String userBefore) {
+ this.userBefore = userBefore;
+ }
+
+ public String getUserAfter() {
+ return userAfter;
+ }
+
+ public void setUserAfter(String userAfter) {
+ this.userAfter = userAfter;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java
new file mode 100644
index 0000000000..2c23b08717
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderData.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+public class HeaderData {
+ String contentMd5;
+ String contentType;
+ String HttpCspUserId;
+ String HttpCspFirstName;
+ String HttpCspLastName;
+ String HttpCspWsType;
+ String HttpIvRemoteAddress;
+ String HttpIvUser;
+
+ public HeaderData() {
+ super();
+ }
+
+ public HeaderData(String contentMd5, String contentType, String httpCspUserId, String httpCspFirstName,
+ String httpCspLastName, String httpCspWsType, String httpIvRemoteAddress, String httpIvUser) {
+ super();
+ this.contentMd5 = contentMd5;
+ this.contentType = contentType;
+ HttpCspUserId = httpCspUserId;
+ HttpCspFirstName = httpCspFirstName;
+ HttpCspLastName = httpCspLastName;
+ HttpCspWsType = httpCspWsType;
+ HttpIvRemoteAddress = httpIvRemoteAddress;
+ HttpIvUser = httpIvUser;
+ }
+
+ public String getContentMd5() {
+ return contentMd5;
+ }
+
+ public void setContentMd5(String contentMd5) {
+ this.contentMd5 = contentMd5;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
+
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
+
+ public String getHttpCspUserId() {
+ return HttpCspUserId;
+ }
+
+ public void setHttpCspUserId(String httpCspUserId) {
+ HttpCspUserId = httpCspUserId;
+ }
+
+ public String getHttpCspFirstName() {
+ return HttpCspFirstName;
+ }
+
+ public void setHttpCspFirstName(String httpCspFirstName) {
+ HttpCspFirstName = httpCspFirstName;
+ }
+
+ public String getHttpCspLastName() {
+ return HttpCspLastName;
+ }
+
+ public void setHttpCspLastName(String httpCspLastName) {
+ HttpCspLastName = httpCspLastName;
+ }
+
+ public String getHttpCspWsType() {
+ return HttpCspWsType;
+ }
+
+ public void setHttpCspWsType(String httpCspWsType) {
+ HttpCspWsType = httpCspWsType;
+ }
+
+ public String getHttpIvRemoteAddress() {
+ return HttpIvRemoteAddress;
+ }
+
+ public void setHttpIvRemoteAddress(String httpIvRemoteAddress) {
+ HttpIvRemoteAddress = httpIvRemoteAddress;
+ }
+
+ public String getHttpIvUser() {
+ return HttpIvUser;
+ }
+
+ public void setHttpIvUser(String httpIvUser) {
+ HttpIvUser = httpIvUser;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java
new file mode 100644
index 0000000000..4a2ad9ab82
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HeaderValue.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+public enum HeaderValue {
+
+ APPLICATION_JSON("application/json");
+
+ String value;
+
+ private HeaderValue(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+
+ return value;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java
new file mode 100644
index 0000000000..cd3beee150
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpHeaderEnum.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+public enum HttpHeaderEnum {
+
+ Content_MD5("Content-MD5"),
+ USER_ID("USER_ID"),
+ HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"),
+ HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"),
+ HTTP_CSP_WSTYPE("HTTP_CSP_WSTYPE"),
+ HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"),
+ HTTP_IV_USER("HTTP_IV_USER"),
+ HTTP_CSP_EMAIL("HTTP_CSP_EMAIL"),
+ 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"),
+ CONTENT_DISPOSITION("Content-Disposition"),
+ HOST("Host"),
+ X_ECOMP_SERVICE_ID_HEADER("X-ECOMP-ServiceID"),
+ WWW_AUTHENTICATE("WWW-Authenticate"),
+ ECOMP_PASSWORD("password"),
+ ECOMP_USERNAME("username");
+
+ String value;
+
+ private HttpHeaderEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+
+ return value;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java
new file mode 100644
index 0000000000..7c2830ec5f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/HttpRequest.java
@@ -0,0 +1,883 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+import java.io.BufferedReader;
+import java.io.DataOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.StringWriter;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Scanner;
+
+import javax.net.ssl.HttpsURLConnection;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.annotation.NotThreadSafe;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.entity.mime.content.StringBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+public class HttpRequest {
+
+ static Logger logger = LoggerFactory.getLogger(HttpRequest.class.getName());
+
+ public RestResponse httpSendGet(String url, Map<String, String> headers) throws IOException {
+
+ RestResponse restResponse = new RestResponse();
+ 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) {
+ // logger.error("Error during getting input stream: ",e);
+ }
+
+ try {
+
+ result = IOUtils.toString(con.getErrorStream());
+ response.append(result);
+
+ } catch (Exception e) {
+ // logger.error("Error during getting error stream: ",e);
+ }
+
+ logger.debug("Response body: {}", response);
+
+ // print result
+
+ restResponse.setErrorCode(responseCode);
+
+ if (response != null) {
+ restResponse.setResponse(response.toString());
+ }
+
+ restResponse.setErrorCode(responseCode);
+ Map<String, List<String>> headerFields = con.getHeaderFields();
+ restResponse.setHeaderFields(headerFields);
+ String responseMessage = con.getResponseMessage();
+ restResponse.setResponseMessage(responseMessage);
+
+ con.disconnect();
+
+ return restResponse;
+ }
+
+ public RestResponse httpsSendGet(String url, Map<String, String> headers) throws IOException {
+
+ RestResponse restResponse = new RestResponse();
+ URL obj = new URL(url);
+ HttpsURLConnection con = (HttpsURLConnection) 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();
+ 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.setErrorCode(responseCode);
+
+ if (response != null) {
+ restResponse.setResponse(response.toString());
+ }
+
+ restResponse.setErrorCode(responseCode);
+ // restResponse.setResponse(result);
+ 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();
+ }
+
+ // con.connect();
+
+ 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) {
+ // response = null;
+ 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.setErrorCode(responseCode);
+ // if (response == null) {
+ // restResponse.setResponse(null);
+ // } else {
+ // restResponse.setResponse(response.toString());
+ // }
+
+ 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 sendHttpPost(String url, 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("POST");
+
+ // 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();
+ }
+
+ // con.connect();
+
+ 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.setErrorCode(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 httpSendPut(String url, String body, Map<String, String> headers) throws IOException {
+ return httpSendPost(url, body, headers, "PUT");
+ }
+
+ 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();
+ }
+
+ // con.connect();
+
+ 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.setErrorCode(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 httpSendDeleteWithBody2(String url, String body, Map<String, String> headers) throws ClientProtocolException, IOException {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ RestResponse restResponse = new RestResponse();
+ HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
+
+ // add request headers
+ if (headers != null) {
+ for (Entry<String, String> header : headers.entrySet()) {
+ String key = header.getKey();
+ String value = header.getValue();
+ httpDelete.addHeader(key, value);
+ }
+ }
+
+ // add body to request
+ StringEntity input = new StringEntity(body, ContentType.APPLICATION_JSON);
+ httpDelete.setEntity(input);
+
+ // execute request
+ CloseableHttpResponse response = httpclient.execute(httpDelete);
+
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+
+ return restResponse;
+ }
+
+ public RestResponse httpSendDeleteWithBody(String url, 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("DELETE");
+
+ // 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
+ con.setDoOutput(true);
+ DataOutputStream wr = new DataOutputStream(con.getOutputStream());
+ wr.writeBytes(body);
+ wr.flush();
+ wr.close();
+
+ // con.connect();
+
+ 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.setErrorCode(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 httpSendPostWithOutBody(String url, 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("POST");
+
+ // 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);
+ }
+ }
+
+ // con.connect();
+
+ 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) {
+ // response = null;
+ 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.setErrorCode(responseCode);
+ // if (response == null) {
+ // restResponse.setResponse(null);
+ // } else {
+ // restResponse.setResponse(response.toString());
+ // }
+
+ 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 httpSendPostMultipart(String url, Map<String, String> headers, String jsonLocation, String zipLocation) throws IOException {
+
+ Gson gson = new Gson();
+ String gsonToSend = null;
+ RestResponse restResponse = new RestResponse();
+ BufferedReader br = null;
+ //
+ //
+ //
+ //
+ // try {
+ //
+ // String sCurrentLine;
+ //
+ // br = new BufferedReader(new FileReader(jsonLocation));
+ //
+ // while ((sCurrentLine = br.readLine()) != null) {
+ // System.out.println(sCurrentLine);
+ // }
+ //
+ // } catch (IOException e) {
+ // e.printStackTrace();
+ // } finally {
+ // try {
+ // if (br != null)br.close();
+ // gsonToSend = br.toString();
+ // } catch (IOException ex) {
+ // ex.printStackTrace();
+ // }
+ // }
+
+ gsonToSend = new Scanner(new File(jsonLocation)).useDelimiter("\\Z").next();
+ logger.debug("gsonToSend: {}", gsonToSend);
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+ mpBuilder.addPart("resourceZip", new FileBody(new File(zipLocation)));
+ mpBuilder.addPart("resourceMetadata", new StringBody(gsonToSend, ContentType.APPLICATION_JSON));
+
+ HttpPost httpPost = new HttpPost(url);
+ httpPost.addHeader("USER_ID", "adminid");
+ httpPost.setEntity(mpBuilder.build());
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ CloseableHttpResponse response = client.execute(httpPost);
+ try {
+ logger.debug("----------------------------------------");
+ logger.debug("response.getStatusLine(): {}", response.getStatusLine());
+ HttpEntity resEntity = response.getEntity();
+ if (resEntity != null) {
+ logger.debug("Response content length: {}", resEntity.getContentLength());
+ }
+ EntityUtils.consume(resEntity);
+ } finally {
+
+ response.close();
+ client.close();
+ }
+
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+ restResponse.setResponse(response.getEntity().toString());
+
+ return restResponse;
+
+ }
+
+ public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username, String password) throws IOException {
+
+ String userPassword = username + ":" + password;
+ String encoding = Base64.encodeBase64String(userPassword.getBytes());
+ RestResponse restResponse = new RestResponse();
+ URL obj = new URL(url);
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
+
+ // add request method
+ con.setRequestMethod("POST");
+
+ con.setRequestProperty("Authorization", "Basic " + encoding);
+
+ // 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
+ con.setDoOutput(true);
+ DataOutputStream wr = new DataOutputStream(con.getOutputStream());
+ wr.writeBytes(body);
+ wr.flush();
+ wr.close();
+
+ // con.connect();
+
+ 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) {
+ response = null;
+
+ }
+ logger.debug("Response body: {}", response);
+
+ // print result
+
+ restResponse.setErrorCode(responseCode);
+ if (response == null) {
+ restResponse.setResponse(null);
+ } else {
+ 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.setErrorCode(responseCode);
+
+ if (response != null) {
+ restResponse.setResponse(response.toString());
+ }
+
+ restResponse.setErrorCode(con.getResponseCode());
+ Map<String, List<String>> headerFields = con.getHeaderFields();
+ restResponse.setHeaderFields(headerFields);
+ String responseMessage = con.getResponseMessage();
+ restResponse.setResponseMessage(responseMessage);
+
+ con.disconnect();
+
+ return restResponse;
+ }
+
+ public static RestResponse sendHttpPostWithEntity(HttpEntity requestEntity, String url, Map<String, String> headers) throws IOException, ClientProtocolException {
+ CloseableHttpResponse response = null;
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ RestResponse restResponse = new RestResponse();
+ for (Entry<String, String> entry : headers.entrySet()) {
+ httpPost.addHeader(entry.getKey(), entry.getValue());
+ }
+
+ httpPost.setEntity(requestEntity);
+ response = client.execute(httpPost);
+ HttpEntity responseEntity = response.getEntity();
+ String responseBody = null;
+ if (responseEntity != null) {
+ InputStream instream = responseEntity.getContent();
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(instream, writer);
+ responseBody = writer.toString();
+ try {
+
+ } finally {
+ instream.close();
+ }
+ }
+
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+ restResponse.setResponse(responseBody);
+
+ return restResponse;
+
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+ }
+
+ private static void closeHttpClient(CloseableHttpClient client) {
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
+ }
+ }
+
+ private static void closeResponse(CloseableHttpResponse response) {
+ try {
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
+ }
+ }
+
+ @NotThreadSafe
+ class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
+ public static final String METHOD_NAME = "DELETE";
+
+ public String getMethod() {
+ return METHOD_NAME;
+ }
+
+ public HttpDeleteWithBody(final String uri) {
+ super();
+ setURI(URI.create(uri));
+ }
+
+ public HttpDeleteWithBody(final URI uri) {
+ super();
+ setURI(uri);
+ }
+
+ public HttpDeleteWithBody() {
+ super();
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java
new file mode 100644
index 0000000000..6937608d2a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/MustHeaders.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class MustHeaders {
+
+ private Map<String, String> headers = new HashMap<String, String>();
+
+ public MustHeaders(HeaderData headerData) {
+
+ super();
+ headers.put(HttpHeaderEnum.Content_MD5.getValue(), headerData.getContentMd5());
+ headers.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), headerData.getContentType());
+ headers.put(HttpHeaderEnum.ACCEPT.getValue(), headerData.getContentType());
+ headers.put(HttpHeaderEnum.USER_ID.getValue(), headerData.getHttpCspUserId());
+ headers.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), headerData.getHttpCspFirstName());
+ headers.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), headerData.getHttpCspLastName());
+ headers.put(HttpHeaderEnum.HTTP_CSP_WSTYPE.getValue(), headerData.getHttpCspWsType());
+ headers.put(HttpHeaderEnum.HTTP_IV_REMOTE_ADDRESS.getValue(), headerData.getHttpIvRemoteAddress());
+ headers.put(HttpHeaderEnum.HTTP_IV_USER.getValue(), headerData.getHttpIvUser());
+
+ }
+
+ public MustHeaders() {
+ super();
+ }
+
+ public Map<String, String> getMap() {
+ return headers;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java
new file mode 100644
index 0000000000..f11d35a646
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/datatypes/http/RestResponse.java
@@ -0,0 +1,84 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.datatypes.http;
+
+import java.util.List;
+import java.util.Map;
+
+public class RestResponse {
+
+ Integer errorCode;
+ String response;
+ Map<String, List<String>> headerFields;
+ String responseMessage;
+
+ public RestResponse() {
+ super();
+ }
+
+ public RestResponse(Integer errorCode, String response, Map<String, List<String>> headerFields,
+ String responseMessage) {
+ super();
+ this.errorCode = errorCode;
+ this.response = response;
+ this.headerFields = headerFields;
+ this.responseMessage = responseMessage;
+ }
+
+ public Integer getErrorCode() {
+ return errorCode;
+ }
+
+ public void setErrorCode(Integer errorCode) {
+ this.errorCode = errorCode;
+ }
+
+ public String getResponse() {
+ return response;
+ }
+
+ public void setResponse(String response) {
+ this.response = response;
+ }
+
+ public Map<String, List<String>> getHeaderFields() {
+ return headerFields;
+ }
+
+ public void setHeaderFields(Map<String, List<String>> headerFields) {
+ this.headerFields = headerFields;
+ }
+
+ public String getResponseMessage() {
+ return responseMessage;
+ }
+
+ public void setResponseMessage(String responseMessage) {
+ this.responseMessage = responseMessage;
+ }
+
+ @Override
+ public String toString() {
+ return "RestResponse [errorCode=" + errorCode + ", response=" + response + ", headerFields=" + headerFields
+ + ", responseMessage=" + responseMessage + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java
new file mode 100644
index 0000000000..3af40c5bb8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/TODO/ImportCapabilityTypeCITest.java
@@ -0,0 +1,135 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.TODO;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.DbUtils.TitanState;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.Test;
+
+import fj.data.Either;
+
+public class ImportCapabilityTypeCITest {
+ public static final DbUtils DbUtils = new DbUtils();
+
+ @AfterClass
+ public static void afterClass() {
+ DbUtils.shutDowntitan();
+ }
+
+ static Config config = Config.instance();
+
+ // private final String IMPORT_CAPABILITY_TYPES_PATH =
+ // "src/test/resources/CI/importResourceTests/import_capabilitiesTypes/";
+
+ @Test
+ public void testAddingCapabilityTypes() throws IOException {
+ TitanState originalState = DbUtils.getCurrentTitanState();
+
+ String importResourceDir = config.getImportResourceConfigDir();
+
+ String capabilityTypes = importResourceDir + File.separator + "capabilityTypesCi.zip";
+ // importCapabilityType("src/test/resources/CI/importResource/capabilityTypesCi.zip");
+ importCapabilityType(capabilityTypes);
+ Either<Vertex, Boolean> eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci");
+ AssertJUnit.assertTrue(eitherVertex.isLeft());
+ DbUtils.restoreToTitanState(originalState);
+ eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.Test.Ci");
+ AssertJUnit.assertTrue(eitherVertex.isRight());
+ }
+
+ @Test
+ public void AddingCapabilityNotFound() throws IOException {
+ TitanState originalState = DbUtils.getCurrentTitanState();
+ String importResourceTestsDir = config.getImportResourceTestsConfigDir();
+ String capabilitiesTests = importResourceTestsDir + File.separator + "capabilityTypesCi.zip";
+ importCapabilityType(capabilitiesTests);
+ Either<Vertex, Boolean> eitherVertex = DbUtils.getVertexByUId("tosca.capabilities.NonExsitingCapability");
+ AssertJUnit.assertTrue(eitherVertex.isRight());
+ DbUtils.restoreToTitanState(originalState);
+ }
+
+ public static Integer importAllCapabilityTypes() throws IOException {
+
+ String importResourceDir = config.getImportResourceConfigDir() + File.separator + "capabilityTypes.zip";
+ // return
+ // importCapabilityType("src/test/resources/CI/importResource/capabilityTypes.zip");
+ return importCapabilityType(importResourceDir);
+ }
+
+ private static Integer importCapabilityType(String filePath) throws IOException {
+ Config config = Utils.getConfig();
+ CloseableHttpResponse response = null;
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("capabilityTypeZip", new FileBody(new File(filePath)));
+
+ String url = String.format(Urls.IMPORT_CAPABILITY_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ httpPost.addHeader("USER_ID", "jh0003");
+ httpPost.setEntity(mpBuilder.build());
+ response = client.execute(httpPost);
+ return response.getStatusLine().getStatusCode();
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+ }
+
+ private static void closeHttpClient(CloseableHttpClient client) {
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (IOException e) {
+ System.out.println("failed to close client or response: " + e.getMessage());
+ }
+ }
+
+ private static void closeResponse(CloseableHttpResponse response) {
+ try {
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException e) {
+ System.out.println("failed to close client or response: " + e.getMessage());
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java
new file mode 100644
index 0000000000..cd0647d8b1
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java
@@ -0,0 +1,656 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpResponseException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.BasicResponseHandler;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+import fj.data.Either;
+
+public class ArtifactServletTest extends ComponentBaseTest {
+
+ private static Logger log = LoggerFactory.getLogger(ArtifactServletTest.class.getName());
+ protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K";
+ protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk";
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+ protected Gson gson = new Gson();
+ protected JSONParser jsonParser = new JSONParser();
+ protected String serviceVersion;
+ protected Resource resourceDetailsVFCcomp;
+ protected Service defaultService1;
+
+ protected User sdncUserDetails;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ArtifactServletTest() {
+ super(name, ArtifactServletTest.class.getName());
+
+ }
+
+ @BeforeMethod
+ public void create() throws Exception {
+
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ Either<Resource, RestResponse> resourceDetailsVFCcompE = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE,
+ ResourceCategoryEnum.APPLICATION_L4_APP_SERVER, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVFCcomp = resourceDetailsVFCcompE.left().value();
+ Either<Service, RestResponse> defaultService1e = AtomicOperationUtils
+ .createDefaultService(UserRoleEnum.DESIGNER, true);
+ defaultService1 = defaultService1e.left().value();
+ }
+
+ @Test
+ public void upadteArtifactWithPayLoadToResourcseTest() throws Exception {
+
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
+ status);
+
+ defaultArtifact.setDescription("kjglkh");
+ defaultArtifact.setArtifactName("install_apache.sh");
+ defaultArtifact.setArtifactType("SHELL");
+ defaultArtifact.setPayload("new payload");
+
+ response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status);
+
+ response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(),
+ defaultArtifact, sdncUserDetails);
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status);
+
+ }
+
+ @Test
+ public void createAndUpdateArtifactToInterface() throws Exception {
+
+ CloseableHttpResponse response;
+ int status;
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+
+ try {
+ // upload artifact to interface
+ String interfaceName = "Standard";
+ String operationName = "configure";
+
+ String userBodyJson = createUploadArtifactBodyJson();
+ String url = String.format(Urls.UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName);
+
+ HttpPost httpPost = createPostAddArtifactRequeast(userBodyJson, url, true);
+ response = httpclient.execute(httpPost);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200);
+
+ // get artifact uniqueId
+ String artifactId = getLifecycleArtifactUid(response);
+
+ Map<String, Object> jsonBody = new HashMap<String, Object>();
+ jsonBody.put("artifactName", "TLV_prv.ppk");
+ jsonBody.put("artifactDisplayName", "configure");
+ jsonBody.put("artifactType", "SHELL");
+ jsonBody.put("mandatory", "false");
+ String newDescription = "new something";
+ jsonBody.put("description", newDescription);
+ jsonBody.put("artifactLabel", "configure");
+ userBodyJson = gson.toJson(jsonBody);
+
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName,
+ artifactId);
+
+ httpPost = createPostAddArtifactRequeast(userBodyJson, url, false);
+
+ response = httpclient.execute(httpPost);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status);
+
+ url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceDetailsVFCcomp.getUniqueId());
+ HttpGet httpGet = createGetRequest(url);
+ response = httpclient.execute(httpGet);
+ AssertJUnit.assertTrue(response.getStatusLine().getStatusCode() == 200);
+ String responseString = new BasicResponseHandler().handleResponse(response);
+
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ responseMap = (JSONObject) responseMap.get("interfaces");
+ responseMap = (JSONObject) responseMap.get(interfaceName.toLowerCase());
+ responseMap = (JSONObject) responseMap.get("operations");
+ responseMap = (JSONObject) responseMap.get(operationName.toLowerCase());
+ responseMap = (JSONObject) responseMap.get("implementation");
+ String description = (String) responseMap.get("description");
+
+ AssertJUnit.assertEquals("the new description value was not set", newDescription, description);
+
+ // delete artifact
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName,
+ artifactId);
+ HttpDelete httpDelete = createDeleteArtifactRequest(url);
+
+ response = httpclient.execute(httpDelete);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ protected String createUploadArtifactBodyJson() {
+ Map<String, Object> jsonBody = new HashMap<String, Object>();
+ jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME);
+ jsonBody.put("artifactDisplayName", "configure");
+ jsonBody.put("artifactType", "SHELL");
+ jsonBody.put("mandatory", "false");
+ jsonBody.put("description", "ff");
+ jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD);
+ jsonBody.put("artifactLabel", "configure");
+ return gson.toJson(jsonBody);
+ }
+
+ protected ArtifactDefinition getArtifactDataFromJson(String json) {
+ Gson gson = new Gson();
+ ArtifactDefinition artifact = new ArtifactDefinition();
+ artifact = gson.fromJson(json, ArtifactDefinition.class);
+
+ /*
+ * atifact.setArtifactName(UPLOAD_ARTIFACT_NAME);
+ * artifact.setArtifactDisplayName("configure");
+ * artifact.setArtifactType("SHELL"); artifact.setMandatory(false);
+ * artifact.setDescription("ff");
+ * artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD);
+ * artifact.setArtifactLabel("configure");
+ */
+ return artifact;
+ }
+
+ protected HttpGet createGetRequest(String url) {
+ HttpGet httpGet = new HttpGet(url);
+ httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ return httpGet;
+ }
+
+ protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String esId = (String) responseMap.get("EsId");
+ return esId;
+ }
+
+ protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact)
+ throws HttpResponseException, IOException, ParseException {
+ // String responseString = new
+ // BasicResponseHandler().handleResponse(response);
+ HttpEntity entity = response.getEntity();
+ String responseString = EntityUtils.toString(entity);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ artifact.setEsId((String) responseMap.get("esId"));
+ artifact.setUniqueId((String) responseMap.get("uniqueId"));
+ artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType")));
+ artifact.setTimeout(((Long) responseMap.get("timeout")).intValue());
+ return artifact;
+ }
+
+ protected String getLifecycleArtifactUid(CloseableHttpResponse response)
+ throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ responseMap = (JSONObject) responseMap.get("implementation");
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected HttpDelete createDeleteArtifactRequest(String url) {
+ HttpDelete httpDelete = new HttpDelete(url);
+ httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ return httpDelete;
+ }
+
+ protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header)
+ throws UnsupportedEncodingException {
+ HttpPost httppost = new HttpPost(url);
+ httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ if (addMd5Header) {
+ httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody));
+ }
+ StringEntity input = new StringEntity(jsonBody);
+ input.setContentType("application/json");
+ httppost.setEntity(input);
+ log.debug("Executing request {}", httppost.getRequestLine());
+ return httppost;
+ }
+
+ protected String createLoadArtifactBody() {
+ Map<String, Object> json = new HashMap<String, Object>();
+ json.put("artifactName", "install_apache2.sh");
+ json.put("artifactType", "SHELL");
+ json.put("description", "ddd");
+ json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz");
+ json.put("artifactLabel", "name123");
+
+ String jsonStr = gson.toJson(json);
+ return jsonStr;
+ }
+
+ protected void checkDeleteResponse(RestResponse response) {
+ BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404);
+ }
+
+ protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception {
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr,
+ ArtifactUiDownloadData.class);
+ return artifactUiDownloadData;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ // TODO
+ // @Ignore("")
+ @Test
+ public void addArtifactNoPayLoadToResourcseTest() throws Exception {
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+ defaultArtifact.setPayload(null);
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertTrue(status == 400);
+
+ }
+
+ @Test
+ public void upadteArtifactNoPayLoadToResourcseTest() throws Exception {
+
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
+ status);
+
+ defaultArtifact.setDescription("kjglkh");
+ defaultArtifact.setArtifactName("install_apache.sh");
+ defaultArtifact.setArtifactType("SHELL");
+ defaultArtifact.setPayload(null);
+
+ response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status);
+
+ response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(),
+ defaultArtifact, sdncUserDetails);
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status);
+
+ }
+
+ // TODO
+ @Test(enabled = false)
+ public void updateDeploymentArtifactToResourcseTest() throws Exception {
+
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultDeploymentArtifactForType("HEAT");
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
+ status);
+
+ response = ArtifactRestUtils.updateInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to update artifact metatdata: " + response.getErrorCode(), 200, status);
+
+ response = ArtifactRestUtils.deleteInformationalArtifactFromResource(resourceDetailsVFCcomp.getUniqueId(),
+ defaultArtifact, sdncUserDetails);
+ status = response.getErrorCode();
+ AssertJUnit.assertEquals("failed to remove artifact: " + response.getErrorCode(), 200, status);
+
+ }
+
+ // --------------------
+ @Test
+ public void addArtifactToResourcse_AlreadyExistsTest() throws Exception {
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ String jsonBody = createLoadArtifactBody();
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId());
+ HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true);
+ CloseableHttpResponse response = httpclient.execute(httppost);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertTrue("failed to add artifact", status == 200);
+
+ String artifactId = getArtifactUid(response);
+
+ httppost = createPostAddArtifactRequeast(jsonBody, url, true);
+ response = httpclient.execute(httppost);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("the returned status code is in correct", status, 400);
+
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), artifactId);
+ HttpDelete httpDelete = createDeleteArtifactRequest(url);
+ response = httpclient.execute(httpDelete);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertTrue("failed to remove artifact", status == 200);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void addArtifactToResourcse_MissingContentTest() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ Map<String, Object> json = new HashMap<String, Object>();
+ json.put("description", "desc");
+ json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz");
+ json.put("Content-MD5", "YTg2Mjg4MWJhNmI5NzBiNzdDFkMWI=");
+
+ String jsonBody = gson.toJson(json);
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId());
+ HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true);
+ CloseableHttpResponse response = httpclient.execute(httppost);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("the returned status code is in correct", status, 400);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void addArtifactToResourcse_MissingMd5Test() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ HashMap<String, Object> json = new HashMap<String, Object>();
+ json.put("artifactName", "install_apache.sh");
+ json.put("artifactType", "SHELL");
+ json.put("description", "kjglkh");
+ json.put("payloadData", "UEsDBYTEIWUYIFHWFMABCNAoAAAAIAAeLb0bDQz");
+ json.put("artifactLabel", "name123");
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId());
+ String jsonBody = gson.toJson(json);
+ HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, false);
+ CloseableHttpResponse response = httpclient.execute(httppost);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertTrue("failed to update artifact metatdata", status == 400);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void deleteArtifact_NotExistsTest() throws Exception {
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), "someFakeId");
+ HttpDelete httpDelete = createDeleteArtifactRequest(url);
+ CloseableHttpResponse response = httpclient.execute(httpDelete);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("the returned status code is in correct", status, 404);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void createAndRemoveArtifactToInterface() throws Exception {
+ CloseableHttpResponse response;
+ int status;
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+
+ try {
+ // upload artifact to interface
+ String interfaceName = "Standard";
+ String operationName = "configure";
+
+ String userBodyJson = createUploadArtifactBodyJson();
+ String url = String.format(Urls.UPLOAD_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName);
+
+ HttpPost httpPost = createPostAddArtifactRequeast(userBodyJson, url, true);
+ response = httpclient.execute(httpPost);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200);
+
+ // get artifact uniqueId
+ String artifactId = getLifecycleArtifactUid(response);
+
+ // delete artifact
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_BY_INTERFACE_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetailsVFCcomp.getUniqueId(), interfaceName, operationName,
+ artifactId);
+ HttpDelete httpDelete = createDeleteArtifactRequest(url);
+
+ response = httpclient.execute(httpDelete);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, status, 200);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void addArtifactToServiceTest() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+
+ try {
+ String jsonStr = createLoadArtifactBody();
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), defaultService1.getUniqueId());
+ HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true);
+ CloseableHttpResponse result = httpclient.execute(httpPost);
+ int status = result.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status);
+
+ String artifactId = getArtifactUid(result);
+
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), defaultService1.getUniqueId(), artifactId);
+ HttpDelete httpDelete = createDeleteArtifactRequest(url);
+
+ result = httpclient.execute(httpDelete);
+ status = result.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 200, returned :" + status, 200, status);
+ } finally {
+ RestResponse response = ServiceRestUtils.deleteService(defaultService1.getName(), serviceVersion,
+ sdncUserDetails);
+ checkDeleteResponse(response);
+ httpclient.close();
+ }
+ }
+
+ @Test
+ public void addArtifactNotSupportedTypeToServiceTest() throws Exception {
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ Map<String, Object> json = new HashMap<String, Object>();
+ json.put("artifactName", "install_apache.sh");
+ json.put("artifactType", "SHELL11");
+ json.put("description", "fff");
+ json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz");
+ json.put("artifactLabel", "name123");
+
+ String jsonStr = gson.toJson(json);
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), defaultService1.getUniqueId());
+
+ HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true);
+ CloseableHttpResponse result = httpclient.execute(httpPost);
+ int status = result.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("response code is not 400, returned :" + status, 400, status);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
+
+ String responseString = EntityUtils.toString(result.getEntity());
+
+ JSONObject map = (JSONObject) jsonParser.parse(responseString);
+ JSONObject requestError = (JSONObject) map.get("requestError");
+ JSONObject serviceException = (JSONObject) requestError.get("serviceException");
+
+ String msgId = (String) serviceException.get("messageId");
+ AssertJUnit.assertEquals("message id did not match expacted", errorInfo.getMessageId(), msgId);
+
+ String text = (String) serviceException.get("text");
+ AssertJUnit.assertEquals("text did not match expacted", errorInfo.getMessage(), text);
+
+ JSONArray variables = (JSONArray) serviceException.get("variables");
+ String type = (String) variables.get(0);
+ AssertJUnit.assertEquals("variable did not match expacted", "SHELL11", type);
+ } finally {
+ RestResponse response = ServiceRestUtils.deleteService(defaultService1.getName(), serviceVersion,
+ sdncUserDetails);
+ checkDeleteResponse(response);
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void addArtifactToResourceTest() throws Exception {
+
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetailsVFCcomp.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
+ status);
+
+ RestResponse resourceResp = ResourceRestUtils.getResource(resourceDetailsVFCcomp.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ AssertJUnit.assertNotNull(resource);
+
+ Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ boolean isExist = false;
+ for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
+ if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) {
+ isExist = true;
+
+ }
+ }
+ AssertJUnit.assertTrue(isExist);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java
new file mode 100644
index 0000000000..b3c3f3f5b6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/CrudArt.java
@@ -0,0 +1,1750 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ArtifactValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class CrudArt extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(CrudArt.class.getName());
+ private static final User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ private static final String HEAT_NET_LABEL = "heatnet";
+ private static final String HEAT_LABEL = "heat";
+
+ protected String testResourcesPath;
+ protected String testResourcesInstancesPath;
+
+ protected static final String dcaeInventoryToscaFile = "toscaSampleArtifact.yml";
+ protected static final String dcaeInventoryJsonFile = "jsonSampleArtifact.json";
+ protected static final String dcaeInventoryPolicyFile = "emfSampleArtifact.emf";
+ protected static final String dcaeInventoryDocFile = "docSampleArtifact.doc";
+ protected static final String dcaeInventoryBlueprintFile = "bluePrintSampleArtifact.xml";
+ protected static final String dcaeInventoryEventFile = "eventSampleArtifact.xml";
+
+ protected static final String heatSuccessFile = "asc_heat 0 2.yaml";
+ protected static final String heatNetSuccessFile = "asc_heat_net 0 2.yaml";
+ protected static final String yangFile = "addYangXmlArtifactToResource.xml";
+ protected static final String jsonFile = "jsonArtifact.json";
+ protected static final String invalidJsonFile = "invalidJson.json";
+ protected static final String invalidYangFile = "invalidYangXml.xml";
+ protected static final String otherFile = "other.txt";
+ protected static final String muranoFile = "asc_heat 0 2.zip";
+ protected static final String heatSuccessMiniFile = "heat_mini.yaml";
+ protected static final String heatInvalidFormat = "heatInvalidFormat.yaml";
+ protected static final String yamlInvalidFormat = "invalidYamlFormat.yaml";
+ protected static final String heatEnvfile = "heatEnvfile.env";
+
+ protected ServiceReqDetails serviceDetails;
+ protected ResourceReqDetails vfResourceDetails;
+ protected ResourceReqDetails cpResourceDetails;
+ protected ResourceReqDetails vfcResourceDetails;
+ protected ResourceReqDetails vlResourceDetails;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CrudArt() {
+ super(name, CrudArt.class.getName());
+ }
+
+ @DataProvider
+ private static final Object[][] getDepArtByType() throws IOException, Exception {
+ return new Object[][] { { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType()) },
+ { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType()) },
+ { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType()) },
+ { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()) }, { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType()) },
+ { ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType()) } };
+ }
+
+ @DataProvider
+ private static final Object[][] getServiceDepArtByType() throws IOException, Exception {
+ return new Object[][] { { ArtifactTypeEnum.OTHER.getType() }, { ArtifactTypeEnum.YANG_XML.getType() }, };
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+ // Set files working directory
+ String sourceDir = config.getResourceConfigDir();
+ String workDir = "HeatDeploymentArtifacts";
+ testResourcesPath = sourceDir + File.separator + workDir;
+ String workDirResourceInstanceArtifacts = "ResourceInstanceArtifacts";
+ testResourcesInstancesPath = sourceDir + File.separator + workDirResourceInstanceArtifacts;
+
+ // Build the components
+ Service serviceObj = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ serviceDetails = new ServiceReqDetails(serviceObj);
+
+ Resource vfcResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ vfcResourceDetails = new ResourceReqDetails(vfcResourceObj);
+
+ Resource vfResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ vfResourceDetails = new ResourceReqDetails(vfResourceObj);
+
+ Resource cpResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true).left().value();
+ cpResourceDetails = new ResourceReqDetails(cpResourceObj);
+
+ Resource vlResourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true).left().value();
+ vlResourceDetails = new ResourceReqDetails(vlResourceObj);
+ }
+
+ // ---------------------------------Resource
+ // success--------------------------------
+ @Test
+ public void addHeatArtifactToResourceAndCertify() throws Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // certified resource
+ RestResponse changeResourceState = LifecycleRestUtils.certifyResource(vfResourceDetails);
+ int status = changeResourceState.getErrorCode();
+ assertEquals("certify resource request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status);
+
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(changeResourceState.getResponse());
+ Map<String, ArtifactDefinition> artifactsMap = resourceJavaObject.getDeploymentArtifacts();
+ boolean flag = false;
+ if (artifactsMap != null) {
+ for (Entry<String, ArtifactDefinition> art : artifactsMap.entrySet()) {
+ if (art.getValue().getArtifactName().equals(heatArtifactDetails.getArtifactName())) {
+ assertTrue("expected artifact type is " + ArtifactGroupTypeEnum.DEPLOYMENT.getType() + " but was " + art.getValue().getArtifactGroupType(), art.getValue().getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT));
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("expected artifact not found", flag == true);
+ }
+
+ }
+
+ // ---------------------------------Resource
+ // success--------------------------------
+ @Test
+ public void addDcaeInventoryToscaArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryToscaFile;
+ String artifactName = dcaeInventoryToscaFile;
+ String artifactLabel = "dcae inv tosca label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addDcaeInventoryJsonArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryJsonFile;
+ String artifactName = dcaeInventoryJsonFile;
+ String artifactLabel = "dcae inv json label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_JSON;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addDcaeInventoryPolicyArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryPolicyFile;
+ String artifactName = dcaeInventoryPolicyFile;
+ String artifactLabel = "dcae inv policy label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_POLICY;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addDcaeInventoryDocArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryDocFile;
+ String artifactName = dcaeInventoryDocFile;
+ String artifactLabel = "dcae inv doc label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_DOC;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addDcaeInventoryBluePrintArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryBlueprintFile;
+ String artifactName = dcaeInventoryBlueprintFile;
+ String artifactLabel = "dcae inv blueprint label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addDcaeInventoryEventArtifactToResourceInstanceAndCertify() throws Exception {
+ String artifactFileName = dcaeInventoryEventFile;
+ String artifactName = dcaeInventoryEventFile;
+ String artifactLabel = "dcae inv event label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_EVENT;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ private RestResponse addArtifactToResourceInstanceAndCertify(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws Exception {
+
+ // Get the resource
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+
+ // Certify VF
+ Pair<Component, RestResponse> changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Add VF instance to service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+
+ // Get the VF instance
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance VfInstance = service.getComponentInstances().get(0);
+
+ // Create the artifact
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstance(artifactFileName, artifactName, artifactLabel, artifactType, VfInstance, serviceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addArtifactToResourceInstanceResponse.getResponseMessage());
+ return addArtifactToResourceInstanceResponse;
+ }
+
+ @Test
+ public void updateArtifactDescriptionToResourceInstance() throws Exception {
+ String artifactFileName = dcaeInventoryToscaFile;
+ String artifactName = dcaeInventoryToscaFile;
+ String artifactLabel = "dcae inv tosca label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addArtifactToResourceInstanceResponse.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Get the artifact from VF instance and change his description.
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance vfInstance = service.getComponentInstances().get(0);
+ Map<String, ArtifactDefinition> deploymentArtifacts = vfInstance.getDeploymentArtifacts();
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get("dcaeinvtoscalabel");
+ artifactDefinition.setDescription("My new description");
+
+ // Update the artifact
+ RestResponse updateDeploymentArtifactToRI = ArtifactRestUtils.updateArtifactToResourceInstance(artifactDefinition, sdncDesignerDetails1, vfInstance.getUniqueId(), service.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", updateDeploymentArtifactToRI.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateDeploymentArtifactToRI.getErrorCode(), updateDeploymentArtifactToRI.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void deleteArtifactToResourceInstance() throws Exception {
+ String artifactFileName = dcaeInventoryToscaFile;
+ String artifactName = dcaeInventoryToscaFile;
+ String artifactLabel = "dcae inv tosca label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.DCAE_INVENTORY_TOSCA;
+ RestResponse addArtifactToResourceInstanceResponse = addArtifactToResourceInstanceAndCertify(artifactFileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addArtifactToResourceInstanceResponse.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addArtifactToResourceInstanceResponse.getErrorCode(), addArtifactToResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Get the artifact from VF instance and change his description.
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance vfInstance = service.getComponentInstances().get(0);
+ Map<String, ArtifactDefinition> deploymentArtifacts = vfInstance.getDeploymentArtifacts();
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get("dcaeinvtoscalabel");
+
+ // Delete the artifact
+ RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils.deleteArtifactFromResourceInstance(artifactDefinition, sdncDesignerDetails1, vfInstance.getUniqueId(), service.getUniqueId());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + deleteInformationalArtifactFromResource.getErrorCode(), deleteInformationalArtifactFromResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addHeatArtifactToResource() throws Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ }
+
+ @Test
+ public void addHeatAndHeatNetArtifactsToResource() throws Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+
+ // Add HEAT
+ logger.debug("listFileName: {}", listFileName.toString());
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Add HEAT_NET
+ String payloadNet = FileUtils.loadPayloadFile(listFileName, heatNetSuccessFile, true);
+ ArtifactReqDetails heatNetArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType());
+ heatNetArtifactDetails.setPayload(payloadNet);
+ heatNetArtifactDetails.setArtifactLabel(HEAT_NET_LABEL);
+
+ RestResponse addInformationalArtifactToResource1 = ArtifactRestUtils.uploadArtifactToPlaceholderOnResource(heatNetArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId(), HEAT_NET_LABEL);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource1.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource1.getErrorCode(), addInformationalArtifactToResource1.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(vfResourceDetails, sdncDesignerDetails1);
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(HEAT_LABEL);
+ assertNotNull(artifactDefinition);
+ String heatEsId = artifactDefinition.getEsId();
+ assertNotNull(heatEsId);
+
+ ArtifactDefinition artifactDefinitionNet = deploymentArtifacts.get(HEAT_NET_LABEL);
+ assertNotNull(artifactDefinitionNet);
+ String heatNetEsId = artifactDefinitionNet.getEsId();
+ assertNotNull(heatNetEsId);
+ assertFalse(heatEsId.equalsIgnoreCase(heatNetEsId));
+ }
+
+ @Test
+ public void addDeleteAddHeatArtifactToResource() throws Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource(vfResourceDetails.getUniqueId(), heatArtifactDetails, sdncDesignerDetails1);
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + deleteInformationalArtifactFromResource.getErrorCode(), deleteInformationalArtifactFromResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ @Test
+ public void addYangXmlArtifactToResource() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "asc_heat 0 2.XML";
+ String artifactLabel = "Label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addOtherTypeDeploymentArtifactToResource() throws Exception {
+
+ String fileName = otherFile;
+ String artifactName = "other.txt";
+ String artifactLabel = "Label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.OTHER;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addYangXmlArtifactSameName() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "asc_heat_0_2.XML";
+ String artifactLabel = "Label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // Changing label but not name
+ artifactLabel = "Label1";
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == 400);
+ BaseValidationUtils.checkErrorResponse(addInformationalArtifactToResource, ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, new String[] { "Resource", vfResourceDetails.getName(), artifactName });
+
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addInvalidYangXmlFormat() throws Exception {
+
+ String fileName = invalidYangFile;
+ String artifactName = "asc_heat_0_2.XML";
+ String artifactLabel = "Label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == 400);
+ BaseValidationUtils.checkErrorResponse(addInformationalArtifactToResource, ActionStatus.INVALID_XML, new String[] { "YANG_XML" });
+
+ }
+
+ @Test
+ public void addSeveralYangXmlArtifacts() throws Exception {
+
+ // Adding 4 artifacts
+ String fileName = yangFile;
+ String artifactName = "asc_heat_0_2.XML";
+ String artifactLabel = "Label";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.YANG_XML;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // Changing label and name
+ artifactLabel = "Label1";
+ artifactName = "asc_heat_0_3.XML";
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Changing label and name
+ artifactLabel = "Label2";
+ artifactName = "asc_heat_0_4.XML";
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+
+ // Changing label and name
+ artifactLabel = "Label3";
+ artifactName = "asc_heat_0_5.XML";
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType);
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 4);
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void updateHeatArtifactToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ heatTypeArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // update
+ heatTypeArtifactDetails.setArtifactName("UPDATE.yaml");
+ heatTypeArtifactDetails.setPayloadData(null);
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", updateInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void updateHeatArtifactTimeOutToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ Resource resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1);
+ int actualTimeout = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getTimeout();
+ assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact timout, expected " + heatTypeArtifactDetails.getTimeout() + ", but was " + actualTimeout, heatTypeArtifactDetails.getTimeout() == actualTimeout);
+
+ // update
+ heatTypeArtifactDetails.setTimeout(35);
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", updateInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1);
+ actualTimeout = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getTimeout();
+ assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact timout, expected " + heatTypeArtifactDetails.getTimeout() + ", but was " + actualTimeout, heatTypeArtifactDetails.getTimeout() == actualTimeout);
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void updateHeatArtifactDescriptionToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ Resource resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1);
+ String actualDescription = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getDescription();
+ assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact Description, expected " + heatTypeArtifactDetails.getDescription() + ", but was " + actualDescription, heatTypeArtifactDetails.getDescription().equals(actualDescription));
+
+ // update
+ heatTypeArtifactDetails.setDescription("the best description was ever");
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", updateInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToResource.getErrorCode(), updateInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ resource = getResourceByResDetails(vfResourceDetails, sdncDesignerDetails1);
+ actualDescription = resource.getDeploymentArtifacts().get(heatTypeArtifactDetails.getArtifactLabel().toLowerCase()).getDescription();
+ assertTrue("verify " + heatTypeArtifactDetails.getArtifactLabel().toLowerCase() + " artifact Description, expected " + heatTypeArtifactDetails.getDescription() + ", but was " + actualDescription, heatTypeArtifactDetails.getDescription().equals(actualDescription));
+ }
+
+ private Resource getResourceByResDetails(ResourceReqDetails resDetails, User userDetails) throws IOException {
+ RestResponse response = ResourceRestUtils.getResource(resDetails, userDetails);
+ assertTrue("response code on get resource not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + response.getErrorCode(), response.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ return resource;
+ }
+
+ // ---------------------------------Service
+ // success--------------------------------
+ @Test()
+ public void addAllTypesDepArtifactToService() throws Exception, Exception {
+
+ // String fileName = heatSuccessFile;
+ // List<String> listFileName =
+ // FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ // logger.debug("listFileName: {}", listFileName.toString());
+
+ // String payload = FileUtils.loadPayloadFile(listFileName, fileName,
+ // true);
+ ArtifactReqDetails otherArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
+ // otherArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(otherArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ ArtifactReqDetails yangXmlArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType());
+
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(yangXmlArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ }
+
+ @Test(enabled = false)
+ public void addMuranoPkgArtifactToService() throws Exception, Exception {
+
+ String fileName = muranoFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MURANO_PKG.getType());
+ heatArtifactDetails.setPayload(payload);
+ heatArtifactDetails.setArtifactName("asc_heat 0 2.zip");
+ heatArtifactDetails.setArtifactLabel("Label");
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ }
+
+ @Test(dataProvider = "getServiceDepArtByType")
+ public void addHeatArtifactToServiceAndCertify(String artType) throws Exception, Exception {
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // certified service
+ RestResponse changeServiceState = LifecycleRestUtils.certifyService(serviceDetails);
+ int status = changeServiceState.getErrorCode();
+ assertEquals("certify service request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status);
+
+ Service resourceJavaObject = ResponseParser.convertServiceResponseToJavaObject(changeServiceState.getResponse());
+ Map<String, ArtifactDefinition> artifactsMap = resourceJavaObject.getDeploymentArtifacts();
+ boolean flag = false;
+ if (artifactsMap != null) {
+ for (Entry<String, ArtifactDefinition> art : artifactsMap.entrySet()) {
+ if (art.getValue().getArtifactName().equals(heatArtifactDetails.getArtifactName())) {
+ assertTrue("expected artifact type is " + ArtifactGroupTypeEnum.DEPLOYMENT.getType() + " but was " + art.getValue().getArtifactGroupType(), art.getValue().getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT));
+ flag = true;
+ break;
+ }
+ }
+ assertTrue("expected artifact not found", flag == true);
+ }
+
+ }
+
+ @Test(enabled = false, dataProvider = "getServiceDepArtByType")
+ public void updateHeatArtifactToService(String artType) throws Exception, Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // update
+ heatArtifactDetails.setPayloadData(payload);
+ RestResponse updateInformationalArtifactToService = ArtifactRestUtils.updateInformationalArtifactOfServiceByMethod(heatArtifactDetails, serviceDetails.getUniqueId(), sdncDesignerDetails1, "POST");
+ logger.debug("updateInformationalArtifactToService response: {}", updateInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + updateInformationalArtifactToService.getErrorCode(), updateInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ }
+
+ // --------------------------------------Resource Negative
+ // Tests-------------------------------------
+
+ // TODO Andrey the method of DEPLOYMENT artifact is update and not add
+ @Test(dataProvider = "getServiceDepArtByType")
+ public void addTheSameAdditionalHeatArtifactToResource(String artType) throws Exception, Exception {
+
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // add the same artifact one more time
+ artifactDetails.setArtifactLabel("the second artifact");
+ addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", vfResourceDetails.getName(), artifactDetails.getArtifactName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ @Test
+ public void addHeatArtifactTwiceSameNameToResource() throws Exception, Exception {
+
+ String filename1 = heatSuccessFile;
+ // String filename2 = heatSuccessMiniFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, filename1, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Add HEAT_NET
+ String payloadNet = FileUtils.loadPayloadFile(listFileName, heatNetSuccessFile, true);
+ ArtifactReqDetails heatNetArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType());
+ heatNetArtifactDetails.setPayload(payloadNet);
+ heatNetArtifactDetails.setArtifactLabel(HEAT_NET_LABEL);
+ heatNetArtifactDetails.setArtifactName(heatArtifactDetails.getArtifactName());
+
+ RestResponse addInformationalArtifactToResource1 = ArtifactRestUtils.uploadArtifactToPlaceholderOnResource(heatNetArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId(), HEAT_NET_LABEL);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource1.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource1.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatNetArtifactDetails.getArtifactName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource1.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatArtifactTwiceToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String filename1 = heatSuccessFile;
+ String filename2 = heatSuccessMiniFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, filename1, true);
+ heatTypeArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // add the second artifact
+ payload = FileUtils.loadPayloadFile(listFileName, heatSuccessMiniFile, true);
+ heatTypeArtifactDetails.setPayload(payload);
+ heatTypeArtifactDetails.setArtifactName(filename2);
+ heatTypeArtifactDetails.setArtifactLabel("the second artifact");
+
+ addInformationalArtifactToResource = ArtifactRestUtils.explicitAddInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatTypeArtifactDetails.getArtifactType(), heatTypeArtifactDetails.getArtifactType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatArtifactInvalidHeatFormatToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = heatInvalidFormat;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ heatTypeArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatArtifactInvalidYamlFormatToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = yamlInvalidFormat;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ heatTypeArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_YAML.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatArtifactInvalidFileExtensionToResource(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = yangFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ heatTypeArtifactDetails.setPayload(payload);
+ heatTypeArtifactDetails.setArtifactName(fileName);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList(heatTypeArtifactDetails.getArtifactType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatArtifactToResourceCertifyAndAddAdditionalHeatArtifact(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ heatTypeArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // certified resource
+ RestResponse changeResourceState = LifecycleRestUtils.certifyResource(vfResourceDetails);
+ int status = changeResourceState.getErrorCode();
+ assertEquals("certify resource request returned status:" + status, BaseRestUtils.STATUS_CODE_SUCCESS, status);
+
+ // add second HEAT artifact to the certified resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(vfResourceDetails, sdncDesignerDetails1, LifeCycleStatesEnum.CHECKOUT);
+ assertTrue("expected code response on change resource state to CHECKOUT BaseRestUtils.STATUS_CODE_SUCCESS, but was " + changeResourceState.getErrorCode(), changeResourceState.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // ArtifactReqDetails heatArtifactDetails1 =
+ // ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatTypeArtifactDetails.setPayload(payload);
+ heatTypeArtifactDetails.setArtifactName(fileName);
+ heatTypeArtifactDetails.setArtifactLabel("the second artifact");
+
+ addInformationalArtifactToResource = ArtifactRestUtils.explicitAddInformationalArtifactToResource(heatTypeArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", vfResourceDetails.getName(), heatTypeArtifactDetails.getArtifactType(), heatTypeArtifactDetails.getArtifactType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ }
+
+ // -----------------Service Negative
+ // Tests--------------------------------------------------------
+
+ // Absolute
+ @Test(enabled = false)
+ public void addHeatArtifactTwiceToService() throws Exception, Exception {
+
+ String fileName1 = heatSuccessFile;
+ String fileName2 = heatSuccessMiniFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName1, true);
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // add the second artifact
+ payload = FileUtils.loadPayloadFile(listFileName, fileName2, true);
+
+ ArtifactReqDetails heatArtifactDetails1 = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
+ heatArtifactDetails1.setPayload(payload);
+ heatArtifactDetails1.setArtifactName(fileName2);
+ heatArtifactDetails1.setArtifactLabel("the second artifact");
+
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails1, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode());
+
+ List<String> variables = Arrays.asList("Service", serviceDetails.getName(), ArtifactTypeEnum.OTHER.getType(), ArtifactTypeEnum.OTHER.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS.name(), variables, addInformationalArtifactToService.getResponse());
+
+ }
+
+ // TODO Andrey Obsolete
+ @Test(enabled = false)
+ public void addHeatArtifactInvalidHeatFormatToService() throws Exception, Exception {
+
+ String fileName = heatInvalidFormat;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode());
+
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT.name(), variables, addInformationalArtifactToService.getResponse());
+
+ }
+
+ // TODO Andrey Obsolete
+ @Test(enabled = false)
+ public void addHeatArtifactInvalidYamlFormatToService() throws Exception, Exception {
+
+ String fileName = yamlInvalidFormat;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_YAML.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode());
+
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML.name(), variables, addInformationalArtifactToService.getResponse());
+
+ }
+
+ @Test
+ public void addHeatArtifactInvalidFileExtensionToService() throws Exception, Exception {
+
+ String fileName = muranoFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType());
+ heatArtifactDetails.setPayload(payload);
+ heatArtifactDetails.setArtifactName(fileName);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ logger.debug("addInformationalArtifactToService response: {}", addInformationalArtifactToService.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode());
+
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.YANG_XML.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables, addInformationalArtifactToService.getResponse());
+
+ }
+
+ @Test(dataProvider = "getDepArtByType")
+ public void addHeatEnvArtifactToResourceNotSupportedType(ArtifactReqDetails heatTypeArtifactDetails) throws Exception, Exception {
+
+ String fileName = heatEnvfile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_ENV.getType());
+ heatArtifactDetails.setPayload(payload);
+ heatArtifactDetails.setArtifactName("asc_heat 0 2.env");
+ heatArtifactDetails.setArtifactLabel(heatTypeArtifactDetails.getArtifactLabel());
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToResource.getErrorCode());
+
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT_ENV.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addInformationalArtifactToResource.getResponse());
+ }
+
+ // TODO Andrey
+ @Test
+ public void addHeatArtifactToServiceNotSupportDeploymentArt() throws Exception, Exception {
+
+ String fileName = heatSuccessFile;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, fileName, true);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(payload);
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(heatArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), addInformationalArtifactToService.getErrorCode());
+
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addInformationalArtifactToService.getResponse());
+
+ }
+
+ protected RestResponse addArtifactToResourceInstance(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType, ComponentInstance componentInstance, ServiceReqDetails serviceDetails) throws Exception {
+ ArtifactReqDetails dcaeArtifactDetails = buildArtifactReqDetailsObject(testResourcesInstancesPath, artifactFileName, artifactName, artifactLabel, artifactType);
+ RestResponse addArtifactToResourceInstance = ArtifactRestUtils.addArtifactToResourceInstance(dcaeArtifactDetails, sdncDesignerDetails1, componentInstance.getUniqueId(), serviceDetails.getUniqueId());
+ return addArtifactToResourceInstance;
+ }
+
+ protected RestResponse addDeploymentArtifactToResource(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws Exception {
+ ArtifactReqDetails heatArtifactDetails = buildArtifactReqDetailsObject(testResourcesPath, artifactFileName, artifactName, artifactLabel, artifactType);
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, vfResourceDetails.getUniqueId());
+ return addInformationalArtifactToResource;
+ }
+
+ protected RestResponse addDeploymentArtifactToResource(String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType, ResourceReqDetails resource) throws Exception {
+ ArtifactReqDetails heatArtifactDetails = buildArtifactReqDetailsObject(testResourcesPath, artifactFileName, artifactName, artifactLabel, artifactType);
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1, resource.getUniqueId());
+ return addInformationalArtifactToResource;
+ }
+
+ // US672293 - Support new artifact type : BEVF_LICENSE , VENDOR_LICENSE
+ @Test
+ public void addNewArtifactsToVFResource() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ artifactName = "artifact2.xml";
+ artifactLabel = "Label2";
+ artifactType = ArtifactTypeEnum.VF_LICENSE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact6.xml";
+ artifactLabel = "Label6";
+ artifactType = ArtifactTypeEnum.APPC_CONFIG;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ fileName = jsonFile;
+ artifactName = "artifact7.json";
+ artifactLabel = "Label7";
+ artifactType = ArtifactTypeEnum.APPC_CONFIG;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 2);
+
+ }
+
+ @Test
+ public void addNewArtifactsToVFCResource() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact2.xml";
+ artifactLabel = "Label2";
+ artifactType = ArtifactTypeEnum.VF_LICENSE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifac5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactsToVfc() throws Exception {
+ String fileName = yangFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactsToCp() throws Exception {
+ String fileName = yangFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactsToVl() throws Exception {
+ String fileName = yangFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addVfInstanceWithNewArtifactsToService() throws Exception {
+ String fileName = yangFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ // Certify VF
+ Pair<Component, RestResponse> changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // Add VF instance to service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+ // get service and verify VF instance contain the Artifacts :VF_LICENSE
+ // and VENDOR_LICENSE
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance VfInstance = service.getComponentInstances().get(0);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VENDOR_LICENSE, 1);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VF_LICENSE, 1);
+ }
+
+ @Test
+ public void addNotSupportedArtifactsTypeToService01() throws Exception, Exception {
+ // Artifact type : VF_LICENSE
+ ArtifactReqDetails deploymentArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VF_LICENSE.getType());
+ RestResponse addDeploymentArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code eturned :" + addDeploymentArtifactToService.getErrorCode(), addDeploymentArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("VF_LICENSE");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToService.getResponse());
+ }
+
+ @Test
+ public void addNotSupportedArtifactsTypeToService02() throws Exception, Exception {
+ // Artifact type : VENDOR_LICENSE
+ ArtifactReqDetails deploymentArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VENDOR_LICENSE.getType());
+ RestResponse addDeploymentArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifactDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code eturned :" + addDeploymentArtifactToService.getErrorCode(), addDeploymentArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("VENDOR_LICENSE");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToService.getResponse());
+ }
+
+ @Test
+ public void addInvalidFileForArtifactTypeVendorLicenseToResource() throws Exception {
+ String fileName = yangFile;
+ String NonXmlFile = heatSuccessFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VF_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ // Artifact type VENDOR_LICENSE must be XML file
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(NonXmlFile, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code 400 returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("VENDOR_LICENSE");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_XML.name(), variables, addDeploymentArtifactToResource.getResponse());
+ // get resource and verify that file not exist within
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+ }
+
+ @Test
+ public void addInvalidFileForArtifactTypeVfLicenseToResource() throws Exception {
+ String fileName = yangFile;
+ String NonXmlFile = heatSuccessFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ // Artifact type VF_LICENSE must be XML file
+ artifactName = "artifact3.xml";
+ artifactLabel = "Label3";
+ artifactType = ArtifactTypeEnum.VF_LICENSE;
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(NonXmlFile, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code 400 returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("VF_LICENSE");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_XML.name(), variables, addDeploymentArtifactToResource.getResponse());
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+ }
+
+ @Test
+ public void addVendorLicenseArtifactAlreadyExistsInResource() throws Exception {
+ String fileName = yangFile;
+ String artifactName = "artifact2.xml";
+ String artifactLabel = "Label2";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VENDOR_LICENSE;
+ RestResponse addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ // Add same file again to resource
+ addDeploymentArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addDeploymentArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 400, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(artifactLabel.toLowerCase());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_EXIST.name(), variables, addDeploymentArtifactToResource.getResponse());
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ // US672294
+
+ @Test()
+ public void addVnfCatalogArtifactsToService() throws Exception, Exception {
+
+ ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.VNF_CATALOG.getType());
+ RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // get service and verify the Artifacts :VNF_CATALOG
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VNF_CATALOG, 1);
+ }
+
+ @Test()
+ public void addModelInventoryProfileArtifactsToService() throws Exception, Exception {
+
+ ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType());
+ RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // get service and verify the Artifacts :VNF_CATALOG
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, 1);
+ }
+
+ @Test()
+ public void addModelQuerySpecArtifactsToService() throws Exception, Exception {
+
+ ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_QUERY_SPEC.getType());
+ RestResponse resp = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + resp.getErrorCode(), resp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // get service and verify the Artifacts :VNF_CATALOG
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1);
+ }
+
+ @Test
+ public void addVfInstanceWithNewArtifactsToService02() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ fileName = yangFile;
+ artifactName = "artifact2.xml";
+ artifactLabel = "Label2";
+ artifactType = ArtifactTypeEnum.APPC_CONFIG;
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifac5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ // Certify VF
+ Pair<Component, RestResponse> changeComponentState = AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Add VF instance to service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true);
+
+ // get service and verify VF instance contain the Artifacts :VF_LICENSE
+ // and VENDOR_LICENSE
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance VfInstance = service.getComponentInstances().get(0);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.VNF_CATALOG, 1);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, 1);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1);
+ ArtifactValidationUtils.validateArtifactsNumberInComponentInstance(VfInstance, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.APPC_CONFIG, 1);
+ }
+
+ @Test
+ public void addAppcConfigArtifactToVfc() throws Exception {
+ String fileName = jsonFile;
+ String artifactName = "artifact7.json";
+ String artifactLabel = "Label7";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(artifactName);
+ variables.add("[VF]");
+ variables.add("VFC (Virtual Function Component)");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse());
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+ }
+
+ @Test
+ public void addAppcConfigArtifactToCp() throws Exception {
+ String fileName = jsonFile;
+ String artifactName = "artifact7.json";
+ String artifactLabel = "Label7";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(artifactName);
+ variables.add("[VF]");
+ variables.add("CP (Connection Point)");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse());
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+ }
+
+ @Test
+ public void addAppcConfigArtifactToVl() throws Exception {
+ String fileName = jsonFile;
+ String artifactName = "artifact7.json";
+ String artifactLabel = "Label7";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(artifactName);
+ variables.add("[VF]");
+ variables.add("VL (Virtual Link)");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE.name(), variables, addInformationalArtifactToResource.getResponse());
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+ }
+
+ @Test()
+ public void addAppcConfigArtifactsToService() throws Exception, Exception {
+ ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.APPC_CONFIG.getType());
+ RestResponse addDeploymentArtifactToResource = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code 400, returned :" + addDeploymentArtifactToResource.getErrorCode(), addDeploymentArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(ArtifactTypeEnum.APPC_CONFIG.toString());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED.name(), variables, addDeploymentArtifactToResource.getResponse());
+ }
+
+ @Test
+ public void addAppcConfigInvalidJsonToVFResourceFailed() throws Exception {
+
+ String fileName = invalidJsonFile;
+ String artifactName = "invalidJson.json";
+ String artifactLabel = "Label7";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.APPC_CONFIG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is 400, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(ArtifactTypeEnum.APPC_CONFIG.toString());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_JSON.name(), variables, addInformationalArtifactToResource.getResponse());
+
+ RestResponse getResource = ResourceRestUtils.getResource(vfResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 0);
+
+ }
+
+ @Test
+ public void addNewArtifactsToCp02() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifac5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, cpResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(cpResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactsToVl02() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifac5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vlResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vlResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactsToVfc02() throws Exception {
+
+ String fileName = yangFile;
+ String artifactName = "artifact1.xml";
+ String artifactLabel = "Label1";
+ ArtifactTypeEnum artifactType = ArtifactTypeEnum.VNF_CATALOG;
+
+ RestResponse addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifact4.xml";
+ artifactLabel = "Label4";
+ artifactType = ArtifactTypeEnum.MODEL_INVENTORY_PROFILE;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+
+ artifactName = "artifac5.xml";
+ artifactLabel = "Label5";
+ artifactType = ArtifactTypeEnum.MODEL_QUERY_SPEC;
+
+ addInformationalArtifactToResource = addDeploymentArtifactToResource(fileName, artifactName, artifactLabel, artifactType, vfcResourceDetails);
+ logger.debug("addInformationalArtifactToResource response: {}", addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToResource.getErrorCode(), addInformationalArtifactToResource.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ getResource = ResourceRestUtils.getResource(vfcResourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(resource, ArtifactGroupTypeEnum.DEPLOYMENT, artifactType, 1);
+ }
+
+ @Test
+ public void addNewArtifactAlreadyExistsInService() throws Exception {
+ ArtifactReqDetails artDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.MODEL_QUERY_SPEC.getType());
+ RestResponse addDeploymentArtifactoService = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addDeploymentArtifactoService.getErrorCode(), addDeploymentArtifactoService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ // get service and verify the Artifacts :VNF_CATALOG
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1);
+ // Add same file again to resource
+ addDeploymentArtifactoService = ArtifactRestUtils.addInformationalArtifactToService(artDetails, sdncDesignerDetails1, serviceDetails.getUniqueId());
+ assertTrue("response code is 400, returned :" + addDeploymentArtifactoService.getErrorCode(), addDeploymentArtifactoService.getErrorCode() == BaseRestUtils.STATUS_CODE_INVALID_CONTENT);
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(artDetails.getArtifactLabel().toLowerCase());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.ARTIFACT_EXIST.name(), variables, addDeploymentArtifactoService.getResponse());
+ // get service and verify the Artifacts :VNF_CATALOG is still exist and
+ // has one occurrences
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails1);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ArtifactValidationUtils.validateArtifactsNumberInComponent(service, ArtifactGroupTypeEnum.DEPLOYMENT, ArtifactTypeEnum.MODEL_QUERY_SPEC, 1);
+ }
+
+ private ArtifactReqDetails buildArtifactReqDetailsObject(String filesPath, String artifactFileName, String artifactName, String artifactLabel, ArtifactTypeEnum artifactType) throws IOException, Exception {
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, artifactFileName, true);
+
+ ArtifactReqDetails dcaeArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(artifactType.getType());
+ dcaeArtifactDetails.setPayload(payload);
+ dcaeArtifactDetails.setArtifactName(artifactName);
+ dcaeArtifactDetails.setArtifactLabel(artifactLabel);
+ return dcaeArtifactDetails;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
new file mode 100644
index 0000000000..0ae975207b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java
@@ -0,0 +1,687 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpResponseException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.BasicResponseHandler;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+
+import fj.data.Either;
+
+public class DownloadComponentArt extends ComponentBaseTest {
+
+ private static Logger log = LoggerFactory.getLogger(DownloadComponentArt.class.getName());
+ protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K";
+ protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk";
+
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+ protected Gson gson = new Gson();
+ protected JSONParser jsonParser = new JSONParser();
+
+ protected String serviceVersion;
+ protected ResourceReqDetails resourceDetails;
+ protected User sdncUserDetails;
+ protected ServiceReqDetails serviceDetails;
+
+ @BeforeMethod
+ public void init() throws Exception {
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ Resource resourceObj = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ Service serviceObj = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ resourceDetails = new ResourceReqDetails(resourceObj);
+ serviceDetails = new ServiceReqDetails(serviceObj);
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public DownloadComponentArt() {
+ super(name, DownloadComponentArt.class.getName());
+
+ }
+
+ // External API - Download artifact for resource
+ @Test
+ public void downloadArtifactFromResourceViaExternalAPI() throws Exception {
+ Resource resourceDetailsVF;
+ Either<Resource, RestResponse> createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(
+ ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE,
+ UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF = createdResource.left().value();
+ ArtifactDefinition heatArtifact = AtomicOperationUtils
+ .uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF, UserRoleEnum.DESIGNER, true, true)
+ .left().value();
+ resourceDetails = new ResourceReqDetails(resourceDetailsVF);
+
+ String resourceUUID = resourceDetailsVF.getUUID();
+ String artifactUUID = heatArtifact.getArtifactUUID();
+
+ System.out.println("Resource UUID: " + resourceUUID);
+ System.out.println("Artifact UUID: " + artifactUUID);
+
+ RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID,
+ artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Resource");
+
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+
+ String response = restResponse.getResponse();
+
+ String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ String decodedPaypload = Decoder.decode(payloadData);
+
+ Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct.");
+
+ String auditAction = "ArtifactDownload";
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
+ String resource_url = String.format("/asdc/v1/catalog/resources/%s/artifacts/%s", resourceUUID, artifactUUID);
+ expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+
+ AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null,
+ false);
+ }
+
+ // External API - Download artifact for resource - negative test
+ @Test
+ public void downloadArtifactFromResourceViaExternalAPINegativeTest() throws Exception {
+ Resource resourceDetailsVF;
+ Either<Resource, RestResponse> createdResource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(
+ ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE,
+ UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF = createdResource.left().value();
+ ArtifactDefinition heatArtifact = AtomicOperationUtils
+ .uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF, UserRoleEnum.DESIGNER, true, true)
+ .left().value();
+ resourceDetails = new ResourceReqDetails(resourceDetailsVF);
+
+ String resourceUUID = resourceDetailsVF.getUUID();
+ String artifactUUID = heatArtifact.getArtifactUUID();
+
+ System.out.println("Resource UUID: " + resourceUUID);
+ System.out.println("Artifact UUID: " + artifactUUID);
+
+ RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID,
+ "dfsgfdsg324", ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Resource");
+
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+ }
+
+ // External API - Download artifact for service - negative test
+ @Test
+ public void downloadArtifactFromServiceViaExternalAPI() throws Exception {
+
+ Service resourceDetailsService;
+ Either<Service, RestResponse> createdResource = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER,
+ true);
+ resourceDetailsService = createdResource.left().value();
+
+ ArtifactDefinition heatArtifact = AtomicOperationUtils
+ .uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsService, UserRoleEnum.DESIGNER, true, true)
+ .left().value();
+
+ String resourceUUID = resourceDetailsService.getUUID();
+ String artifactUUID = heatArtifact.getArtifactUUID();
+
+ System.out.println("Resource UUID: " + resourceUUID);
+ System.out.println("Artifact UUID: " + artifactUUID);
+
+ RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID,
+ artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service");
+
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+
+ String response = restResponse.getResponse();
+
+ String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ String decodedPaypload = Decoder.decode(payloadData);
+
+ Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct.");
+
+ String auditAction = "ArtifactDownload";
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setResourceName(resourceDetailsService.getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
+ String resource_url = String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceUUID, artifactUUID);
+ expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+
+ AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null,
+ false);
+ }
+
+ // External API - Download ComponentInstance artifact of service - negative
+ // test
+ @Test
+ public void downloadArtifactOfComponentInstanceFromServiceViaExternalAPI() throws Exception {
+
+ Either<Resource, RestResponse> resourceDetailsVF_01e = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+ Component resourceDetailsVF_01 = resourceDetailsVF_01e.left().value();
+ ArtifactDefinition heatArtifact = AtomicOperationUtils
+ .uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true)
+ .left().value();
+
+ resourceDetailsVF_01 = AtomicOperationUtils
+ .changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true)
+ .getLeft();
+
+ Service resourceDetailsService;
+ Either<Service, RestResponse> createdResource = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER,
+ true);
+ resourceDetailsService = createdResource.left().value();
+
+ ComponentInstance resourceDetailsVF1ins_01 = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceDetailsVF_01, resourceDetailsService,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+
+ System.out.println("-----");
+
+ String resourceUUID = resourceDetailsService.getUUID();
+ String componentInstanceUID = resourceDetailsVF1ins_01.getUniqueId();
+ String artifactUUID = heatArtifact.getArtifactUUID();
+
+ System.out.println("Resource UUID: " + resourceUUID);
+ System.out.println("Component instance UID: " + componentInstanceUID);
+ System.out.println("Artifact UUID: " + artifactUUID);
+
+ RestResponse restResponse = ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceUUID,
+ componentInstanceUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service");
+ //
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+
+ String response = restResponse.getResponse();
+
+ String payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ String decodedPaypload = Decoder.decode(payloadData);
+
+ Assert.assertEquals(response, decodedPaypload, "Response deployment artifact not correct.");
+
+ String auditAction = "ArtifactDownload";
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setResourceName(resourceDetailsVF1ins_01.getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
+ String resource_url = String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s",
+ resourceUUID, componentInstanceUID, artifactUUID);
+ expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+
+ AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject, auditAction, null,
+ false);
+ }
+
+ @Test
+ public void downloadArtifactFromResourceTest() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ String jsonBody = createUploadArtifactBodyJson();
+
+ String resourceId = resourceDetails.getUniqueId();
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceId);
+ HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true);
+ HttpResponse response = httpclient.execute(httppost);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("failed to add artifact", 200, status);
+
+ ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonBody);
+ addArtifactDataFromResponse(response, origArtifact);
+ String artifactId = origArtifact.getUniqueId();
+
+ url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceId, artifactId);
+ HttpGet httpGet = createGetRequest(url);
+ response = httpclient.execute(httpGet);
+ status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("failed to download artifact", 200, status);
+
+ InputStream inputStream = response.getEntity().getContent();
+ ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream));
+ AssertJUnit.assertEquals("Downloaded payload is different from uploaded one", UPLOAD_ARTIFACT_PAYLOAD,
+ artifactUiDownloadData.getBase64Contents());
+ AssertJUnit.assertEquals("Downloaded artifact name is different from uploaded one", UPLOAD_ARTIFACT_NAME,
+ artifactUiDownloadData.getArtifactName());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
+ String auditAction = "ArtifactDownload";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact));
+ expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void downloadArtifactFromServiceTest() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+
+ try {
+
+ String jsonStr = createUploadArtifactBodyJson();
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), serviceDetails.getUniqueId());
+ HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true);
+ CloseableHttpResponse result = httpclient.execute(httpPost);
+ int status = result.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("failed to add artifact", 200, status);
+
+ ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonStr);
+ addArtifactDataFromResponse(result, origArtifact);
+ String artifactId = origArtifact.getUniqueId();
+
+ url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(),
+ serviceDetails.getUniqueId(), artifactId);
+ HttpGet httpGet = createGetRequest(url);
+ CloseableHttpResponse response2 = httpclient.execute(httpGet);
+ status = response2.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("failed to download artifact", 200, status);
+ InputStream inputStream = response2.getEntity().getContent();
+ ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream));
+ AssertJUnit.assertEquals("Downloaded payload is different from uploaded one", UPLOAD_ARTIFACT_PAYLOAD,
+ artifactUiDownloadData.getBase64Contents());
+ AssertJUnit.assertEquals("Downloaded artifact name is different from uploaded one", UPLOAD_ARTIFACT_NAME,
+ artifactUiDownloadData.getArtifactName());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = AuditValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails);
+ String auditAction = "ArtifactDownload";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact));
+ expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ } finally {
+ // RestResponse response =
+ // ServiceRestUtils.deleteService(serviceDetails, serviceVersion,
+ // sdncUserDetails );
+ // checkDeleteResponse(response);
+ httpclient.close();
+ }
+ }
+
+ @Test
+ public void downloadArtifactFromResourceNotFound() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+
+ String resourceId = resourceDetails.getUniqueId();
+ String artifactIdNotFound = "11111";
+
+ ArtifactDefinition origArtifact = new ArtifactDefinition();
+ origArtifact.setUniqueId(artifactIdNotFound);
+
+ String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceId, artifactIdNotFound);
+ HttpGet httpGet = createGetRequest(url);
+ CloseableHttpResponse response = httpclient.execute(httpGet);
+ int status = response.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("expected 404 not found", 404, status);
+
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
+ String auditAction = "ArtifactDownload";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ expectedResourceAuditJavaObject.setArtifactData("");
+ expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ expectedResourceAuditJavaObject.setPrevArtifactUuid(null);
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void downloadArtifactFromServiceNotFound() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+
+ String artifactIdNotFound = "11111";
+ ArtifactDefinition origArtifact = new ArtifactDefinition();
+ origArtifact.setUniqueId(artifactIdNotFound);
+
+ String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(),
+ config.getCatalogBePort(), serviceDetails.getUniqueId(), artifactIdNotFound);
+ HttpGet httpGet = createGetRequest(url);
+ CloseableHttpResponse response2 = httpclient.execute(httpGet);
+ int status = response2.getStatusLine().getStatusCode();
+ AssertJUnit.assertEquals("expected 404 not found", 404, status);
+
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), sdncUserDetails);
+ String auditAction = "ArtifactDownload";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ expectedResourceAuditJavaObject.setArtifactData("");
+ expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ } finally {
+ httpclient.close();
+ }
+
+ }
+
+ @Test
+ public void addArtifactToResourceTest() throws Exception {
+
+ ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact, sdncUserDetails,
+ resourceDetails.getUniqueId());
+ int status = response.getErrorCode();
+ AssertJUnit.assertEquals("add informational artifact request returned status: " + response.getErrorCode(), 200,
+ status);
+
+ RestResponse resourceResp = ResourceRestUtils.getResource(resourceDetails.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ AssertJUnit.assertNotNull(resource);
+
+ Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ boolean isExist = false;
+ for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
+ if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) {
+ isExist = true;
+
+ }
+ }
+ AssertJUnit.assertTrue(isExist);
+ }
+
+ protected String createUploadArtifactBodyJson() {
+ Map<String, Object> jsonBody = new HashMap<String, Object>();
+ jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME);
+ jsonBody.put("artifactDisplayName", "configure");
+ jsonBody.put("artifactType", "SHELL");
+ jsonBody.put("mandatory", "false");
+ jsonBody.put("description", "ff");
+ jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD);
+ jsonBody.put("artifactLabel", "configure");
+ return gson.toJson(jsonBody);
+ }
+
+ protected ArtifactDefinition getArtifactDataFromJson(String json) {
+ Gson gson = new Gson();
+ JsonObject jsonElement = new JsonObject();
+ jsonElement = gson.fromJson(json, jsonElement.getClass());
+ ArtifactDefinition artifact = new ArtifactDefinition();
+ String payload = null;
+ JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
+ if (artifactPayload != null && !artifactPayload.isJsonNull()) {
+ payload = artifactPayload.getAsString();
+ }
+ jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
+ artifact = gson.fromJson(jsonElement, ArtifactDefinition.class);
+ artifact.setPayloadData(payload);
+
+ /*
+ * atifact.setArtifactName(UPLOAD_ARTIFACT_NAME);
+ * artifact.setArtifactDisplayName("configure");
+ * artifact.setArtifactType("SHELL"); artifact.setMandatory(false);
+ * artifact.setDescription("ff");
+ * artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD);
+ * artifact.setArtifactLabel("configure");
+ */
+ return artifact;
+ }
+
+ protected HttpGet createGetRequest(String url) {
+ HttpGet httpGet = new HttpGet(url);
+ httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ return httpGet;
+ }
+
+ protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String esId = (String) responseMap.get("EsId");
+ return esId;
+ }
+
+ protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact)
+ throws HttpResponseException, IOException, ParseException {
+ // String responseString = new
+ // BasicResponseHandler().handleResponse(response);
+ HttpEntity entity = response.getEntity();
+ String responseString = EntityUtils.toString(entity);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ artifact.setEsId((String) responseMap.get("esId"));
+ artifact.setUniqueId((String) responseMap.get("uniqueId"));
+ artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType")));
+ artifact.setTimeout(((Long) responseMap.get("timeout")).intValue());
+ return artifact;
+ }
+
+ protected String getLifecycleArtifactUid(CloseableHttpResponse response)
+ throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ responseMap = (JSONObject) responseMap.get("implementation");
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected HttpDelete createDeleteArtifactRequest(String url) {
+ HttpDelete httpDelete = new HttpDelete(url);
+ httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ return httpDelete;
+ }
+
+ protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header)
+ throws UnsupportedEncodingException {
+ HttpPost httppost = new HttpPost(url);
+ httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ if (addMd5Header) {
+ httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody));
+ }
+ StringEntity input = new StringEntity(jsonBody);
+ input.setContentType("application/json");
+ httppost.setEntity(input);
+ log.debug("Executing request {}", httppost.getRequestLine());
+ return httppost;
+ }
+
+ protected String createLoadArtifactBody() {
+ Map<String, Object> json = new HashMap<String, Object>();
+ json.put("artifactName", "install_apache2.sh");
+ json.put("artifactType", "SHELL");
+ json.put("description", "ddd");
+ json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz");
+ json.put("artifactLabel", "name123");
+
+ String jsonStr = gson.toJson(json);
+ return jsonStr;
+ }
+
+ protected void checkDeleteResponse(RestResponse response) {
+ BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404);
+ }
+
+ protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception {
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr,
+ ArtifactUiDownloadData.class);
+ return artifactUiDownloadData;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java
new file mode 100644
index 0000000000..02bef89f2c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/PlaceHolderValidations.java
@@ -0,0 +1,696 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+//import static org.junit.Assert.assertTrue;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.javatuples.Pair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.datastax.driver.core.Row;
+
+import fj.data.Either;
+
+public class PlaceHolderValidations extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(PlaceHolderValidations.class.getName());
+ private static final String heatExtension = "yaml";
+ // private static final String yangXmlExtension = "xml";
+ // private static final String muranoPkgExtension = "zip";
+ private final String folderName = "addHeatArtifactToServiceAndSertify";
+ private Resource resource;
+ private final int timeOut = 60;
+ private ArtifactReqDetails updateArtifactReqDetails = null;
+ protected User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected User sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+ protected ResourceReqDetails resourceDetails1;
+ protected ResourceReqDetails resourceVF;
+ protected ResourceReqDetails resourceCP;
+ protected ResourceReqDetails resourceVL;
+
+ protected ArtifactReqDetails heatArtifactDetails;
+ protected ArtifactReqDetails heatVolArtifactDetails;
+ protected ArtifactReqDetails heatNetArtifactDetails;
+
+ public PlaceHolderValidations() {
+ super(name, PlaceHolderValidations.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ @BeforeMethod
+ public void init() throws IOException, Exception {
+
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatNetArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType());
+ heatVolArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType());
+ Resource resourceObject = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetails1 = new ResourceReqDetails(resourceObject);
+ resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ resourceVF = new ResourceReqDetails(resourceObject);
+ resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ resourceCP = new ResourceReqDetails(resourceObject);
+ resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ resourceVL = new ResourceReqDetails(resourceObject);
+ }
+
+ @Test
+ public void validateDeploymentPlaceHoldersByConfig() throws IOException {
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+ Resource resourceObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceObject.getDeploymentArtifacts();
+ assertNotNull("deploymentArtifacts list is null", deploymentArtifacts);
+ List<String> listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String resDepArtType : listOfResDepArtTypesFromConfig) {
+ assertNotNull("placeholder of " + resDepArtType + " type doesn't exist",
+ deploymentArtifacts.get(resDepArtType));
+ }
+ }
+
+ private void validateToscaArtifactsBeforeAndAfterSFT(ResourceReqDetails resourceDetails)
+ throws IOException, Exception {
+ RestResponse componentResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1);
+ Component component = ResponseParser.convertResourceResponseToJavaObject(componentResponse.getResponse());
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ for (ArtifactDefinition artifact : toscaArtifacts.values()) {
+ assertNull(artifact.getEsId());
+ }
+
+ componentResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ component = ResponseParser.convertResourceResponseToJavaObject(componentResponse.getResponse());
+ toscaArtifacts = component.getToscaArtifacts();
+
+ for (ArtifactDefinition artifact : toscaArtifacts.values()) {
+ assertEquals(artifact.getEsId(), artifact.getUniqueId());
+ List<Pair<String, String>> fields = new ArrayList();
+ fields.add(new Pair<String, String>("id", artifact.getEsId()));
+ List<Row> fetchFromTable = CassandraUtils.fetchFromTableQuery("sdcartifact", "resources", fields);
+ assertTrue(1 == fetchFromTable.size());
+ }
+ }
+
+ @Test
+ public void validateToscaArtifactsBeforeAndAfterSFT() throws IOException, Exception {
+ // TODO ADD VF and Service
+ validateToscaArtifactsBeforeAndAfterSFT(resourceDetails1);
+ validateToscaArtifactsBeforeAndAfterSFT(resourceCP);
+ validateToscaArtifactsBeforeAndAfterSFT(resourceVL);
+ }
+
+ @Test
+ public void validateToscaPlaceHoldersByConfig() throws IOException, Exception {
+ List<Component> components = new ArrayList<>();
+ RestResponse componentGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+ components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse()));
+
+ componentGetResponse = ResourceRestUtils.getResource(resourceCP, sdncDesignerDetails1);
+ components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse()));
+
+ componentGetResponse = ResourceRestUtils.getResource(resourceVF, sdncDesignerDetails1);
+ components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse()));
+
+ componentGetResponse = ResourceRestUtils.getResource(resourceVL, sdncDesignerDetails1);
+ components.add(ResponseParser.convertResourceResponseToJavaObject(componentGetResponse.getResponse()));
+
+ Service service = AtomicOperationUtils
+ .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ componentGetResponse = ServiceRestUtils.getService(service.getUniqueId(),
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ components.add(ResponseParser.parseToObjectUsingMapper(componentGetResponse.getResponse(), Service.class));
+
+ for (Component component : components) {
+ Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
+ assertNotNull("toscaArtifacts list is null", toscaArtifacts);
+ List<String> listOfToscaArtTypesFromConfig = Utils.getListOfToscaArtLabels(true);
+ assertNotNull("tosca artifact types list is null", listOfToscaArtTypesFromConfig);
+ for (String toscaArtType : listOfToscaArtTypesFromConfig) {
+ assertNotNull("placeholder of " + toscaArtType + " type doesn't exist",
+ toscaArtifacts.get(toscaArtType));
+ }
+ }
+
+ }
+
+ // test check configuration of "displayName" field for "heat" type
+ // deployment artifact
+ @Test
+ public void validateDeploymentPlaceHoldersDescriptionOfHeatByConfig() throws IOException {
+
+ Map<String, Object> mapOfDepResArtTypesObjects = getMapOfDepResArtTypesObjects();
+ assertNotNull("deployment artifact types list is null", mapOfDepResArtTypesObjects);
+ Object object = mapOfDepResArtTypesObjects.get("heat");
+ if (object instanceof Map<?, ?>) {
+ Map<String, Object> map = (Map<String, Object>) object;
+ assertTrue(map.get("displayName").equals("Base HEAT Template"));
+ } else {
+ assertTrue("return object does not instance of map", false);
+ }
+ }
+
+ @Test
+ public void addDepResArtEachType() throws Exception {
+
+ String artType;
+
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails);
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ List<String> listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String iter : listOfResDepArtTypesFromConfig) {
+ artType = iter;
+ verifyDepArtPlaceHoldersByType(artType);
+ }
+ }
+
+ @Test
+ public void checkHeatParametersExistingForEachType() throws Exception {
+
+ String artType;
+
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails);
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ List<String> listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String iter : listOfResDepArtTypesFromConfig) {
+ artType = iter;
+ verifyDepArtPlaceHoldersByType(artType);
+ verifyHeatParametersExistance(artType, false);
+ }
+ }
+
+ @Test
+ public void checkHeatParametersExistingForSpecificType() throws Exception {
+
+ String artType;
+
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails);
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ List<String> listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String iter : listOfResDepArtTypesFromConfig) {
+ artType = iter;
+ if (heatArtifactDetails.getArtifactLabel().equals(iter)) {
+ verifyHeatParametersExistance(artType, true);
+ } else {
+ verifyHeatParametersExistance(artType, false);
+ }
+ }
+ }
+
+ @Test
+ public void addAndDeleteDepResArtEachType() throws Exception {
+
+ String artType;
+
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails);
+ addDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails);
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ List<String> listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String iter : listOfResDepArtTypesFromConfig) {
+ artType = iter;
+ verifyDepArtPlaceHoldersByType(artType);
+ }
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1,
+ sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN);
+ assertTrue("expected response code in CHECKIN 200", restResponseResource.getErrorCode() == 200);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertTrue("expected response code in CHECKOUT 200", restResponseResource.getErrorCode() == 200);
+
+ // delete all deployment artifacts
+ deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatArtifactDetails);
+ deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatVolArtifactDetails);
+ deleteDeploymentArtifactByTypeToResource(resourceDetails1, heatNetArtifactDetails);
+ response = ResourceRestUtils.getResource(resourceDetails1.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ listOfResDepArtTypesFromConfig = Utils.getListOfDepResArtLabels(true);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtTypesFromConfig);
+ for (String iter : listOfResDepArtTypesFromConfig) {
+ artType = iter;
+ verifyDepArtPlaceHoldersByType(artType);
+ }
+ }
+
+ @Test
+ public void addRemoveAddAgainArtifact() throws Exception {
+
+ // get MAP before upload artifact
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat");
+
+ // validate place holder exist
+ assertNotNull(artifactDefinition);
+
+ // add artifact
+ updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType());
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+
+ // remove artifact
+ RestResponse deleteArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource(
+ resourceDetails1.getUniqueId(), updateArtifactReqDetails, sdncDesignerDetails1);
+ logger.debug(
+ "addInformationalArtifactToResource response: " + deleteArtifactFromResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + deleteArtifactFromResource.getErrorCode(),
+ deleteArtifactFromResource.getErrorCode() == 200);
+
+ RestResponse getResourceResp = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+
+ artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(deleteArtifactFromResource.getResponse());
+ assertTrue(artifactDefinitionResponseJavaObject.getArtifactName().isEmpty());
+ assertTrue(artifactDefinitionResponseJavaObject.getDescription().isEmpty());
+ assertTrue(artifactDefinitionResponseJavaObject.getArtifactChecksum().isEmpty());
+ assertTrue(artifactDefinitionResponseJavaObject.getEsId().isEmpty());
+ assertTrue(artifactDefinitionResponseJavaObject.getArtifactUUID().isEmpty());
+ assertNull(artifactDefinitionResponseJavaObject.getHeatParameters());
+
+ // add artifact again with different user
+ addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+
+ assertFalse("check artifact checksum", artDef1.getArtifactChecksum().equals(artDef2.getArtifactChecksum()));
+ assertTrue("check artifact EsId", artDef1.getEsId().equals(artDef2.getEsId()));
+ assertFalse("check artifact UUID", artDef1.getArtifactUUID().equals(artDef2.getArtifactUUID()));
+ assertTrue("check UserIdCreator", artDef1.getUserIdCreator().equals(artDef2.getUserIdCreator()));
+ assertTrue("check UserIdLastUpdater", artDef1.getUserIdLastUpdater().equals(artDef2.getUserIdLastUpdater()));
+ }
+
+ @Test
+ public void addUpdateArtifactByType() throws Exception {
+
+ // get MAP before upload artifact
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat");
+
+ // validate place holder exist
+ assertNotNull(artifactDefinition);
+
+ // add artifact
+ updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType());
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1,
+ sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails2,
+ LifeCycleStatesEnum.CHECKOUT);
+
+ // update with different user artifact
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setUniqueId(artifactDefinition.getUniqueId());
+ heatArtifactDetails.setArtifactName("2.yaml");
+ heatArtifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
+
+ addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails2, resourceDetails1.getUniqueId(), "heat");
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+ verifyArtDefFields(artDef1, artDef2);
+
+ }
+
+ @Test
+ public void addUpdateDeleteArtifact() throws Exception {
+
+ // get MAP before upload artifact
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails1, sdncDesignerDetails1);
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get("heat");
+
+ // validate place holder exist
+ assertNotNull(artifactDefinition);
+
+ updateArtifactReqDetails = getUpdateArtifactDetails(ArtifactTypeEnum.HEAT.getType());
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ updateArtifactReqDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId());
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ ArtifactDefinition artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef1 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1,
+ sdncDesignerDetails1, LifeCycleStatesEnum.CHECKIN);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails1, sdncDesignerDetails2,
+ LifeCycleStatesEnum.CHECKOUT);
+
+ // update with different user artifact
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setArtifactName("2.yaml");
+
+ addInformationalArtifactToResource = ArtifactRestUtils.updateInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails2, resourceDetails1.getUniqueId(), "heat");
+ logger.debug("addInformationalArtifactToResource response: "
+ + addInformationalArtifactToResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 200);
+
+ artifactDefinitionResponseJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addInformationalArtifactToResource.getResponse());
+ ArtifactDefinition artDef2 = fillArtDefFromResponse(artifactDefinitionResponseJavaObject);
+
+ verifyArtDefFields(artDef1, artDef2);
+
+ RestResponse delteArtifactFromResource = ArtifactRestUtils.deleteInformationalArtifactFromResource(
+ resourceDetails1.getUniqueId(), heatArtifactDetails, sdncDesignerDetails2);
+ logger.debug("addInformationalArtifactToResource response: {}", delteArtifactFromResource.getResponseMessage());
+ assertTrue("response code is not 200, returned :" + delteArtifactFromResource.getErrorCode(),
+ delteArtifactFromResource.getErrorCode() == 200);
+
+ }
+
+ @Test
+ public void addHeatVolArtInvalidExtension() throws Exception {
+
+ heatVolArtifactDetails.setArtifactName("heatVol.txt");
+ RestResponse response = getResponseOnAddDeploymentArtifactByTypeToResource(resourceDetails1,
+ heatVolArtifactDetails);
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name());
+ assertEquals("Check response code after upload artifact", errorInfo.getCode(), response.getErrorCode());
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT_VOL.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables,
+ response.getResponse());
+ }
+
+ @Test
+ public void addHeatNetArtInvalidExtension() throws Exception {
+
+ heatNetArtifactDetails.setArtifactName("yaml");
+ RestResponse response = getResponseOnAddDeploymentArtifactByTypeToResource(resourceDetails1,
+ heatNetArtifactDetails);
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name());
+ assertEquals("Check response code after upload artifact", errorInfo.getCode(), response.getErrorCode());
+ List<String> variables = Arrays.asList(ArtifactTypeEnum.HEAT_NET.getType());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION.name(), variables,
+ response.getResponse());
+ }
+
+ @Test
+ public void checkServiceSecurityTemplateInformationalArtifactsCreation() throws IOException, Exception {
+
+ Either<Service, RestResponse> createServiceResponse = AtomicOperationUtils
+ .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true);
+ Map<String, ArtifactDefinition> artifacts = null;
+ ArtifactDefinition securitytemplate = null;
+ if (createServiceResponse.isLeft()) {
+ Component component = createServiceResponse.left().value();
+ artifacts = component.getArtifacts();
+ securitytemplate = artifacts.get("servicesecuritytemplate");
+ assertNotNull(securitytemplate);
+ assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName());
+ } else {
+ logger.debug("checkSecurityTemplateInformationalArtifactsCreation service creation response: "
+ + createServiceResponse.right().value().getResponseMessage());
+ }
+ }
+
+ @Test
+ public void checkResourceSecurityTemplateInformationalArtifactsCreation() throws IOException, Exception {
+
+ Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.CONTAINER_APPLICATION, ResourceCategoryEnum.APPLICATION_L4_BORDER,
+ UserRoleEnum.DESIGNER, true).left().value();
+ Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ ArtifactDefinition securitytemplate = artifacts.get("resourcesecuritytemplate");
+ assertNotNull(securitytemplate);
+ assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName());
+ }
+
+ // Benny
+ @Test
+ public void serviceSecurityTemplateInformationalArtifact() throws IOException, Exception {
+ String artifactPlaceHolder = "servicesecuritytemplate";
+ Service service = AtomicOperationUtils
+ .createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ Map<String, ArtifactDefinition> artifacts = service.getArtifacts();
+ ArtifactDefinition securitytemplate = artifacts.get(artifactPlaceHolder);
+ assertNotNull(securitytemplate);
+ assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName());
+ assertEquals("OTHER", securitytemplate.getArtifactType());
+ assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel());
+ // Get service
+ RestResponse getService = ServiceRestUtils.getService(service.getUniqueId(),
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getService.getErrorCode().intValue());
+ service = ResponseParser.parseToObjectUsingMapper(getService.getResponse(), Service.class);
+ artifacts = service.getArtifacts();
+ securitytemplate = artifacts.get(artifactPlaceHolder);
+ assertNotNull(securitytemplate);
+ assertEquals("Service Security Template", securitytemplate.getArtifactDisplayName());
+ assertEquals("OTHER", securitytemplate.getArtifactType());
+ assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel());
+ }
+
+ @Test
+ public void resourceSecurityTemplateInformationalArtifacts() throws IOException, Exception {
+ String artifactPlaceHolder = "resourcesecuritytemplate";
+ Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.CONTAINER_APPLICATION, ResourceCategoryEnum.APPLICATION_L4_BORDER,
+ UserRoleEnum.DESIGNER, true).left().value();
+ Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ ArtifactDefinition securitytemplate = artifacts.get("resourcesecuritytemplate");
+ assertNotNull(securitytemplate);
+ assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName());
+ assertEquals("OTHER", securitytemplate.getArtifactType());
+ assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel());
+ // Get resource
+ RestResponse getresource = ResourceRestUtils.getResource(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ resource.getUniqueId());
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getresource.getErrorCode().intValue());
+ resource = ResponseParser.parseToObjectUsingMapper(getresource.getResponse(), Resource.class);
+ artifacts = resource.getArtifacts();
+ securitytemplate = artifacts.get(artifactPlaceHolder);
+ assertNotNull(securitytemplate);
+ assertEquals("Resource Security Template", securitytemplate.getArtifactDisplayName());
+ assertEquals("OTHER", securitytemplate.getArtifactType());
+ assertEquals(artifactPlaceHolder, securitytemplate.getArtifactLabel());
+ }
+
+ // ================================================
+
+ @SuppressWarnings("unchecked")
+ private Map<String, Object> getMapOfDepResArtTypesObjects() throws FileNotFoundException {
+
+ return (Map<String, Object>) Utils.parseYamlConfig("deploymentResourceArtifacts");
+
+ }
+
+ private void addDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails,
+ ArtifactReqDetails artReqDetails) throws IOException, Exception {
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(artReqDetails,
+ sdncDesignerDetails1, resourceReqDetails.getUniqueId());
+ assertTrue("add" + artReqDetails.getArtifactLabel() + " artifact to resource request returned status:"
+ + response.getErrorCode(), response.getErrorCode() == 200);
+ }
+
+ private RestResponse getResponseOnAddDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails,
+ ArtifactReqDetails artReqDetails) throws IOException, Exception {
+
+ return ArtifactRestUtils.addInformationalArtifactToResource(artReqDetails, sdncDesignerDetails1,
+ resourceReqDetails.getUniqueId());
+ }
+
+ private void deleteDeploymentArtifactByTypeToResource(ResourceReqDetails resourceReqDetails,
+ ArtifactReqDetails artReqDetails) throws IOException, Exception {
+
+ RestResponse response = ArtifactRestUtils.deleteInformationalArtifactFromResource(
+ resourceReqDetails.getUniqueId(), artReqDetails, sdncDesignerDetails1);
+ assertTrue("delete" + artReqDetails.getArtifactLabel() + " artifact to resource request returned status:"
+ + response.getErrorCode(), response.getErrorCode() == 200);
+ }
+
+ private void verifyDepArtPlaceHoldersByType(String artType) {
+
+ Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
+ assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType));
+ assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType).getEsId());
+ assertNotNull("deployment artifact data is null", deploymentArtifacts.get(artType).getDescription());
+ assertTrue(
+ "deployment artifact timeout does not equal to default value " + timeOut + " expected " + timeOut
+ + ", actual - " + deploymentArtifacts.get(artType).getTimeout(),
+ deploymentArtifacts.get(artType).getTimeout() == timeOut);
+ assertTrue("deployment artifact label value ",
+ deploymentArtifacts.get(artType).getArtifactLabel().equals(artType));
+ }
+
+ private void verifyHeatParametersExistance(String artType, Boolean isNull) {
+ Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts();
+ if (isNull) {
+ assertNull("heatParameters list for type " + artType + " is not null",
+ deploymentArtifacts.get(artType).getHeatParameters());
+ } else {
+ assertNotNull("heatParameters list for type " + artType + " is null",
+ deploymentArtifacts.get(artType).getHeatParameters());
+ }
+ }
+
+ private void verifyArtDefFields(ArtifactDefinition artDef1, ArtifactDefinition artDef2) {
+
+ assertFalse("check artifact checksum", artDef1.getArtifactChecksum().equals(artDef2.getArtifactChecksum()));
+ assertFalse("check artifact EsId", artDef1.getEsId().equals(artDef2.getEsId()));
+ assertFalse("check artifact UUID", artDef1.getArtifactUUID().equals(artDef2.getArtifactUUID()));
+ assertTrue("check UserIdCreator", artDef1.getUserIdCreator().equals(artDef2.getUserIdCreator()));
+ assertFalse("check UserIdLastUpdater", artDef1.getUserIdLastUpdater().equals(artDef2.getUserIdLastUpdater()));
+
+ }
+
+ private ArtifactDefinition fillArtDefFromResponse(ArtifactDefinition artifactDefinitionResponseJavaObject) {
+ ArtifactDefinition artDef = new ArtifactDefinition();
+ artDef.setArtifactChecksum(artifactDefinitionResponseJavaObject.getArtifactChecksum());
+ artDef.setEsId(artifactDefinitionResponseJavaObject.getEsId());
+ artDef.setArtifactUUID(artifactDefinitionResponseJavaObject.getArtifactUUID());
+ artDef.setUserIdCreator(artifactDefinitionResponseJavaObject.getUserIdCreator());
+ artDef.setUserIdLastUpdater(artifactDefinitionResponseJavaObject.getUserIdLastUpdater());
+ return artDef;
+ }
+
+ private ArtifactReqDetails getUpdateArtifactDetails(String artType) throws IOException, Exception {
+ String ext = heatExtension;
+ String sourceDir = config.getResourceConfigDir();
+ String testResourcesPath = sourceDir + File.separator + folderName;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ logger.debug("listFileName: {}", listFileName.toString());
+
+ String payload = FileUtils.loadPayloadFile(listFileName, ext, true);
+ ArtifactReqDetails updateArtifactReqDetails = ElementFactory.getDefaultDeploymentArtifactForType(artType);
+ updateArtifactReqDetails.setPayload(payload);
+ updateArtifactReqDetails.setArtifactName("1.yaml");
+ return updateArtifactReqDetails;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
new file mode 100644
index 0000000000..01169630a4
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateArtResponse.java
@@ -0,0 +1,631 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.yaml.snakeyaml.Yaml;
+
+public class ValidateArtResponse extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+ protected String serviceVersion;
+
+ public ValidateArtResponse() {
+ super(name, ArtifactServletTest.class.getName());
+
+ }
+
+ protected final String pathToFile = "heatArtifactParameters";
+ protected final String heatWithValidParams = "heatWithValidParams.yaml";
+ protected final String heatWithParamsMissingDefault = "heatWithParamsMissingDefault.yaml";
+ protected final String heatWithParamsMissingDesc = "heatWithParamsMissingDesc.yaml";
+ protected final String heatWithParamsMissingType = "heatWithParamsMissingType.yaml";
+ protected final String importNoDerivedFromFile = "myComputeDerivedFromNotExists.yml";
+ protected final String decodedPayload = "decodedPayload";
+ protected final String encodedPayload = "encodedPayload";
+
+ protected Resource resourceDetailsObj;
+ protected ResourceReqDetails resourceDetails;
+ protected User sdncDesignerDetails;
+
+ @BeforeMethod
+ public void init() throws Exception {
+
+ resourceDetailsObj = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetails = new ResourceReqDetails(resourceDetailsObj);
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ }
+
+ @Test
+ public void compareParamtersVsYaml() throws Exception {
+
+ // select file to upload
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithValidParams);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ protected void assertnull(String string, boolean equals) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Map<String, String> extractSingleParameter(Map<String, String> curr) {
+ Map<String, String> innerMap = new HashMap<String, String>();
+ if (curr.containsKey("description")) {
+ innerMap.put("description", curr.get("description"));
+ }
+
+ if (curr.containsKey("defaultValue")) {
+ innerMap.put("default", curr.get("defaultValue"));
+ } else {
+ // System.out.println("kuku");
+ }
+ innerMap.put("type", curr.get("type"));
+ return innerMap;
+ }
+
+ public Map<String, Map> createMapFromYaml(String payload) {
+ ArrayList<String> parametersList = new ArrayList<String>();
+
+ Yaml yaml = new Yaml();
+
+ Map<String, Map> result = (Map<String, Map>) yaml.load(payload);
+ Map<String, Map> paramters = (Map<String, Map>) result.get("parameters");
+
+ for (Map.Entry<String, Map> entry : paramters.entrySet()) {
+ Map<String, String> origInnerMap = (Map<String, String>) entry.getValue();
+
+ if (origInnerMap.containsKey("label")) {
+ origInnerMap.remove("label");
+ paramters.remove(entry);
+ paramters.put(entry.getKey(), origInnerMap);
+ }
+ }
+ return paramters;
+ }
+
+ public Map<String, Map<String, String>> jsonToMap(RestResponse addInformationalArtifactToResource,
+ String section2extract, String createKeyMapBy) {
+ Map<String, Object> JsonToMap = new HashMap<String, Object>();
+ JsonToMap = (Map<String, Object>) ResponseParser.parseToObject(addInformationalArtifactToResource.getResponse(),
+ JsonToMap.getClass());
+
+ List<Map<String, String>> listOfParamters = (List<Map<String, String>>) JsonToMap.get(section2extract);
+ Map<String, Map<String, String>> mapOfActualParameters = new HashMap<String, Map<String, String>>();
+
+ for (Map<String, String> curr : listOfParamters) {
+ Map<String, String> innerMap = extractSingleParameter(curr);
+
+ mapOfActualParameters.put(curr.get(createKeyMapBy), innerMap);
+ }
+ return mapOfActualParameters;
+ }
+
+ public Map<String, String> selectFileToUpload(String pathToFile, String fileName) throws IOException {
+ String sourceDir = config.getResourceConfigDir();
+ String testResourcesPath = sourceDir + File.separator + pathToFile;
+ String file = fileName;
+ Map<String, String> filePayload = new HashMap<String, String>();
+ String payload = Decoder.readFileToString(testResourcesPath + File.separator + file);
+ filePayload.put(decodedPayload, payload);
+ filePayload.put(encodedPayload, Decoder.encode(payload.getBytes()));
+
+ return filePayload;
+ }
+
+ @Test
+ public void missingDescParam() throws Exception {
+
+ // select file to upload
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDesc);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void missingDefaultParam() throws Exception {
+
+ // select file to upload
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDefault);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void missingTypeParam() throws Exception {
+
+ // select file to upload
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingType);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // System.out.println(addInformationalArtifactToResource);
+ AssertJUnit.assertTrue(
+ "response code is not 400, returned :" + addInformationalArtifactToResource.getErrorCode(),
+ addInformationalArtifactToResource.getErrorCode() == 400);
+
+ }
+
+ @Test
+ public void updateValueParam() throws Exception {
+
+ String updateValueParam = "changed";
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithValidParams);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+ // System.out.println(resourceGetResponse.getResponse().toString());
+ String atifactUniqueId = ResponseParser
+ .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId");
+
+ ArtifactReqDetails artifacJavaObject = ResponseParser
+ .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters2 = artifacJavaObject.getHeatParameters();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters2) {
+ heatParameterDefinition.setCurrentValue(updateValueParam);
+ }
+ artifacJavaObject.setHeatParameters(heatParameters2);
+ artifacJavaObject.setPayloadData(null);
+
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource(
+ artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // verify change in update response
+
+ ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // verify change in getResource
+
+ resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void updateValueParamMissingDefault() throws Exception {
+
+ String updateValueParam = "changed";
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithParamsMissingDefault);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+ // System.out.println(resourceGetResponse.getResponse().toString());
+ String atifactUniqueId = ResponseParser
+ .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId");
+
+ ArtifactReqDetails artifacJavaObject = ResponseParser
+ .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters2 = artifacJavaObject.getHeatParameters();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters2) {
+ heatParameterDefinition.setCurrentValue(updateValueParam);
+ }
+ artifacJavaObject.setHeatParameters(heatParameters2);
+ artifacJavaObject.setPayloadData(null);
+
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource(
+ artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // verify change in update response
+
+ ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // verify change in getResource
+
+ resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void updateValueParamNull() throws Exception {
+
+ String updateValueParam = null;
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithValidParams);
+
+ // upload HEAT file and save JSON response
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+ // System.out.println(resourceGetResponse.getResponse().toString());
+ String atifactUniqueId = ResponseParser
+ .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId");
+
+ ArtifactReqDetails artifacJavaObject = ResponseParser
+ .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters2 = artifacJavaObject.getHeatParameters();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters2) {
+ heatParameterDefinition.setCurrentValue(updateValueParam);
+ }
+ artifacJavaObject.setHeatParameters(heatParameters2);
+ artifacJavaObject.setPayloadData(null);
+
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource(
+ artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // verify change in update response
+ ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ // String verify = updateValueParam;
+ if (heatParameterDefinition.getDefaultValue() != null) {
+ AssertJUnit.assertTrue(
+ heatParameterDefinition.getDefaultValue().equals(heatParameterDefinition.getCurrentValue()));
+ } else {
+ AssertJUnit.assertNull("verification failed", heatParameterDefinition.getCurrentValue());
+ }
+ }
+
+ // verify change in getResource
+ resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ // String verify = updateValueParam;
+ if (heatParameterDefinition.getDefaultValue() != null) {
+ AssertJUnit.assertTrue(
+ heatParameterDefinition.getDefaultValue().equals(heatParameterDefinition.getCurrentValue()));
+ } else {
+ AssertJUnit.assertNull("verification failed", heatParameterDefinition.getCurrentValue());
+ }
+ }
+
+ // create MAP from received JSON
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void updateValueParamEmpty() throws Exception {
+
+ String updateValueParam = "";
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithValidParams);
+
+ // upload HEAT file and save JSON response
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+ // System.out.println(resourceGetResponse.getResponse().toString());
+ String atifactUniqueId = ResponseParser
+ .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId");
+
+ ArtifactReqDetails artifacJavaObject = ResponseParser
+ .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters2 = artifacJavaObject.getHeatParameters();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters2) {
+ heatParameterDefinition.setCurrentValue(updateValueParam);
+ }
+ artifacJavaObject.setHeatParameters(heatParameters2);
+ artifacJavaObject.setPayloadData(null);
+
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource(
+ artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ // verify change in update response
+
+ ArtifactDefinition ArtifactDefinitionRespJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(updateInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters = ArtifactDefinitionRespJavaObject.getHeatParameters();
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // verify change in getResource
+
+ resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ deploymentArtifacts.get(heatArtifactDetails.getArtifactName());
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ String verify = updateValueParam;
+ AssertJUnit.assertTrue("verification failed", verify.equals(heatParameterDefinition.getCurrentValue()));
+ }
+
+ // create MAP from received JSON
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+ @Test
+ public void onlyValueParamPermited() throws Exception {
+
+ Map<String, String> filePayload = selectFileToUpload(pathToFile, heatWithValidParams);
+
+ // upload HEAT file and save JSON response
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatArtifactDetails.setPayload(filePayload.get(encodedPayload));
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+ // System.out.println(resourceGetResponse.getResponse().toString());
+ String atifactUniqueId = ResponseParser
+ .getValueFromJsonResponse(addInformationalArtifactToResource.getResponse(), "uniqueId");
+
+ ArtifactReqDetails artifacJavaObject = ResponseParser
+ .convertArtifactReqDetailsToJavaObject(addInformationalArtifactToResource.getResponse());
+ List<HeatParameterDefinition> heatParameters2 = artifacJavaObject.getHeatParameters();
+
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters2) {
+ heatParameterDefinition.setDefaultValue("changed");
+ heatParameterDefinition.setName("changed");
+ heatParameterDefinition.setDescription("changed");
+ heatParameterDefinition.setType("changed");
+ heatParameterDefinition.setCurrentValue("changed");
+ }
+ artifacJavaObject.setHeatParameters(heatParameters2);
+ artifacJavaObject.setPayloadData(null);
+
+ RestResponse updateInformationalArtifactToResource = ArtifactRestUtils.updateDeploymentArtifactToResource(
+ artifacJavaObject, sdncDesignerDetails, resourceDetails.getUniqueId());
+
+ resourceGetResponse = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails);
+
+ // create MAP from received JSON
+
+ String section2extract = "heatParameters";
+ String createKeyMapBy = "name";
+ Map<String, Map<String, String>> mapOfActualParameters = jsonToMap(addInformationalArtifactToResource,
+ section2extract, createKeyMapBy);
+
+ // Prepare map to validate JS
+
+ Map<String, Map> paramters = createMapFromYaml(filePayload.get(decodedPayload));
+
+ // compare MAPs
+
+ ResourceValidationUtils.compareElements(mapOfActualParameters, paramters);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java
new file mode 100644
index 0000000000..c22dcb96d4
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsFromUI.java
@@ -0,0 +1,444 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+//
+//import java.util.Arrays;
+//import java.util.List;
+//
+//import org.junit.Rule;
+//import org.junit.rules.TestName;
+//import org.testng.AssertJUnit;
+//import org.testng.annotations.Test;
+//
+//import org.openecomp.sdc.be.dao.api.ActionStatus;
+//import org.openecomp.sdc.be.model.ArtifactDefinition;
+//import org.openecomp.sdc.be.model.ComponentInstance;
+//import org.openecomp.sdc.be.model.HeatParameterDefinition;
+//import org.openecomp.sdc.be.model.Resource;
+//import org.openecomp.sdc.be.model.Service;
+//import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+//import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+//import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
+//import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+//import org.openecomp.sdc.ci.tests.preRequisites.HeatEnvBaseTest;
+//import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+//import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+//import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+//import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+//import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+//import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+//
+//public class ValidateHeatArtFieldsFromUI extends HeatEnvBaseTest {
+public class ValidateHeatArtFieldsFromUI {
+ //
+ //
+ //
+ // private static final String heatExtension = "yaml";
+ // private static final String yangXmlExtension = "xml";
+ // private static final String muranoPkgExtension = "zip";
+ // private final String folderName= "yamlFieldsValidation";
+ //
+ //
+ // private final String uuidString =
+ // RespJsonKeysEnum.UUID.getRespJsonKeyName().toString();
+ //
+ // public ValidateHeatArtFieldsFromUI() {
+ // super(name, ValidateHeatArtFieldsFromUI.class.getName());
+ // }
+ //
+ // @Rule
+ // public static TestName name = new TestName();
+ //
+ //
+ // @Test
+ // public void heatEnvValidateHeatArtFiledTypes_UpdateFailed() throws
+ // Exception {
+ //
+ // //get relevant service
+ // RestResponse serviceGetResponse =
+ // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
+ // Service service =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ // List<ComponentInstance> resourceInstances =
+ // service.getComponentInstances();
+ // ComponentInstance resourceInstance = resourceInstances.get(0);
+ //
+ //
+ // String defaultParam = null;
+ //
+ // //update heatEnv with invalid value in number field
+ //
+ // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromService();
+ // String currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "home_number", "Tel Aviv");
+ // ArtifactReqDetails artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // RestResponse res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
+ // sdncDesignerDetails, resourceInstance.getUniqueId(),
+ // service.getUniqueId());
+ //
+ // // validate negative response
+ // List<String> variables = Arrays.asList("HEAT_ENV", "number",
+ // "home_number");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // String currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "home_number");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "private_building", "Tel Aviv");
+ // artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
+ // sdncDesignerDetails, resourceInstance.getUniqueId(),
+ // service.getUniqueId());
+ //
+ // // validate negative response
+ // variables = Arrays.asList("HEAT_ENV", "boolean", "private_building");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "private_building");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ //
+ //
+ //
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "city_name", "\uC2B5");
+ // artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
+ // sdncDesignerDetails, resourceInstance.getUniqueId(),
+ // service.getUniqueId());
+ // // validate negative response
+ // variables = Arrays.asList("HEAT_ENV", "string", "city_name");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "city_name");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ // }
+ //
+ // @Test
+ // public void heatValidateHeatArtFiledTypes_UpdateFailed() throws Exception
+ // {
+ //
+ //
+ // RestResponse checkOutResponse =
+ // LifecycleRestUtils.changeResourceState(resourceSC, sdncDesignerDetails,
+ // LifeCycleStatesEnum.CHECKOUT);
+ // AssertJUnit.assertTrue("response code is not 200, returned: " +
+ // checkOutResponse.getErrorCode(),checkOutResponse.getErrorCode() == 200);
+ // //get relevant service
+ // RestResponse resourceGetResponse =
+ // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
+ // Resource resource =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ //
+ // //update heatEnv with invalid value in number field
+ //
+ // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromResource();
+ // String currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "home_number", "Tel Aviv");
+ // ArtifactReqDetails artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // RestResponse res =
+ // ArtifactRestUtils.updateInformationalArtifactToResource(artReq,
+ // sdncDesignerDetails, resource.getUniqueId());
+ // // validate negative response
+ // List<String> variables = Arrays.asList("HEAT", "number", "home_number");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ // String currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "home_number");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ //
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "private_building", "Tel Aviv");
+ // artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // res = ArtifactRestUtils.updateDeploymentArtifactToResource(artReq,
+ // sdncDesignerDetails, resource.getUniqueId());
+ // // validate negative response
+ // variables = Arrays.asList("HEAT", "boolean", "private_building");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ //
+ // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "private_building");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ //
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ // currentHeatEnvParamBeforeUpdate = replaceHeatParamsValue(artifact,
+ // "city_name", "\uC2B5");
+ //
+ // artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // res = ArtifactRestUtils.updateDeploymentArtifactToResource(artReq,
+ // sdncDesignerDetails, resource.getUniqueId());
+ // // validate negative response
+ // variables = Arrays.asList("HEAT", "string", "city_name");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ // variables, res.getResponse());
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ // currentHeatEnvParamAfterUpdate = getHeatParamsValue(artifact,
+ // "city_name");
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBeforeUpdate,
+ // currentHeatEnvParamBeforeUpdate.equals(currentHeatEnvParamAfterUpdate));
+ //
+ // }
+ //
+ // @Test
+ // public void heatEnvValidateHeatArtFiledTypes_boolNormalization_suc()
+ // throws Exception {
+ //
+ // //get relevant service
+ // RestResponse serviceGetResponse =
+ // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
+ // Service service =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ // List<ComponentInstance> resourceInstances =
+ // service.getComponentInstances();
+ // ComponentInstance resourceInstance = resourceInstances.get(0);
+ //
+ // String defaultParam = null;
+ // String currentHeatEnvParamBefore = null;
+ // String currentHeatEnvParamAfter = null;
+ //
+ //
+ // List<String> listOfBoolValuesToValidate = Arrays.asList("T", "on", "1",
+ // "yes", "y");
+ //
+ // for (String element : listOfBoolValuesToValidate) {
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromService();
+ // List<HeatParameterDefinition> heatParameters =
+ // artifact.getHeatParameters();
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals("private_building")){
+ // defaultParam = param.getDefaultValue();
+ // currentHeatEnvParamBefore = param.getCurrentValue();
+ // param.setCurrentValue(element);
+ // }
+ // }
+ // artifact.setHeatParameters(heatParameters);
+ // ArtifactReqDetails artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // RestResponse res = ArtifactRestUtils.updateDeploymentArtifactToRI(artReq,
+ // sdncDesignerDetails, resourceInstance.getUniqueId(),
+ // service.getUniqueId());
+ // AssertJUnit.assertTrue("response code is not 200, returned: " +
+ // res.getErrorCode(), res.getErrorCode() == 200);
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromService();
+ // heatParameters = artifact.getHeatParameters();
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals("private_building")){
+ // currentHeatEnvParamAfter = param.getCurrentValue();
+ // }
+ // }
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBefore, currentHeatEnvParamAfter.equals("true"));
+ //
+ // }
+ //
+ // }
+ //
+ //
+ // @Test
+ // public void heatValidateHeatArtFiledTypes_boolNormalization_suc() throws
+ // Exception {
+ //
+ // RestResponse checkOutResponse =
+ // LifecycleRestUtils.changeResourceState(resourceSC, sdncDesignerDetails,
+ // LifeCycleStatesEnum.CHECKOUT);
+ // AssertJUnit.assertTrue("response code is not 200, returned: " +
+ // checkOutResponse.getErrorCode(),checkOutResponse.getErrorCode() == 200);
+ // //get relevant service
+ // RestResponse resourceGetResponse =
+ // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
+ // Resource resource =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ //
+ //
+ // String defaultParam = null;
+ // String currentHeatEnvParamBefore = null;
+ // String currentHeatEnvParamAfter = null;
+ //
+ //
+ // List<String> listOfBoolValuesToValidate = Arrays.asList("T", "on", "1",
+ // "yes", "y");
+ //
+ // for (String element : listOfBoolValuesToValidate) {
+ //
+ // //update heatEnv with invalid value in boolean field
+ //
+ // ArtifactDefinition artifact = getCurrentArtifactDefinitionFromResource();
+ // List<HeatParameterDefinition> heatParameters =
+ // artifact.getHeatParameters();
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals("private_building")){
+ // defaultParam = param.getDefaultValue();
+ // currentHeatEnvParamBefore = param.getCurrentValue();
+ // param.setCurrentValue(element);
+ // }
+ // }
+ // artifact.setHeatParameters(heatParameters);
+ // ArtifactReqDetails artReq =
+ // ResponseParser.convertArtifactDefinitionToArtifactReqDetailsObject(artifact);
+ // RestResponse res =
+ // ArtifactRestUtils.updateInformationalArtifactToResource(artReq,
+ // sdncDesignerDetails, resource.getUniqueId());
+ // AssertJUnit.assertTrue("response code is not 200, returned: " +
+ // res.getErrorCode(), res.getErrorCode() == 200);
+ //
+ // //validate current value not affected
+ //
+ // artifact = getCurrentArtifactDefinitionFromResource();
+ // heatParameters = artifact.getHeatParameters();
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals("private_building")){
+ // currentHeatEnvParamAfter = param.getCurrentValue();
+ // }
+ // }
+ // AssertJUnit.assertTrue("HeatEnvParam was not updated: " +
+ // currentHeatEnvParamBefore, currentHeatEnvParamAfter.equals("true"));
+ //
+ // }
+ //
+ // }
+ //
+ //
+ // private ArtifactDefinition getCurrentArtifactDefinitionFromResource()
+ // throws Exception {
+ //
+ // RestResponse resourceGetResponse =
+ // ResourceRestUtils.getResource(resourceSC, sdncDesignerDetails);
+ // Resource resource =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ //
+ // ArtifactDefinition artifactDefinition =
+ // resource.getDeploymentArtifacts().get("heat");
+ //
+ //
+ // return artifactDefinition;
+ //
+ // }
+ //
+ //
+ // private ArtifactDefinition getCurrentArtifactDefinitionFromService()
+ // throws Exception {
+ //
+ // RestResponse serviceGetResponse =
+ // ServiceRestUtils.getService(serviceDetails2, sdncDesignerDetails);
+ // Service service =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ // ArtifactDefinition artifactDefinition = new ArtifactDefinition();
+ // artifactDefinition =
+ // service.getComponentInstances().get(0).getDeploymentArtifacts().get("heatenv");
+ //
+ //
+ // return artifactDefinition;
+ //
+ // }
+ //
+ // private String replaceHeatParamsValue(ArtifactDefinition artifact, String
+ // paramName, String paramValue) {
+ // String defaultParam;
+ // String currentHeatEnvParam = null;
+ // List<HeatParameterDefinition> heatParameters =
+ // artifact.getHeatParameters();
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals(paramName)){
+ // defaultParam = param.getDefaultValue();
+ // currentHeatEnvParam = param.getCurrentValue();
+ // param.setCurrentValue(paramValue);
+ // }
+ // }
+ // artifact.setHeatParameters(heatParameters);
+ // return currentHeatEnvParam;
+ // }
+ //
+ // private String getHeatParamsValue(ArtifactDefinition artifact,
+ // String paramName) {
+ // List<HeatParameterDefinition> heatParameters =
+ // artifact.getHeatParameters();
+ // String currentHeatEnvParamValue = null;
+ // for(HeatParameterDefinition param : heatParameters){
+ // if (param.getName().equals(paramName)){
+ // currentHeatEnvParamValue = param.getCurrentValue();
+ // }
+ // }
+ // return currentHeatEnvParamValue;
+ // }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java
new file mode 100644
index 0000000000..09cda0b73c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ValidateHeatArtFieldsTypes.java
@@ -0,0 +1,176 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.artifacts;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.HeatParameterDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ArtifactValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.Test;
+
+public class ValidateHeatArtFieldsTypes extends ComponentBaseTest {
+
+ protected User sdncDesignerDetails;
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+
+ private static final String heatExtension = "yaml";
+ private static final String yangXmlExtension = "xml";
+ private static final String muranoPkgExtension = "zip";
+ private final String folderName = "yamlFieldsValidation";
+
+ private final String uuidString = RespJsonKeysEnum.UUID.getRespJsonKeyName().toString();
+
+ public ValidateHeatArtFieldsTypes() {
+ super(name, ValidateHeatArtFieldsTypes.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ @Test
+ public void validateHeatArtFiledTypes() throws Exception {
+
+ // get relevant resource and service
+
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ resourceDetails = ElementFactory.getDefaultResource();
+
+ RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails);
+ AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 201);
+
+ // add artifact to resource1
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ List<String> listOfArtifactFromFolder = ArtifactValidationUtils.getListOfArtifactFromFolder(folderName);
+ for (int i = 0; i < listOfArtifactFromFolder.size(); i++) {
+ heatArtifactDetails = ArtifactValidationUtils.replaceDefaultArtWithArtFromList(heatArtifactDetails,
+ heatExtension, folderName, i);
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails,
+ resourceDetails.getUniqueId());
+
+ if (heatArtifactDetails.getArtifactName().contains("bool")) {
+ if (heatArtifactDetails.getArtifactName().contains("negative")) {
+ // validate negative response
+ List<String> variables = Arrays.asList("HEAT", "boolean", "city_name");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ variables, response.getResponse());
+ }
+ if (heatArtifactDetails.getArtifactName().contains("positive")) {
+ AssertJUnit.assertTrue(
+ "add HEAT artifact to resource request returned status:" + response.getErrorCode()
+ + " fileName: " + heatArtifactDetails.getArtifactName(),
+ response.getErrorCode() == 200);
+ ArtifactDefinition artifactDefinitionJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(response.getResponse());
+ List<HeatParameterDefinition> heatParameters = artifactDefinitionJavaObject.getHeatParameters();
+ String currentValue = null;
+ for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
+ if (heatParameterDefinition.getName().equals("city_name")) {
+ currentValue = heatParameterDefinition.getCurrentValue();
+ }
+ }
+ if (heatArtifactDetails.getArtifactName().contains("true")) {
+ AssertJUnit.assertTrue(currentValue.equals("true"));
+ }
+ if (heatArtifactDetails.getArtifactName().contains("false")) {
+ AssertJUnit.assertTrue(currentValue.equals("false"));
+ }
+ RestResponse deleteInformationalArtifactFromResource = ArtifactRestUtils
+ .deleteInformationalArtifactFromResource(resourceDetails.getUniqueId(), heatArtifactDetails,
+ sdncDesignerDetails);
+ AssertJUnit.assertTrue(
+ "delete HEAT artifact from resource request returned status:"
+ + deleteInformationalArtifactFromResource.getErrorCode(),
+ deleteInformationalArtifactFromResource.getErrorCode() == 200);
+ }
+
+ } else if (heatArtifactDetails.getArtifactName().contains("number")) {
+ if (heatArtifactDetails.getArtifactName().contains("negative")) {
+ // validate negative response
+ List<String> variables = Arrays.asList("HEAT", "number", "city_name");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ variables, response.getResponse());
+ }
+ if (heatArtifactDetails.getArtifactName().contains("positive")) {
+ AssertJUnit.assertTrue(
+ "add HEAT artifact to resource request returned status:" + response.getErrorCode()
+ + " fileName: " + heatArtifactDetails.getArtifactName(),
+ response.getErrorCode() == 200);
+ }
+
+ } else if (heatArtifactDetails.getArtifactName().contains("string")) {
+ if (heatArtifactDetails.getArtifactName().contains("negative")) {
+ // validate negative response
+ List<String> variables = Arrays.asList("HEAT", "string", "city_name");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_VALUE.name(),
+ variables, response.getResponse());
+ }
+ if (heatArtifactDetails.getArtifactName().contains("positive")) {
+ AssertJUnit.assertTrue(
+ "add HEAT artifact to resource request returned status:" + response.getErrorCode()
+ + " fileName: " + heatArtifactDetails.getArtifactName(),
+ response.getErrorCode() == 200);
+ }
+
+ }
+
+ else if (heatArtifactDetails.getArtifactName().contains("unsupported")) {
+
+ // validate negative response
+ List<String> variables = Arrays.asList("HEAT", "number123");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_HEAT_PARAMETER_TYPE.name(),
+ variables, response.getResponse());
+
+ }
+
+ else {
+ AssertJUnit.assertTrue(
+ "add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ }
+ }
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
new file mode 100644
index 0000000000..58e27177d1
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/attribute/ComponentInstanceAttributeTest.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.attribute;
+
+import static org.junit.Assert.assertEquals;
+import static org.openecomp.sdc.common.datastructure.FunctionalInterfaces.swallowException;
+
+import java.io.File;
+import java.util.function.Function;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class ComponentInstanceAttributeTest extends ComponentBaseTest {
+
+ public static Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ComponentInstanceAttributeTest() {
+ super(name, ComponentInstanceAttributeTest.class.getName());
+ }
+
+ @Test
+ public void testUpdateAttributeOnResourceInstance() {
+ // Prepare VF with vfc instance with Attributes
+ String testResourcesPath = config.getResourceConfigDir() + File.separator + "importToscaResourceByCreateUrl";
+ final Resource vfcWithAttributes = AtomicOperationUtils.importResource(testResourcesPath, "CPWithAttributes.yml").left().value();
+ swallowException(() -> AtomicOperationUtils.changeComponentState(vfcWithAttributes, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, false));
+ Resource vf = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, false).left().value();
+ ComponentInstance vfcInstance = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfcWithAttributes, vf).left().value();
+
+ // util method to get the specific attribute from the vf
+ Function<Resource, ComponentInstanceAttribute> attributeGetter = resourceVf -> resourceVf.getComponentInstancesAttributes().values().iterator().next().stream().filter(att -> att.getName().equals("private_address")).findAny().get();
+ // update attribute on vfc instance
+ final Resource vfWithInsatncePreUpdate = swallowException(() -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ ComponentInstanceAttribute attributeOfRI = attributeGetter.apply(vfWithInsatncePreUpdate);
+ final String newAttValue = "NewValue";
+ attributeOfRI.setValue(newAttValue);
+ String body = gson.toJson(attributeOfRI);
+ String url = String.format(Urls.UPDATE_ATTRIBUTE_ON_RESOURCE_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(ComponentTypeEnum.RESOURCE), vf.getUniqueId(), vfcInstance.getUniqueId());
+ swallowException(() -> BaseRestUtils.sendPost(url, body, UserRoleEnum.DESIGNER.getUserId(), BaseRestUtils.acceptHeaderData));
+ // Retrieve updated vf and verify attribute was updated
+ final Resource vfWithInsatncePostUpdate = swallowException(() -> (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER));
+ ComponentInstanceAttribute updatedAttribute = attributeGetter.apply(vfWithInsatncePostUpdate);
+ assertEquals(updatedAttribute.getValue(), newAttValue);
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
new file mode 100644
index 0000000000..d9df79350b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CatalogDataApiTest.java
@@ -0,0 +1,234 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class CatalogDataApiTest extends ComponentBaseTest {
+
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+ @Rule
+ public static TestName name = new TestName();
+ protected User user;
+ protected RestResponse res1;
+ protected RestResponse res2;
+ protected RestResponse svc1;
+ protected ResourceReqDetails resourceDetails1;
+ protected ResourceReqDetails resourceDetails2;
+ protected ServiceReqDetails svcDetails1;
+
+ public CatalogDataApiTest() {
+ super(name, CatalogDataApiTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+ user = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ resourceDetails1 = buildResourceDetails(user, "TestResource1");
+ resourceDetails2 = buildResourceDetails(user, "TestResource2");
+ svcDetails1 = buildServiceDetails("TestService1");
+
+ res1 = createResource(user, resourceDetails1);
+ AssertJUnit.assertEquals("create resorce failed", 201, res1.getErrorCode().intValue());
+ resourceDetails1.setUniqueId(ResponseParser.getUniqueIdFromResponse(res1));
+ resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res1));
+
+ res2 = createResource(user, resourceDetails2);
+ AssertJUnit.assertEquals("create resorce failed", 201, res2.getErrorCode().intValue());
+ resourceDetails2.setUniqueId(ResponseParser.getUniqueIdFromResponse(res2));
+ resourceDetails2.setVersion(ResponseParser.getVersionFromResponse(res2));
+
+ svc1 = createService(user, svcDetails1);
+ AssertJUnit.assertEquals("create resorce failed", 201, svc1.getErrorCode().intValue());
+ svcDetails1.setUniqueId(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getUniqueId());
+ svcDetails1.setVersion(ResponseParser.convertServiceResponseToJavaObject(svc1.getResponse()).getVersion());
+ }
+
+ @AfterMethod
+ public void tearDown() throws Exception {
+ deleteResource(resourceDetails1.getUniqueId(), user.getUserId());
+ deleteResource(resourceDetails2.getUniqueId(), user.getUserId());
+ deleteService(svcDetails1.getUniqueId(), user);
+ }
+
+ // Keep 1
+ @Test
+ public void getCatalogData() throws Exception {
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails1, user, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("check in operation failed", 200, checkInResponse.getErrorCode().intValue());
+
+ RestResponse res = CatalogRestUtils.getCatalog(user.getUserId());
+ String json = res.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+ JSONArray services = (JSONArray) jsonResp.get("services");
+
+ // Verify all the expected resources received.
+ AssertJUnit.assertTrue("check resource1 is in response",
+ isComponentInArray(resourceDetails1.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check resource2 is in response",
+ isComponentInArray(resourceDetails2.getUniqueId(), resources));
+ AssertJUnit.assertTrue("check service1 is in response",
+ isComponentInArray(svcDetails1.getUniqueId(), services));
+
+ }
+
+ protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception {
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId);
+
+ }
+
+ protected RestResponse createResource(User user, ResourceReqDetails resourceDetails) throws Exception {
+ deleteResource(resourceDetails.getName(), user.getUserId());
+ return ResourceRestUtils.createResource(resourceDetails, user);
+ }
+
+ protected ResourceReqDetails buildResourceDetails(User user, String resourceName) {
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.0";
+ String contactId = user.getUserId();
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(),
+ ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory());
+ return resourceDetails;
+ }
+
+ protected boolean isComponentInArray(String id, JSONArray component) {
+ for (int i = 0; i < component.size(); i++) {
+ JSONObject jobject = (JSONObject) component.get(i);
+ if (jobject.get("uniqueId").toString().equals(id.toLowerCase())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected RestResponse createService(User user, ServiceReqDetails svcDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = getHeadersMap(user);
+
+ Gson gson = new Gson();
+ String body = gson.toJson(svcDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
+ RestResponse res = http.httpSendPost(url, body, headersMap);
+ // System.out.println("Create service was finished with response:
+ // "+res.getErrorCode());
+ return res;
+ }
+
+ protected Map<String, String> getHeadersMap(User user) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+ return headersMap;
+ }
+
+ protected ServiceReqDetails buildServiceDetails(String serviceName) {
+ String description = "description";
+ ArrayList<String> serviceTags = new ArrayList<String>();
+ serviceTags.add("tag1");
+ serviceTags.add(serviceName);
+ String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ String vendorName = "Oracle";
+ String vendorRelease = "0.1";
+ String contactId = "al1976";
+ String icon = "myIcon";
+
+ ServiceReqDetails svcdetails = new ServiceReqDetails(serviceName, category, serviceTags, description,
+ contactId, icon);
+ return svcdetails;
+ }
+
+ public RestResponse deleteService(String serviceId, User user) throws Exception {
+ HttpRequest httpRequest = new HttpRequest();
+ String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ serviceId);
+
+ Map<String, String> headersMap = getHeadersMap(user);
+ RestResponse res = httpRequest.httpSendDelete(url, headersMap);
+ // System.out.println("Delete service was finished with response:
+ // "+res.getErrorCode());
+ return res;
+ }
+
+ public class NewObject {
+ private String _name;
+
+ public String getName() {
+ return _name;
+ }
+
+ public void setName(String name) {
+ this._name = name;
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java
new file mode 100644
index 0000000000..d68f3f5582
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesBaseTest.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+
+public abstract class CategoriesBaseTest extends ComponentBaseTest {
+
+ public CategoriesBaseTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ protected static final String AUDIT_SERVICE_TYPE = "Service";
+ protected static final String AUDIT_RESOURCE_TYPE = "Resource";
+ protected static final String AUDIT_PRODUCT_TYPE = "Product";
+ protected static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy";
+ protected static User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected static User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected static User sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected static User sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ protected static User sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ protected static User sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ protected static User sdncProductManagerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ protected static User sdncProductStrategistUserDetails = ElementFactory
+ .getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java
new file mode 100644
index 0000000000..a3ee121611
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/CategoriesTests.java
@@ -0,0 +1,2289 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.lang3.text.WordUtils;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.json.JSONArray;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class CategoriesTests extends CategoriesBaseTest {
+
+ private static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy";
+ protected static final String ADD_CATEGORY = "AddCategory";
+ protected static final String DELETE_CATEGORY = "DeleteCategory";
+
+ public CategoriesTests() {
+ super(name, CategoriesTests.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+ private CategoryDefinition categoryDefinition;
+ private List<CategoryDefinition> categoryList;
+ private List<SubCategoryDefinition> subCategoryList;
+ private Map<String, List<String>> subCategoriesToDeleteMap;
+
+ @BeforeMethod
+ public void init() throws Exception {
+ subCategoriesToDeleteMap = new HashMap<String, List<String>>();
+ DbUtils.deleteFromEsDbByPattern("_all");
+
+ categoryDefinition = new CategoryDefinition();
+ categoryDefinition.setName("Abcd");
+ categoryList = defineCategories();
+ subCategoryList = defineSubCategories(categoryList.size());
+ }
+
+ // pass
+ @Test
+ public void createServiceCategorySuccessFlow() throws Exception {
+ // Add New category
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ // get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); // also
+ // set
+ // catalog
+ // uniqeId
+
+ }
+
+ // pass
+ @Test
+ public void createResourceCategorySuccessFlow() throws Exception {
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get Category
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ // pass
+ @Test
+ public void createProductCategorySuccessFlow() throws Exception {
+ // Add Category by Product-strategist
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+
+ // Get Category
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void CategoryNameValidation_FirstWordStartWithAlphaNumeric_01() throws Exception { // category
+ // for
+ // service
+ categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category14AadE &-+.'#=:@_");
+ categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_FirstWordStartWithAlphaNumeric_02() throws Exception { // category
+ // for
+ // resource
+ categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category14AadE &-+.'#=:@_");
+ categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_FirstWordStartWithAlphaNumeric_03() throws Exception { // category
+ // for
+ // resource
+ categoryDefinition.setName("Category14AadE &&&---+++.'''###=:@@@____");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category14AadE &-+.'#=:@_");
+ categoryDefinition.setNormalizedName("category14aade &-+.'#=:@_");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ // pass
+ @Test
+ public void createServiceCategoryByNonAdminUser() throws Exception {
+ // Add New category
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncProductStrategistUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION,
+ createCategotyRest.getErrorCode().intValue());
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_SERVICE_TYPE);
+ }
+
+ // pass
+ @Test
+ public void createResourceCategoryByNonAdminUser() throws Exception {
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncProductStrategistUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION,
+ createCategotyRest.getErrorCode().intValue());
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE);
+ }
+
+ // pass
+ @Test
+ public void createProductCategoryByNonProductStrategistUser() throws Exception {
+ // Add New product category not by Product-Strategist
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION,
+ createCategotyRest.getErrorCode().intValue());
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.RESTRICTED_OPERATION, STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE);
+
+ }
+
+ // pass
+ @Test
+ public void addCategoryByNonExistingUser() throws Exception {
+ User sdncAdminUserDetailsNonExisting = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncAdminUserDetailsNonExisting.setUserId("bt555h");
+ // Add New category
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncAdminUserDetailsNonExisting, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_RESTRICTED_OPERATION,
+ createCategotyRest.getErrorCode().intValue());
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("(" + sdncAdminUserDetailsNonExisting.getUserId() + ")");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName("");
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_RESTRICTED_OPERATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_01() throws Exception {
+ categoryDefinition.setName("1234AbcdE&");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde&"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_02() throws Exception {
+ categoryDefinition.setName("1234AbcdE-");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde-"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_03() throws Exception {
+ categoryDefinition.setName("1234AbcdE+");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde+"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_04() throws Exception {
+ categoryDefinition.setName("1234AbcdE.");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde."); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_05() throws Exception {
+ categoryDefinition.setName("1234AbcdE'");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde'");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_06() throws Exception {
+ categoryDefinition.setName("1234AbcdE=");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde="); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_07() throws Exception {
+ categoryDefinition.setName("1234AbcdE:");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde:"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_08() throws Exception {
+ categoryDefinition.setName("1234AbcdE@");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde@"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_09() throws Exception {
+ categoryDefinition.setName("1234AbcdE_");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde_"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_10() throws Exception {
+ categoryDefinition.setName("1234AbcdE#");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde#"); // normalization
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_11() throws Exception {
+ categoryDefinition.setName("1234AbcdE d");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde d"); // normalization
+ categoryDefinition.setName("1234AbcdE D");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void addServiceCategoryAllowedcharacters_12() throws Exception {
+ categoryDefinition.setName("1234AbcdE &_=+.-'#:@ d");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("1234abcde &_=+.-'#:@ d"); // normalization
+ categoryDefinition.setName("1234AbcdE &_=+.-'#:@ D");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveSpaceFromBeginning() throws Exception {
+ categoryDefinition.setName(" Category01");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("category01"); // normalization
+ categoryDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveSpaceFromEnd() throws Exception {
+ categoryDefinition.setName("Category01 ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("category01"); // normalization
+ categoryDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraSpace() throws Exception {
+ categoryDefinition.setName("Category 02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("category 02"); // normalization
+ categoryDefinition.setName("Category 02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraAmpersand() throws Exception {
+ categoryDefinition.setName("Category&& &02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("category& &02"); // normalization
+ categoryDefinition.setName("Category& &02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraDash() throws Exception {
+ categoryDefinition.setName("CategorY-- --02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("CategorY- -02");
+ categoryDefinition.setNormalizedName("category- -02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraPlus() throws Exception {
+ categoryDefinition.setName("CateGory++++ +02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("CateGory+ +02");
+ categoryDefinition.setNormalizedName("category+ +02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraPeriod() throws Exception {
+ categoryDefinition.setName("Category.... .02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category. .02");
+ categoryDefinition.setNormalizedName("category. .02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraApostrophe() throws Exception {
+ categoryDefinition.setName("CaTegory''' '02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("CaTegory' '02");
+ categoryDefinition.setNormalizedName("category' '02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraHashtag() throws Exception {
+ categoryDefinition.setName("Category### #02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category# #02");
+ categoryDefinition.setNormalizedName("category# #02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtrEequal() throws Exception {
+ categoryDefinition.setName("Category=== =02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category= =02");
+ categoryDefinition.setNormalizedName("category= =02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtrColon() throws Exception {
+ categoryDefinition.setName("Category::: :02");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category: :02");
+ categoryDefinition.setNormalizedName("category: :02");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtrAt() throws Exception {
+ categoryDefinition.setName("Category@@@ @a2");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category@ @a2");
+ categoryDefinition.setNormalizedName("category@ @a2");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_RemoveExtraUnderscore() throws Exception {
+ categoryDefinition.setName("Category___ _22");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Category_ _22");
+ categoryDefinition.setNormalizedName("category_ _22");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_FirstWordStartWithNumber() throws Exception {
+ categoryDefinition.setName("1Category one");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("1Category One");
+ categoryDefinition.setNormalizedName("1category one");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_FirstWordStartWithNonAlphaNumeric() throws Exception { // The
+ // first
+ // word
+ // must
+ // start
+ // with
+ // an
+ // alpha-numeric
+ // character
+ // [a-Z
+ // A..Z,
+ // 0..9]
+ char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ categoryDefinition.setName(invalidChars[i] + "AbcD123");
+ categoryDefinition.setNormalizedName((invalidChars[i] + "AbcD123").toLowerCase());
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition,
+ sdncAdminUserDetails1, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+
+ }
+ }
+
+ @Test
+ public void addServiceCategoryAlreadyExist_uniqueness() throws Exception { // Verify
+ // category
+ // name
+ // duplication
+ // ("uniqueness")
+ // as
+ // non-case-sensitive,
+ // so
+ // we
+ // don’t
+ // create
+ // duplicate
+ // names
+ // with
+ // upper/lower
+ // case
+ // inconsistency.
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition); // also
+ // set
+ // catalog
+ // uniqeId
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ // Create same category name again
+ DbUtils.deleteFromEsDbByPattern("_all");
+ CategoryDefinition categoryDataDefinition2 = new CategoryDefinition();
+ categoryDataDefinition2.setName(categoryDefinition.getName());
+ RestResponse addDuplicateCategoryRest = CategoryRestUtils.createCategory(categoryDataDefinition2,
+ sdncAdminUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_ALREADY_EXISTS,
+ addDuplicateCategoryRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDataDefinition2, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS, STATUS_CODE_ALREADY_EXISTS, AUDIT_SERVICE_TYPE,
+ "Service", categoryDefinition.getName());
+ // Get Category and verify that category was created is not deleted
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_01() throws Exception {
+ categoryDefinition.setName("At and T");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("At & T");
+ categoryDefinition.setNormalizedName("at & t");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_02() throws Exception {
+ categoryDefinition.setName("At and t");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("At & T");
+ categoryDefinition.setNormalizedName("at & t");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_03() throws Exception {
+ categoryDefinition.setName("Atand T");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("atand t");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_04() throws Exception {
+ categoryDefinition.setName("At andT");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("at andt");
+ categoryDefinition.setName("At AndT");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_05() throws Exception {
+ categoryDefinition.setName(" and AttT");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("and attt");
+ categoryDefinition.setName("And AttT");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_06() throws Exception {
+ categoryDefinition.setName("AttT and ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("attt and");
+ categoryDefinition.setName("AttT And");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ // Bug
+ @Test
+ public void categoryNameValidation_ReplaceAndWithAmpersand_07() throws Exception {
+ categoryDefinition.setName(" and a");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("and a");
+ categoryDefinition.setName("And a");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationMaxLength() throws Exception {
+ categoryDefinition.setName("AsdfghjQ234567890@#.&:+-_");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("asdfghjq234567890@#.&:+-_");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+
+ }
+
+ @Test
+ public void categoryNameValidationMaxLengthAfterNormalization() throws Exception {
+ categoryDefinition.setName(" A jQ234 @@@___ +++ At and T and and ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("A JQ234 @_ + At & T & And");
+ categoryDefinition.setNormalizedName("a jq234 @_ + at & t & and");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+
+ }
+
+ @Test
+ public void categoryNameValidationExceedMaxLengthAfterNormalization() throws Exception {
+ categoryDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("abdfghbcva jq234 @_ + at&t");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+ }
+
+ @Test
+ public void categoryNameValidationMinLengthAfterNormalization() throws Exception { // MinLengthAfterNormalization
+ // =
+ // 4
+ // characters
+ categoryDefinition.setName(" At and T ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("At & T");
+ categoryDefinition.setNormalizedName("at & t");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationLessThanMinLengthAfterNormalization() throws Exception {
+ categoryDefinition.setName(" A&&&&&&&&&&&&&&&&&T ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("a&t");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+ }
+
+ @Test
+ public void categoryNameValidationIsNull() throws Exception {
+ categoryDefinition.setName(null);
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+ }
+
+ @Test
+ public void categoryNameValidationIsEmpty() throws Exception {
+ categoryDefinition.setName("");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+ }
+
+ @Test
+ public void categoryNameValidationInvalidCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // DbUtils.cleanAllAudits();
+ categoryDefinition.setName("AbcD123" + invalidChars[i]);
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setNormalizedName("");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditFailure(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE,
+ "Service", "category");
+ }
+ }
+
+ @Test
+ public void categoryNameValidationSameNameDifferentResourceType() throws Exception { // same
+ // Catalog
+ // Name
+ // for
+ // service/resource/product
+ // is
+ // allowed
+ String name = ("Abcd");
+ CategoryDefinition categoryDataDefinition1 = new CategoryDefinition();
+ CategoryDefinition categoryDataDefinition2 = new CategoryDefinition();
+ CategoryDefinition categoryDataDefinition3 = new CategoryDefinition();
+ categoryDataDefinition1.setName(name);
+ categoryDataDefinition2.setName(name);
+ categoryDataDefinition3.setName(name);
+ // CREATE CATEGORY FOR SERVICE
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition1,
+ sdncAdminUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDataDefinition1.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDataDefinition1);
+ // get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition1); // also
+ // set
+ // catalog
+ // uniqeId
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDataDefinition1, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ // CREATE CATEGORY FOR RESOURCE_COMPONENT_TYPE
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition2, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDataDefinition2.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDataDefinition2);
+ // Get Category
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition2);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDataDefinition2, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ // CREATE CATEGORY FOR PRODUCT
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse addCategotyRest = CategoryRestUtils.createCategory(categoryDataDefinition3,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ addCategotyRest.getErrorCode().intValue());
+ categoryDataDefinition3.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateCategoryResponse(addCategotyRest, categoryDataDefinition3);
+
+ // Get Category
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDataDefinition3);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception { // First
+ // letter
+ // of
+ // key
+ // words
+ // are
+ // capitalized
+ categoryDefinition.setName("beNNy shaY michEl");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("BeNNy ShaY MichEl");
+ categoryDefinition.setNormalizedName("benny shay michel");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_01() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" bank OF america ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Bank of America");
+ categoryDefinition.setNormalizedName("bank of america");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_02() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName("THE america bank ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("THE America Bank");
+ categoryDefinition.setNormalizedName("the america bank");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_03() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" A bank OF america ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("A Bank of America");
+ categoryDefinition.setNormalizedName("a bank of america");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_04() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" bank america is A big ban ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Bank America Is a Big Ban");
+ categoryDefinition.setNormalizedName("bank america is a big ban");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_05() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" aN apple comPany inC ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("AN Apple ComPany InC");
+ categoryDefinition.setNormalizedName("an apple company inc");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_06() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" eat AN apple ANAN");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Eat an Apple ANAN");
+ categoryDefinition.setNormalizedName("eat an apple anan");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_07() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" united states OF americA ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("United States of AmericA");
+ categoryDefinition.setNormalizedName("united states of america");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ // need to re-check
+ @Test
+ public void categoryNameValidationConjunctions_08() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" oF united states OF amer ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("OF United States of Amer");
+ categoryDefinition.setNormalizedName("of united states of amer");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_09() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" to Apple TO at&T TOO ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("To Apple to At&T TOO");
+ categoryDefinition.setNormalizedName("to apple to at&t too");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_10() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" eat apple AS you liiikeas ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Eat Apple as You Liiikeas");
+ categoryDefinition.setNormalizedName("eat apple as you liiikeas");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_11() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" as you may want ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("As You May Want");
+ categoryDefinition.setNormalizedName("as you may want");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void categoryNameValidationConjunctions_12() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" the bank OF america ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("The Bank of America");
+ categoryDefinition.setNormalizedName("the bank of america");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ // need to recheck
+ @Test
+ public void categoryNameValidationConjunctions_13() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" To tel-toto ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("To Tel-toto");
+ categoryDefinition.setNormalizedName("to tel-toto");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ // recheck
+ @Test
+ public void categoryNameValidationConjunctions_14() throws Exception { // Normalize
+ // the
+ // category
+ // name
+ // conjunctions
+ // ('of',
+ // 'to',
+ // 'for',
+ // 'as',
+ // 'a',
+ // 'an'
+ // ,
+ // 'the')
+ // are
+ // lower
+ // case.
+ categoryDefinition.setName(" tel-aviv To la ");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_CREATED,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Tel-aviv to La");
+ categoryDefinition.setNormalizedName("tel-aviv to la");
+ CategoryValidationUtils.validateCreateCategoryResponse(createCategotyRest, categoryDefinition);
+ // Get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ AuditValidationUtils.categoryAuditSuccess(ADD_CATEGORY, categoryDefinition, sdncAdminUserDetails,
+ STATUS_CODE_CREATED, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void createServiceCategoryHttpCspUserIdIsEmpty() throws Exception {
+ User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncAdminUserDetails1.setUserId("");
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Abcd");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName("");
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY);
+ }
+
+ @Test
+ public void createServiceCategorHttpCspUserIdIsNull() throws Exception {
+ User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncAdminUserDetails1.setUserId(null);
+ RestResponse createCategotyRest = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails1,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createCategotyRest.getErrorCode().intValue());
+ categoryDefinition.setName("Abcd");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName("");
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY);
+ }
+
+ @Test
+ public void createSrvcCategoryHttpCspUserIdHeaderIsMissing() throws Exception {
+ RestResponse createConsumerRest = CategoryRestUtils
+ .createServiceCategoryHttpCspAtuUidIsMissing(categoryDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createConsumerRest.getErrorCode().intValue());
+ categoryDefinition.setName("Abcd");
+ // get service category and validate that category was not added
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyCategoryNotExistsInGetResponse(getAllCategoriesRest, categoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName("");
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_SERVICE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_CATEGORY);
+ }
+
+ @Test
+ public void getServiceCategoryHierarchySuccessFlow() throws Exception {
+
+ int numOfCategories = 3;
+ List<CategoryDefinition> categories = new ArrayList<CategoryDefinition>();
+ RestResponse restResponse;
+ CategoryDefinition category;
+ String categoryName = categoryDefinition.getName();
+ for (int i = 0; i < numOfCategories; i++) {
+ categoryDefinition.setName(categoryName + i);
+ restResponse = CategoryRestUtils.createCategory(categoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ category = ResponseParser.parseToObject(restResponse.getResponse(), CategoryDefinition.class);
+ categories.add(category);
+ }
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+
+ AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY, AUDIT_SERVICE_TYPE,
+ sdncAdminUserDetails, STATUS_CODE_SUCCESS);
+ for (CategoryDefinition categoryCurr : categories) {
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryCurr);
+ }
+ }
+
+ ///////////////////////////////// US570520 /////////////////////////////////
+ private List<CategoryDefinition> defineCategories() throws Exception {
+ String firstCategory = "FirstCategory";
+ String secondCategory = "secondCategory";
+ String thirdCategory = "ThirdCategory";
+ String forthCategory = "forthCategory";
+ CategoryDefinition category1 = new CategoryDefinition(categoryDefinition);
+ category1.setName(firstCategory);
+ CategoryDefinition category2 = new CategoryDefinition(categoryDefinition);
+ category2.setName(secondCategory);
+ CategoryDefinition category3 = new CategoryDefinition(categoryDefinition);
+ category3.setName(thirdCategory);
+ CategoryDefinition category4 = new CategoryDefinition(categoryDefinition);
+ category4.setName(forthCategory);
+ ArrayList<CategoryDefinition> categoryList = new ArrayList<CategoryDefinition>();
+ categoryList.add(category1);
+ categoryList.add(category2);
+ categoryList.add(category3);
+ categoryList.add(category4);
+ return categoryList;
+ }
+
+ @Test
+ public void getAllResourceCategoriesHirarchy() throws Exception {
+ createAndValidateCategoriesExist(RESOURCE_COMPONENT_TYPE, categoryList);
+
+ for (int i = 0; i < categoryList.size(); i++) {
+ List<String> subCategorieUniqueIdList = new ArrayList<String>();
+ for (int j = 0; j < subCategoryList.size(); j++) {
+ RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryList.get(j),
+ categoryList.get(i), sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ if (createSubCategory.getErrorCode().intValue() == STATUS_CODE_CREATED) {
+ String subCategoryUniqeId = ResponseParser.getUniqueIdFromResponse(createSubCategory);
+ subCategorieUniqueIdList.add(subCategoryUniqeId);
+ subCategoriesToDeleteMap.put(categoryList.get(i).getUniqueId(), subCategorieUniqueIdList);
+ }
+ }
+ }
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+
+ for (int i = 0; i < categoryList.size(); i++) {
+ for (int j = 0; j < subCategoryList.size(); j++) {
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ categoryList.get(i).getUniqueId(), subCategoryList.get(j));
+ }
+ }
+
+ checkAuditSuccess(RESOURCE_COMPONENT_TYPE);
+ }
+
+ private List<SubCategoryDefinition> defineSubCategories(int catListSize) {
+ List<SubCategoryDefinition> subCatList = new ArrayList<SubCategoryDefinition>();
+ for (int j = 1; j <= catListSize; j++) {
+ SubCategoryDefinition subCategory = new SubCategoryDefinition();
+ subCategory.setName("SubCategory" + String.valueOf(j));
+ subCatList.add(subCategory);
+ }
+ return subCatList;
+ }
+
+ private void createAndValidateCategoriesExist(String comp, List<CategoryDefinition> categoryList) throws Exception {
+ createCategories(comp, categoryList);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, comp);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ verifyCategoriesExist(categoryList, getAllCategoriesRest);
+ }
+
+ private void verifyCategoriesExist(List<CategoryDefinition> categoryList, RestResponse getAllCategoriesRest) {
+ for (int i = 0; i < categoryList.size(); i++) {
+ categoryList.get(i).setName(WordUtils.capitalize(categoryList.get(i).getName()));
+ CategoryValidationUtils.verifyCategoryExistInGetResponse(getAllCategoriesRest, categoryList.get(i));
+ }
+ }
+
+ private void createCategories(String comp, List<CategoryDefinition> categoryList) throws Exception {
+ for (int i = 0; i < categoryList.size(); i++) {
+ CategoryRestUtils.createCategory(categoryList.get(i), sdncAdminUserDetails, comp);
+ }
+ }
+
+ @Test
+ public void getAllServiceCategoriesHirarchy() throws Exception {
+ // deleteCategories(categoryList, SERVICE_COMPONENT_TYPE);
+ createAndValidateCategoriesExist(SERVICE_COMPONENT_TYPE, categoryList);
+ checkAuditSuccess(SERVICE_COMPONENT_TYPE);
+ // deleteCategories(categoryList, SERVICE_COMPONENT_TYPE);
+ }
+
+ @Test
+ public void getAllResourceCategories_noAttUserHeader() throws Exception {
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(new User(), RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", 403, getAllCategoriesRest.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
+ getAllCategoriesRest.getResponse());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY);
+ expectedCatrgoryAuditJavaObject.setModifierName("");
+ expectedCatrgoryAuditJavaObject.setModifierUid("");
+ expectedCatrgoryAuditJavaObject.setDetails(RESOURCE_COMPONENT_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY);
+ }
+
+ @Test
+ public void getAllResourceCategories_userNotProvisioned() throws Exception {
+ User notProvisionedUser = new User();
+ notProvisionedUser.setUserId("aa0001");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(notProvisionedUser,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", 409, getAllCategoriesRest.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ getAllCategoriesRest.getResponse());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY);
+ expectedCatrgoryAuditJavaObject.setModifierName("");
+ expectedCatrgoryAuditJavaObject.setModifierUid(notProvisionedUser.getUserId());
+ expectedCatrgoryAuditJavaObject.setDetails(RESOURCE_COMPONENT_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_RESTRICTED_OPERATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY);
+ }
+
+ @Test
+ public void getAllResourceCategories_unsupportedComponent() throws Exception {
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "comp");
+ assertEquals("Check response code after get all categories hirarchy", 400,
+ getAllCategoriesRest.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(),
+ new ArrayList<String>(Arrays.asList("component type")), getAllCategoriesRest.getResponse());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.UNSUPPORTED_ERROR.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY);
+ expectedCatrgoryAuditJavaObject.setModifierUid(sdncAdminUserDetails.getUserId());
+ expectedCatrgoryAuditJavaObject.setModifierName(sdncAdminUserDetails.getFullName());
+ expectedCatrgoryAuditJavaObject.setDetails("comp");
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_INVALID_CONTENT));
+ expectedCatrgoryAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo,
+ new ArrayList<String>(Arrays.asList("component type"))));
+ AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY);
+ }
+
+ @Test(enabled = false)
+ public void getAllResourceCategories_emptyList() throws Exception {
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse());
+ assertTrue(jArr.length() == 0);
+
+ checkAuditSuccess(RESOURCE_COMPONENT_TYPE);
+ }
+
+ private void checkAuditSuccess(String componentType) throws Exception {
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(GET_CATEGORY_HIERARCHY);
+ expectedCatrgoryAuditJavaObject.setModifierName(sdncAdminUserDetails.getFullName());
+ expectedCatrgoryAuditJavaObject.setModifierUid(sdncAdminUserDetails.getUserId());
+ expectedCatrgoryAuditJavaObject.setDetails(componentType);
+ expectedCatrgoryAuditJavaObject.setStatus("200");
+ expectedCatrgoryAuditJavaObject.setDesc("OK");
+ AuditValidationUtils.validateGetCategoryHirarchy(expectedCatrgoryAuditJavaObject, GET_CATEGORY_HIERARCHY);
+ }
+
+ @Test(enabled = false)
+ public void getAllServiceCategories_emptyList() throws Exception {
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse());
+ assertTrue(jArr.length() == 0);
+
+ checkAuditSuccess(SERVICE_COMPONENT_TYPE);
+ }
+
+ @Test(enabled = false)
+ public void getAllProductCategories_emptyList() throws Exception {
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get Category", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ JSONArray jArr = new JSONArray(getAllCategoriesRest.getResponse());
+ assertTrue(jArr.length() == 0);
+
+ checkAuditSuccess(PRODUCT_COMPONENT_TYPE);
+ }
+
+ //////////////////////////////////////////////////////////////////////////////
+
+ @Test
+ public void importCategories() throws Exception {
+
+ String importResourceDir = config.getImportTypesConfigDir() + File.separator + "categoryTypesTest.zip";
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+ mpBuilder.addPart("categoriesZip", new FileBody(new File(importResourceDir)));
+
+ RestResponse importResult = CategoryRestUtils.importCategories(mpBuilder, sdncAdminUserDetails.getUserId());
+ assertEquals("Check response code after Import", BaseRestUtils.STATUS_CODE_CREATED,
+ importResult.getErrorCode().intValue());
+
+ Map<String, Object> map = ResponseParser.parseToObjectUsingMapper(importResult.getResponse(), Map.class);
+ assertEquals("Check entries count", 2, map.size());
+
+ List<Map<String, Object>> resources = (List<Map<String, Object>>) map.get("resources");
+ assertEquals("Check resource category entries count", 1, resources.size());
+
+ List<Map<String, Object>> services = (List<Map<String, Object>>) map.get("services");
+ assertEquals("Check resource category entries count", 2, services.size());
+
+ RestResponse allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "resources");
+ List<CategoryDefinition> resourceCategories = ResponseParser.parseCategories(allCategories);
+ for (Map<String, Object> resource : resources) {
+ boolean exist = false;
+
+ for (CategoryDefinition categ : resourceCategories) {
+ if (categ.getName().equals(resource.get("name"))) {
+ exist = true;
+ break;
+ }
+ }
+ assertTrue("Check existance resource category " + resource.get("name"), exist);
+ }
+
+ allCategories = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, "services");
+ List<CategoryDefinition> servicesCategories = ResponseParser.parseCategories(allCategories);
+ for (Map<String, Object> service : services) {
+ boolean exist = false;
+
+ for (CategoryDefinition categ : servicesCategories) {
+ if (categ.getName().equals(service.get("name"))) {
+ exist = true;
+ break;
+ }
+ }
+ assertTrue("Check existance service category " + service.get("name"), exist);
+ }
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java
new file mode 100644
index 0000000000..7f30f8ca92
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/ElementsApiTest.java
@@ -0,0 +1,147 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.testng.annotations.Test;
+
+public class ElementsApiTest extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ElementsApiTest() {
+ super(name, ElementsApiTest.class.getName());
+ }
+
+ // public LCSbaseTest(TestName testName, String className) {
+ // super(testName, className);
+ // }
+
+ // public ElementsApiTest(TestName name, String name2) {
+ //// super(name, name2);
+ // // TODO Auto-generated constructor stub
+ // }
+
+ // Expected 200 Keep
+ @Test
+ public void getAllPropertyScopesSuccess() throws Exception {
+ RestResponse response = ResourceRestUtils.getAllPropertyScopesTowardsCatalogBe();
+ String action = "Get All Property Scopes";
+ int expectedCode = 200;
+ verifyErrorCode(response, action, expectedCode);
+ }
+
+ // Expected 200 Keep
+ @Test
+ public void getAllArtifactTypes() throws Exception {
+ RestResponse response = ResourceRestUtils.getAllArtifactTypesTowardsCatalogBe();
+ String action = "Get All Artifact Types";
+ int expectedCode = 200;
+ verifyErrorCode(response, action, expectedCode);
+ }
+
+ // Expected 200 Keep
+ @Test
+ public void getConfiguration() throws Exception {
+ RestResponse response = ResourceRestUtils.getConfigurationTowardsCatalogBe();
+ String action = "Get All Artifact Types";
+ int expectedCode = 200;
+
+ String json = response.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+
+ HashMap<String, Object> artifacts = (HashMap<String, Object>) jsonResp.get("artifacts");
+ Long defaultHeatTimeout = (Long) jsonResp.get("defaultHeatTimeout");
+
+ if (defaultHeatTimeout == null) {
+ response.setErrorCode(500);
+ verifyErrorCode(response, action, expectedCode);
+ return;
+ }
+
+ if (artifacts == null) {
+ response.setErrorCode(500);
+ verifyErrorCode(response, action, expectedCode);
+ return;
+ }
+
+ JSONObject deploymentResources = (JSONObject) artifacts.get("deployment");
+ JSONArray otherResources = (JSONArray) artifacts.get("other");
+ if (deploymentResources == null || otherResources == null) {
+ response.setErrorCode(500);
+ verifyErrorCode(response, action, expectedCode);
+ return;
+ }
+
+ JSONArray roles = (JSONArray) jsonResp.get("roles");
+ if (roles == null) {
+ response.setErrorCode(500);
+ verifyErrorCode(response, action, expectedCode);
+ return;
+ }
+
+ }
+
+ public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
+ assertNotNull("check response object is not null after " + action, response);
+ assertNotNull("check error code exists in response after " + action, response.getErrorCode());
+ assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void getAllCategoriesSuccess() throws Exception {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ RestResponse response = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
+ String action = "Get All Categories";
+ int expectedCode = 200;
+ verifyErrorCode(response, action, expectedCode);
+ }
+
+ @Test(enabled = false)
+ public void getAllTagSuccess() throws Exception {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ RestResponse response = ResourceRestUtils.getAllTagsTowardsCatalogBe();
+ String action = "Get All Categories";
+ int expectedCode = 200;
+ verifyErrorCode(response, action, expectedCode);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java
new file mode 100644
index 0000000000..7858b3259f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/GroupingTest.java
@@ -0,0 +1,2003 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.SkipException;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GroupingTest extends CategoriesBaseTest {
+
+ protected static final String ADD_GROUPING = "AddGrouping";
+ protected static final String CATEGORY = "category";
+ protected static final String SUB_CATEGORY = "sub-category";
+ protected static final String GROUPING = "grouping";
+
+ public GroupingTest() {
+ super(name, GroupingTest.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ private CategoryDefinition productCategoryDefinition;
+ private CategoryDefinition productCategoryDefinition2;
+
+ private SubCategoryDefinition productSubCategoryDefinition;
+ private SubCategoryDefinition productSubCategoryDefinition2;
+ private SubCategoryDefinition productSubCategoryDefinition3;
+
+ private GroupingDefinition productGroupingDefinition;
+ private GroupingDefinition productGroupingDefinition2;
+ private GroupingDefinition productGroupingDefinition3;
+
+ @BeforeMethod
+ public void init() throws Exception {
+
+ // Category setup
+ productCategoryDefinition = new CategoryDefinition();
+ productCategoryDefinition.setName("Category1");
+ productCategoryDefinition2 = new CategoryDefinition();
+ productCategoryDefinition2.setName("Category2");
+
+ // Subcategory setup
+ productSubCategoryDefinition = new SubCategoryDefinition();
+ productSubCategoryDefinition.setName("SubCategory1");
+
+ productSubCategoryDefinition2 = new SubCategoryDefinition();
+ productSubCategoryDefinition2.setName("SubCategory2");
+
+ productSubCategoryDefinition3 = new SubCategoryDefinition();
+ productSubCategoryDefinition3.setName("SubCategory1");
+
+ // Group setup
+ productGroupingDefinition = new GroupingDefinition();
+ productGroupingDefinition.setName("Grouping1");
+
+ productGroupingDefinition2 = new GroupingDefinition();
+ productGroupingDefinition2.setName("Grouping2");
+
+ productGroupingDefinition3 = new GroupingDefinition();
+ productGroupingDefinition3.setName("Grouping1");
+
+ // Init product category
+ RestResponse createCategory = CategoryRestUtils.createCategory(productCategoryDefinition,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ CategoryDefinition category = ResponseParser.parseToObject(createCategory.getResponse(),
+ CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productCategoryDefinition.getName(),
+ category.getName());
+ productCategoryDefinition = category;
+
+ // Init product category1
+ createCategory = CategoryRestUtils.createCategory(productCategoryDefinition2, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productCategoryDefinition2.getName(),
+ category.getName());
+ productCategoryDefinition2 = category;
+
+ // Init product productSubCategoryDefinition to
+ // productCategoryDefinition
+ RestResponse createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createSubCategory.getErrorCode().intValue());
+ SubCategoryDefinition subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(),
+ SubCategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productSubCategoryDefinition.getName(),
+ subCategory.getName());
+ productSubCategoryDefinition = subCategory;
+ productCategoryDefinition.addSubCategory(productSubCategoryDefinition);
+
+ // Init product productSubCategoryDefinition1 to
+ // productCategoryDefinition
+ createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition2,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createSubCategory.getErrorCode().intValue());
+ subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(), SubCategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productSubCategoryDefinition2.getName(),
+ subCategory.getName());
+ productSubCategoryDefinition2 = subCategory;
+ productCategoryDefinition.addSubCategory(productSubCategoryDefinition2);
+
+ // Init product productSubCategoryDefinition3 to
+ // productCategoryDefinition2
+ createSubCategory = CategoryRestUtils.createSubCategory(productSubCategoryDefinition3,
+ productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createSubCategory.getErrorCode().intValue());
+ subCategory = ResponseParser.parseToObject(createSubCategory.getResponse(), SubCategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productSubCategoryDefinition3.getName(),
+ subCategory.getName());
+ productSubCategoryDefinition3 = subCategory;
+ productCategoryDefinition2.addSubCategory(productSubCategoryDefinition3);
+ }
+
+ @Test
+ public void createProductGroupCategorySuccess() throws Exception {
+ createGroupingSuccess(productGroupingDefinition, productSubCategoryDefinition, productCategoryDefinition,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE, AUDIT_PRODUCT_TYPE);
+ }
+
+ private void createGroupingSuccess(GroupingDefinition groupingDefinition,
+ SubCategoryDefinition subCategoryDefinition, CategoryDefinition categoryDefinition,
+ User sdncProductStrategistUserDetails, String productComponentType, String auditType) throws Exception {
+
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, subCategoryDefinition,
+ categoryDefinition, sdncProductStrategistUserDetails, productComponentType);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("grouping1");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ productComponentType);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest, categoryDefinition.getUniqueId(),
+ subCategoryDefinition.getUniqueId(), groupingDefinition);
+
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, categoryDefinition, subCategoryDefinition,
+ groupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, auditType);
+ }
+
+ //// Benny
+
+ @Test
+ public void createProductGroupByProductStrategist() throws Exception {
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("grouping1");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createProductGroupAlreadyExistInSameCategorySubCategory() throws Exception {
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("grouping1");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ // Create Same Group already exist on same Category/SubCategory
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition, productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS,
+ createGroupingRest.getErrorCode().intValue());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_GROUPING_EXISTS_FOR_SUB_CATEGORY, STATUS_CODE_ALREADY_EXISTS, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, productGroupingDefinition.getName(), productSubCategoryDefinition.getName());
+ }
+
+ @Test
+ public void createProductGroupUnderSameCategoryButDifferentSubCategory() throws Exception {
+ // Setting : Category-A, Sub-category-B , group : aBcd (display-Name :
+ // ABcd, normalized: abcd)  [A, B, ABcd]
+ // Action : Category-A, Sub-category-C, group : abcD (display-Name :
+ // ABcd, normalized: abcd)  [A, C, ABcd]
+ productGroupingDefinition.setName("ABCd");
+ productGroupingDefinition2.setName("abcD");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition2,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition2.setName("ABCd");
+ productGroupingDefinition2.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition,
+ productSubCategoryDefinition2, productGroupingDefinition2, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition2.getUniqueId(),
+ productGroupingDefinition2);
+ }
+
+ @Test
+ public void createProductGroupUnderSameSubCategoryButDifferentCategory() throws Exception {
+ // Setting : Category-A, Sub-category-B , group : aBcd (display-Name :
+ // ABcd, normalized: abcd)  [A, B, ABcd]
+ // : Category-A, Sub-category-C, group : abcD (display-Name : ABcd,
+ // normalized: abcd)  [A, C, ABcd]
+ // : Category-K, Sub-category-B, group : abcD (display-Name : ABcd,
+ // normalized: abcd)  [K, B, ABcd]
+ productGroupingDefinition.setName("ABCd");
+ productGroupingDefinition2.setName("abcD");
+ productGroupingDefinition3.setName("aBCd");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition2,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition2.setName("ABCd");
+ productGroupingDefinition2.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition,
+ productSubCategoryDefinition2, productGroupingDefinition2, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition3, productSubCategoryDefinition3,
+ productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition3.setName("ABCd");
+ productGroupingDefinition3.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition3);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition2,
+ productSubCategoryDefinition3, productGroupingDefinition3, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition2.getUniqueId(),
+ productGroupingDefinition2);
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition2.getUniqueId(), productSubCategoryDefinition3.getUniqueId(),
+ productGroupingDefinition3);
+
+ }
+
+ @Test
+ public void createProductGroupsOnSameCategorySubCategory() throws Exception {
+ // Setting : Category-A, Sub-category-B , group : ABcd (display-Name :
+ // ABcd, normalized: abcd) [A ,B, ABcd]
+ // Action : Category-A, Sub-category-B, group : ZXcv (display-Name :
+ // ZXcv, normalized: zxcv) [A, B, ZXcv]
+ productGroupingDefinition.setName("ABcd");
+ productGroupingDefinition2.setName("ZXcv");
+ productGroupingDefinition2.setNormalizedName("zxcv");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition2, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition2);
+ }
+
+ @Test
+ public void createProductGroupUnderDifferentCategory() throws Exception {
+ // Setting : Category-A, Sub-category-B , group : aBcd (display-Name :
+ // ABcd, normalized: abcd) [A ,B, ABcd]
+ // Action : Category-K, Sub-category-B, group : abcD (display-Name :
+ // ABcd, normalized: abcd) [K, B, ABcd]
+ // productGroupingDefinition.setName("ABCd");
+ productGroupingDefinition.setName("ABcD");
+ productGroupingDefinition2.setName("abcD");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("abcd");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition2, productSubCategoryDefinition3,
+ productCategoryDefinition2, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition2.setNormalizedName("abcd");
+ productGroupingDefinition2.setName("ABcD");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition2);
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition2,
+ productSubCategoryDefinition3, productGroupingDefinition2, sdncProductStrategistUserDetails,
+ STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition2.getUniqueId(), productSubCategoryDefinition3.getUniqueId(),
+ productGroupingDefinition2);
+ }
+
+ ///////////
+ @Test
+ public void createProductGroupByNonProductStrategist() throws Exception {
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_RESTRICTED_OPERATION,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncAdminUserDetails, ActionStatus.RESTRICTED_OPERATION,
+ STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE);
+ }
+
+ // @Ignore("DE176245")
+ @Test
+ public void createProductGroupForNonExistingComponentType() throws Exception {
+ String nonSupportedComponentType = "NonExistingComponentType"; // instead
+ // resource/product
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ nonSupportedComponentType);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType);
+ }
+
+ // @Ignore("DE176245")
+ @Test
+ public void createResourceGroup() throws Exception {
+ // Resource doesn't have group
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE);
+ }
+
+ // @Ignore("DE176245")
+ @Test
+ public void createServiceGroup() throws Exception {
+ // Service doesn't have group
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void createProductGroupForNonExistingCategory() throws Exception {
+
+ CategoryDefinition productCategoryDefinition100 = new CategoryDefinition();
+ productCategoryDefinition100.setName("category.nonexistingCategory");
+ productCategoryDefinition100.setUniqueId("category.nonexistingCategory");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition100, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ productSubCategoryDefinition.setName(productSubCategoryDefinition.getUniqueId());
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition100,
+ productSubCategoryDefinition, productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, STATUS_CODE_NOT_FOUND, AUDIT_PRODUCT_TYPE,
+ PRODUCT_COMPONENT_TYPE, CATEGORY, "");
+ }
+
+ @Test
+ public void createProductGroupForNonExistingSunCategory() throws Exception {
+ throw new SkipException(
+ "Skipping - failed in audit validation expected \"products\" actual result was \"product\" ");
+ // SubCategoryDefinition productSubCategoryDefinition100 = new
+ // SubCategoryDefinition();
+ // productSubCategoryDefinition100.setUniqueId("category.nonexistingSubCategory");
+ // RestResponse createGroupingRest =
+ // CategoryRestUtils.createGrouping(productGroupingDefinition,
+ // productSubCategoryDefinition100, productCategoryDefinition,
+ // sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ // assertEquals("Check response code after create Sub category",
+ // STATUS_CODE_NOT_FOUND, createGroupingRest.getErrorCode().intValue());
+ // RestResponse getAllCategoriesRest =
+ // CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ // PRODUCT_COMPONENT_TYPE);
+ // assertEquals("Check response code after get all categories ",
+ // STATUS_CODE_SUCCESS, getAllCategoriesRest.getErrorCode().intValue());
+ // CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ // productCategoryDefinition.getUniqueId(),
+ // productSubCategoryDefinition.getUniqueId(),
+ // productGroupingDefinition);
+ // //Audit validation
+ // productSubCategoryDefinition100.setName(productSubCategoryDefinition100.getUniqueId());
+ // AuditValidationUtils.groupingAuditFailure(ADD_GROUPING ,
+ // productCategoryDefinition, productSubCategoryDefinition100,
+ // productGroupingDefinition, sdncProductStrategistUserDetails,
+ // ActionStatus.COMPONENT_CATEGORY_NOT_FOUND,
+ // STATUS_CODE_NOT_FOUND,AUDIT_PRODUCT_TYPE, PRODUCT_COMPONENT_TYPE,
+ // SUB_CATEGORY, "");
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_01() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE-");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde-");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_02() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE+");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde+");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_03() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE&");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde&");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_04() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE-");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde-");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_05() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE+");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde+");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_06() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE.");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde.");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_07() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE'");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde'");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_08() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE=");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde=");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_09() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE:");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde:");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_10() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE@");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde@");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_11() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE_");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde_");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_12() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE#");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("1234abcde#");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void ProductGroupAllowedcharacters_13() throws Exception {
+ productGroupingDefinition.setName("1234AbcdE d");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("1234AbcdE D");
+ productGroupingDefinition.setNormalizedName("1234abcde d");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveSpaceFromBeginning() throws Exception {
+ productGroupingDefinition.setName(" Category01");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("category01");
+ productGroupingDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveSpaceFromEnd() throws Exception {
+ productGroupingDefinition.setName("Category01 ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("category01");
+ productGroupingDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraSpace() throws Exception {
+ productGroupingDefinition.setName("Category 02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("category 02");
+ productGroupingDefinition.setName("Category 02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraAmpersand() throws Exception {
+ productGroupingDefinition.setName("Category&& &02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("category& &02");
+ productGroupingDefinition.setName("Category& &02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraDash() throws Exception {
+ productGroupingDefinition.setName("CategorY-- --02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("category- -02");
+ productGroupingDefinition.setName("CategorY- -02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraPlus() throws Exception {
+ productGroupingDefinition.setName("CateGory++++ +02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("CateGory+ +02");
+ productGroupingDefinition.setNormalizedName("category+ +02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraPeriod() throws Exception {
+ productGroupingDefinition.setName("Category.... .02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category. .02");
+ productGroupingDefinition.setNormalizedName("category. .02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraApostrophe() throws Exception {
+ productGroupingDefinition.setName("CaTegory''' '02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("CaTegory' '02");
+ productGroupingDefinition.setNormalizedName("category' '02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraHashtag() throws Exception {
+ productGroupingDefinition.setName("Category### #02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category# #02");
+ productGroupingDefinition.setNormalizedName("category# #02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtrEequal() throws Exception {
+ productGroupingDefinition.setName("Category=== =02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category= =02");
+ productGroupingDefinition.setNormalizedName("category= =02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtrColon() throws Exception {
+ productGroupingDefinition.setName("Category::: :02");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category: :02");
+ productGroupingDefinition.setNormalizedName("category: :02");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtrAt() throws Exception {
+ productGroupingDefinition.setName("Category@@@ @a2");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category@ @a2");
+ productGroupingDefinition.setNormalizedName("category@ @a2");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_RemoveExtraUnderscore() throws Exception {
+ productGroupingDefinition.setName("Category___ _22");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Category_ _22");
+ productGroupingDefinition.setNormalizedName("category_ _22");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_FirstWordStartWithNumber() throws Exception {
+ productGroupingDefinition.setName("1Category one");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("1Category One");
+ productGroupingDefinition.setNormalizedName("1category one");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_FirstWordStartWithNonAlphaNumeric() throws Exception { // The
+ // first
+ // word
+ // must
+ // start
+ // with
+ // an
+ // alpha-numeric
+ // character
+ // [a-Z
+ // A..Z,
+ // 0..9]
+ char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' };
+ RestResponse createGroupingRest;
+ RestResponse getAllCategoriesRest;
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ productGroupingDefinition.setName(invalidChars[i] + "AbcD123");
+ productGroupingDefinition.setNormalizedName((invalidChars[i] + "AbcD123").toLowerCase());
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ }
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_01() throws Exception {
+ productGroupingDefinition.setName("At and T");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("At & T");
+ productGroupingDefinition.setNormalizedName("at & t");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_02() throws Exception {
+ productGroupingDefinition.setName("At and t");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("At & T");
+ productGroupingDefinition.setNormalizedName("at & t");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_03() throws Exception {
+ productGroupingDefinition.setName("Atand T");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("atand t");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_04() throws Exception {
+ productGroupingDefinition.setName("At andT");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("at andt");
+ productGroupingDefinition.setName("At AndT");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_05() throws Exception {
+ productGroupingDefinition.setName(" and AttT");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("and attt");
+ productGroupingDefinition.setName("And AttT");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_06() throws Exception {
+ productGroupingDefinition.setName("AttT and ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("attt and");
+ productGroupingDefinition.setName("AttT And");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidation_ReplaceAndWithAmpersand_07() throws Exception {
+ productGroupingDefinition.setName(" and a");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("and a");
+ productGroupingDefinition.setName("And a");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationMaxLength() throws Exception {
+ productGroupingDefinition.setName("AsdfghjQ234567890@#.&:+-_");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("asdfghjq234567890@#.&:+-_");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationMaxLengthAfterNormalization() throws Exception {
+ productGroupingDefinition.setName(" A jQ234 @@@___ +++ At and T and and ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("a jq234 @_ + at & t & and");
+ productGroupingDefinition.setName("A JQ234 @_ + At & T & And");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationExceedMaxLengthAfterNormalization() throws Exception {
+ productGroupingDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("abdfghbcva jq234 @_ + at&t");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, GROUPING);
+ }
+
+ @Test
+ public void groupNameValidationMinLengthAfterNormalization() throws Exception {
+ productGroupingDefinition.setName(" At&&&&&&&&&&&&t ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("at&t");
+ productGroupingDefinition.setName("At&t");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationLessThanMinLengthAfterNormalization() throws Exception {
+ productGroupingDefinition.setName(" A&&&&&&&&&&&&T ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("a&t");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, GROUPING);
+ }
+
+ @Test
+ public void groupNameValidationIsEmpty() throws Exception {
+ productGroupingDefinition.setName("");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("");
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, GROUPING);
+ }
+
+ @Test
+ public void groupNameValidationInvalidCharacters() throws Exception {
+ RestResponse createGroupingRest;
+ RestResponse getAllCategoriesRest;
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ productGroupingDefinition.setName("AbcD123" + invalidChars[i]);
+ createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_INVALID_CONTENT,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("");
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditFailure(ADD_GROUPING, productCategoryDefinition,
+ productSubCategoryDefinition, productGroupingDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, GROUPING);
+ }
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_01() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" bank OF america ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setNormalizedName("bank of america");
+ productGroupingDefinition.setName("Bank of America");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_02() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName("THE america bank ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("THE America Bank");
+ productGroupingDefinition.setNormalizedName("the america bank");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_03() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" A bank OF america ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("A Bank of America");
+ productGroupingDefinition.setNormalizedName("a bank of america");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_04() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" bank america is A big ban ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Bank America Is a Big Ban");
+ productGroupingDefinition.setNormalizedName("bank america is a big ban");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_05() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" aN apple comPany inC ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("AN Apple ComPany InC");
+ productGroupingDefinition.setNormalizedName("an apple company inc");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_06() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" eat AN apple ANAN");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Eat an Apple ANAN");
+ productGroupingDefinition.setNormalizedName("eat an apple anan");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_07() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" united states OF americA ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("United States of AmericA");
+ productGroupingDefinition.setNormalizedName("united states of america");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_08() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" oF united states OF amer ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("OF United States of Amer");
+ productGroupingDefinition.setNormalizedName("of united states of amer");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_09() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" to Apple TO at&T TOO ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("To Apple to At&T TOO");
+ productGroupingDefinition.setNormalizedName("to apple to at&t too");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_10() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" eat apple AS you liiikeas ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Eat Apple as You Liiikeas");
+ productGroupingDefinition.setNormalizedName("eat apple as you liiikeas");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_11() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" as you may want ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("As You May Want");
+ productGroupingDefinition.setNormalizedName("as you may want");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_12() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" the bank OF america ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("The Bank of America");
+ productGroupingDefinition.setNormalizedName("the bank of america");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_13() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" To tel-toto ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("To Tel-toto");
+ productGroupingDefinition.setNormalizedName("to tel-toto");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void groupNameValidationConjunctions_14() throws Exception {
+ // Normalize the grouping name conjunctions ('of', 'to', 'for', 'as',
+ // 'a', 'an' , 'the') are lower case.
+ productGroupingDefinition.setName(" tel-aviv To la ");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create product group", STATUS_CODE_CREATED,
+ createGroupingRest.getErrorCode().intValue());
+ productGroupingDefinition.setName("Tel-aviv to La");
+ productGroupingDefinition.setNormalizedName("tel-aviv to la");
+ CategoryValidationUtils.validateCreateGroupResponse(createGroupingRest, productGroupingDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ AuditValidationUtils.groupingAuditSuccess(ADD_GROUPING, productCategoryDefinition, productSubCategoryDefinition,
+ productGroupingDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createProductGroupHttpCspUserIdIsEmpty() throws Exception {
+ User sdncPS = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+ sdncPS.setUserId("");
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncPS, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_GROUPING);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(productCategoryDefinition.getUniqueId());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(productSubCategoryDefinition.getUniqueId());
+ expectedCatrgoryAuditJavaObject.setGroupingName(productGroupingDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_PRODUCT_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_GROUPING);
+ }
+
+ @Test
+ public void createProductGroupHttpCspUserIdIsNull() throws Exception {
+ User sdncPS = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+ sdncPS.setUserId(null);
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(productGroupingDefinition,
+ productSubCategoryDefinition, productCategoryDefinition, sdncPS, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createGroupingRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifyGroupingNotExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition.getUniqueId(),
+ productGroupingDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_GROUPING);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(productCategoryDefinition.getUniqueId());
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(productSubCategoryDefinition.getUniqueId());
+ expectedCatrgoryAuditJavaObject.setGroupingName(productGroupingDefinition.getName());
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_PRODUCT_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_GROUPING);
+ }
+
+ ////////////////////////////////////////////////
+ ///////////////////////////////////////////////
+ @Test
+ public void getProductCategoryHierarchySuccessFlow() throws Exception {
+ throw new SkipException(
+ "Skipping - failed in audit validation expected \"products\" actual result was \"product\" ");
+ // int numOfGrouping = 3;
+ // List<GroupingDefinition> groupingList = new ArrayList<>();
+ // RestResponse restResponse;
+ // GroupingDefinition grouping;
+ // String groupingName = productGroupingDefinition.getName();
+ // for (int i = 0; i < numOfGrouping; i++) {
+ // productGroupingDefinition.setName(groupingName+i);
+ // restResponse =
+ // CategoryRestUtils.createGrouping(productGroupingDefinition,
+ // productSubCategoryDefinition, productCategoryDefinition,
+ // sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ // grouping = ResponseParser.parseToObject(restResponse.getResponse(),
+ // GroupingDefinition.class);
+ // groupingList.add(grouping);
+ // }
+ // RestResponse getAllCategoriesRest =
+ // CategoryRestUtils.getAllCategories(sdncProductStrategistUserDetails,
+ // PRODUCT_COMPONENT_TYPE);
+ // assertEquals("Check response code after get all categories ",
+ // STATUS_CODE_SUCCESS, getAllCategoriesRest.getErrorCode().intValue());
+ // AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY,
+ // AUDIT_PRODUCT_TYPE, sdncProductStrategistUserDetails,
+ // STATUS_CODE_SUCCESS);
+ //
+ // for (GroupingDefinition group : groupingList) {
+ // CategoryValidationUtils.verifyGroupingExistInGetResponse(getAllCategoriesRest,
+ // productCategoryDefinition.getUniqueId(),
+ // productSubCategoryDefinition.getUniqueId(), group);
+ // }
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java
new file mode 100644
index 0000000000..dd96ebfc2f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/category/SubCategoriesTest.java
@@ -0,0 +1,1907 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.category;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.RESOURCE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.SERVICE_COMPONENT_TYPE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.CategoryValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class SubCategoriesTest extends ComponentBaseTest {
+
+ protected static final String ADD_SUB_CATEGORY = "AddSubCategory";
+ protected static final String CATEGORY = "category";
+ protected static final String SUB_CATEGORY = "sub-category";
+
+ protected static final String AUDIT_SERVICE_TYPE = "Service";
+ protected static final String AUDIT_RESOURCE_TYPE = "Resource";
+ protected static final String AUDIT_PRODUCT_TYPE = "Product";
+ protected static final String GET_CATEGORY_HIERARCHY = "GetCategoryHierarchy";
+ protected static User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected static User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected static User sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected static User sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ protected static User sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ protected static User sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ protected static User sdncProductManagerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ protected static User sdncProductStrategistUserDetails = ElementFactory
+ .getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+
+ public SubCategoriesTest() {
+ super(name, SubCategoriesTest.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ private CategoryDefinition resourceCategoryDefinition;
+ private CategoryDefinition resourceCategoryDefinition1;
+ private CategoryDefinition serviceCategoryDefinition;
+ private CategoryDefinition productCategoryDefinition;
+ private CategoryDefinition productCategoryDefinition1;
+ private CategoryDefinition resourceCategoryDefinition100;
+ private CategoryDefinition productCategoryDefinition200;
+
+ private SubCategoryDefinition resourceSubCategoryDefinition;
+ private SubCategoryDefinition resourceSubCategoryDefinition1;
+ private SubCategoryDefinition serviceSubCategoryDefinition;
+ private SubCategoryDefinition productSubCategoryDefinition;
+ private SubCategoryDefinition productSubCategoryDefinition1;
+
+ @BeforeMethod
+ public void init() throws Exception {
+
+ // Category setup
+ resourceCategoryDefinition = new CategoryDefinition();
+ resourceCategoryDefinition1 = new CategoryDefinition();
+ serviceCategoryDefinition = new CategoryDefinition();
+ productCategoryDefinition = new CategoryDefinition();
+ productCategoryDefinition1 = new CategoryDefinition();
+ resourceCategoryDefinition100 = new CategoryDefinition(); // for
+ // negative
+ // tests
+ productCategoryDefinition200 = new CategoryDefinition(); // for negative
+ // tests
+
+ resourceCategoryDefinition.setName("Category1");
+ resourceCategoryDefinition1.setName("Category2");
+ serviceCategoryDefinition.setName("Category1");
+ productCategoryDefinition.setName("Category2");
+ productCategoryDefinition1.setName("Category3");
+ resourceCategoryDefinition100.setName("Category100");
+ productCategoryDefinition200.setName("Category100");
+
+ // Subcategory setup
+ resourceSubCategoryDefinition = new SubCategoryDefinition();
+ resourceSubCategoryDefinition1 = new SubCategoryDefinition();
+ serviceSubCategoryDefinition = new SubCategoryDefinition();
+ productSubCategoryDefinition = new SubCategoryDefinition();
+ productSubCategoryDefinition1 = new SubCategoryDefinition();
+
+ resourceSubCategoryDefinition.setName("Resource-subcat");
+ // Service sub - for negative testing since it's not allowed
+ serviceSubCategoryDefinition.setName("Service-subcat");
+ productSubCategoryDefinition.setName("Product-subcat");
+
+ // Init resource category
+ RestResponse createCategory = CategoryRestUtils.createCategory(resourceCategoryDefinition, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ CategoryDefinition category = ResponseParser.parseToObject(createCategory.getResponse(),
+ CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", resourceCategoryDefinition.getName(),
+ category.getName());
+ resourceCategoryDefinition = category;
+
+ // Init resource category1
+ createCategory = CategoryRestUtils.createCategory(resourceCategoryDefinition1, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", resourceCategoryDefinition1.getName(),
+ category.getName());
+ resourceCategoryDefinition1 = category;
+
+ // Init service category
+ createCategory = CategoryRestUtils.createCategory(serviceCategoryDefinition, sdncAdminUserDetails,
+ SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", serviceCategoryDefinition.getName(),
+ category.getName());
+ serviceCategoryDefinition = category;
+
+ // Init product category
+ createCategory = CategoryRestUtils.createCategory(productCategoryDefinition, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productCategoryDefinition.getName(),
+ category.getName());
+ productCategoryDefinition = category;
+
+ // Init product category1
+ createCategory = CategoryRestUtils.createCategory(productCategoryDefinition1, sdncProductStrategistUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create category", STATUS_CODE_CREATED,
+ createCategory.getErrorCode().intValue());
+ category = ResponseParser.parseToObject(createCategory.getResponse(), CategoryDefinition.class);
+ assertEquals("Check category name after creating category ", productCategoryDefinition1.getName(),
+ category.getName());
+ productCategoryDefinition1 = category;
+
+ }
+
+ @Test
+ public void createResourceSubCategorySuccess() throws Exception {
+ createSubCategorySuccess(resourceCategoryDefinition, resourceSubCategoryDefinition, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void createProductSubCategorySuccess() throws Exception {
+ createSubCategorySuccess(productCategoryDefinition, productSubCategoryDefinition,
+ sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createProductSubCategoryTwoCategoriesCaseInsensitive() throws Exception {
+ String componentType = PRODUCT_COMPONENT_TYPE;
+ String auditType = AUDIT_PRODUCT_TYPE;
+ User user = sdncProductStrategistUserDetails;
+ // Create product sub Category2-->Product-subcat
+ createSubCategorySuccess(productCategoryDefinition, productSubCategoryDefinition, user, componentType,
+ auditType);
+ DbUtils.deleteFromEsDbByPattern("_all");
+
+ // Create product sub Category3-->PRoDUCT-SUBcat
+ // Should be created Category3-->Product-subcat
+ productSubCategoryDefinition1.setName("PRoDUCT-SUBcat");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1,
+ productCategoryDefinition1, user, componentType);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(user, componentType);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ productSubCategoryDefinition1.setName(productSubCategoryDefinition.getName());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition1.getUniqueId(), productSubCategoryDefinition1);
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition1,
+ productSubCategoryDefinition1, user, STATUS_CODE_CREATED, auditType);
+ }
+
+ // Benny
+ @Test
+ public void createResourceSubCategoryAlreadyExistInDifferentResourceCategory() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ resourceSubCategoryDefinition1.setName("ResourcE-subCat");
+ createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition1,
+ resourceCategoryDefinition1, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition1.setName(resourceSubCategoryDefinition.getName());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition1.getUniqueId(), resourceSubCategoryDefinition1); // also
+ // set
+ // catalog
+ // uniqeId
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition1,
+ resourceSubCategoryDefinition1, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void createProductSubCategoryAlreadyExistInDifferentProductCategory() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED,
+ AUDIT_PRODUCT_TYPE);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ productSubCategoryDefinition1.setName("PRoDUCT-SUBcat");
+ createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1,
+ productCategoryDefinition1, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ productSubCategoryDefinition1.setName(productSubCategoryDefinition.getName());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition1.getUniqueId(), productSubCategoryDefinition1); // also
+ // set
+ // catalog
+ // uniqeId
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition1,
+ productSubCategoryDefinition1, sdncProductStrategistUserDetails, STATUS_CODE_CREATED,
+ AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createResourceSubCategoryAlreadyExistInCategory() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ resourceSubCategoryDefinition1.setName("ResourcE-subCat");
+ createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition1,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS,
+ createSubCategoryRest.getErrorCode().intValue());
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition1, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, STATUS_CODE_ALREADY_EXISTS,
+ AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, resourceSubCategoryDefinition1.getName(),
+ resourceCategoryDefinition.getName());
+ }
+
+ @Test
+ public void createProductSubCategoryAlreadyExistInCategory() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED,
+ AUDIT_PRODUCT_TYPE);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ productSubCategoryDefinition1.setName("ProducT-subCat");
+ createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition1,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_ALREADY_EXISTS,
+ createSubCategoryRest.getErrorCode().intValue());
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition1, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY, STATUS_CODE_ALREADY_EXISTS, AUDIT_PRODUCT_TYPE,
+ AUDIT_PRODUCT_TYPE, productSubCategoryDefinition1.getName(), productCategoryDefinition.getName());
+ }
+
+ @Test
+ public void addSameNormalizedSubCategoryNameForRecourceAndProductCategory() throws Exception {
+ // add sub-categoty name "SubCaT" to resource category
+ // add sub-categoty name "SUbcAt" to product category
+ resourceSubCategoryDefinition.setName("SubCaT"); // normalized 'subcat'
+ productSubCategoryDefinition.setName("SUbcAt"); // normalized 'subcat'
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails, STATUS_CODE_CREATED,
+ AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createResourceSubCategoryByNonAdminUser() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncTesterUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION,
+ STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void createResourceSubCategoryByProducStrategistUser() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncProductStrategistUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.RESTRICTED_OPERATION,
+ STATUS_CODE_RESTRICTED_OPERATION, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void createProductSubCategoryByNonProducStrategistUser() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncDesignerUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION,
+ STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE);
+ }
+
+ @Test
+ public void createProductSubCategoryByAdminUser() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncAdminUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_RESTRICTED_OPERATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.RESTRICTED_OPERATION,
+ STATUS_CODE_RESTRICTED_OPERATION, AUDIT_PRODUCT_TYPE);
+ }
+
+ // @Ignore("DE176245")
+ @Test
+ public void createResourceSubCategoryForNonExistingComponentType() throws Exception {
+ String nonSupportedComponentType = "NonExistingComponentType"; // instead
+ // resource/product
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, nonSupportedComponentType);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType);
+ }
+
+ // @Ignore("DE176245")
+ @Test
+ public void createProductSubCategoryForNonExistingComponentType() throws Exception {
+ String nonSupportedComponentType = "NonExistingComponentType"; // instead
+ // resource/product
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, nonSupportedComponentType);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, nonSupportedComponentType);
+ }
+
+ @Test
+ public void createServiceSubCategoryByAdmin() throws Exception {
+ // Service doesn't have sub-category
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ resourceCategoryDefinition.setName(resourceCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void createServiceSubCategoryByProductStrategist() throws Exception {
+ // Service doesn't have sub-category
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition, sdncProductStrategistUserDetails, SERVICE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation
+ productCategoryDefinition.setName(productCategoryDefinition.getUniqueId());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails, ActionStatus.INVALID_CONTENT,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_SERVICE_TYPE);
+ }
+
+ @Test
+ public void createResourceSubCategoryForNonExistingCategory() throws Exception {
+ resourceCategoryDefinition100.setUniqueId(resourceCategoryDefinition100.getName());
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition100, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND,
+ createSubCategoryRest.getErrorCode().intValue());
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition100,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_CATEGORY_NOT_FOUND,
+ STATUS_CODE_NOT_FOUND, AUDIT_RESOURCE_TYPE, RESOURCE_COMPONENT_TYPE, CATEGORY, "");
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition100.getUniqueId(), resourceSubCategoryDefinition);
+ }
+
+ @Test
+ public void createProductSubCategoryForNonExistingCategory() throws Exception {
+ productCategoryDefinition200.setUniqueId(productCategoryDefinition200.getName());
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(productSubCategoryDefinition,
+ productCategoryDefinition200, sdncProductStrategistUserDetails, PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_NOT_FOUND,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ PRODUCT_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ productCategoryDefinition200.getUniqueId(), productSubCategoryDefinition);
+ // Audit validation // need to change ActionStatus
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, productCategoryDefinition200,
+ productSubCategoryDefinition, sdncProductStrategistUserDetails,
+ ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, STATUS_CODE_NOT_FOUND, AUDIT_PRODUCT_TYPE,
+ PRODUCT_COMPONENT_TYPE, CATEGORY, "");
+ }
+
+ // pass
+ @Test
+ public void subCategoryAllowedcharacters_01() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE-");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition); // also
+ // set
+ // catalog
+ // uniqeId
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ // pass
+ @Test
+ public void subCategoryAllowedcharacters_02() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE+");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_03() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE&");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_04() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE.");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_05() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE'");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_06() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE=");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_07() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE:");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_08() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE@");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_09() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE_");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_10() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE#");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_11() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE d");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("1234AbcdE D");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryAllowedcharacters_12() throws Exception {
+ resourceSubCategoryDefinition.setName("1234AbcdE &_=+.-'#:@ d");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("1234AbcdE &_=+.-'#:@ D");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveSpaceFromBeginning() throws Exception {
+ resourceSubCategoryDefinition.setName(" Category01");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveSpaceFromEnd() throws Exception {
+ resourceSubCategoryDefinition.setName("Category01 ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category01");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraSpace() throws Exception {
+ resourceSubCategoryDefinition.setName("Category 02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category 02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraAmpersand() throws Exception {
+ resourceSubCategoryDefinition.setName("Category&& &02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category& &02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraDash() throws Exception {
+ resourceSubCategoryDefinition.setName("CategorY-- --02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("CategorY- -02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraPlus() throws Exception {
+ resourceSubCategoryDefinition.setName("CateGory++++ +02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("CateGory+ +02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraPeriod() throws Exception {
+ resourceSubCategoryDefinition.setName("Category.... .02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category. .02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraApostrophe() throws Exception {
+ resourceSubCategoryDefinition.setName("CaTegory''' '02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("CaTegory' '02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraHashtag() throws Exception {
+ resourceSubCategoryDefinition.setName("Category### #02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category# #02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtrEequal() throws Exception {
+ resourceSubCategoryDefinition.setName("Category=== =02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category= =02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtrColon() throws Exception {
+ resourceSubCategoryDefinition.setName("Category::: :02");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category: :02");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtrAt() throws Exception {
+ resourceSubCategoryDefinition.setName("Category@@@ @a2");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category@ @a2");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryRemoveExtraUnderscore() throws Exception {
+ resourceSubCategoryDefinition.setName("Category___ _22");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Category_ _22");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryFirstWordStartWithNumber() throws Exception {
+ resourceSubCategoryDefinition.setName("1Category one");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("1Category One");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ // Bug
+ // Desc=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
+ // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = "&AbcD123" GROUPING_NAME
+ // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4556: Error:
+ // Invalid Resource sub-category name format.">
+ // DESC=SVC4556: Error: InvalidResourcesub-categorynameformat.,
+ // @Ignore
+ @Test
+ public void subCategoryFirstWordStartWithNonAlphaNumeric() throws Exception {
+ // The first word must start with an alpha-numeric character [a-Z A..Z,
+ // 0..9]
+ char invalidChars[] = { '&', '-', '+', '.', '\'', '#', '=', ':', '@', '_' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ resourceSubCategoryDefinition.setName(invalidChars[i] + "AbcD123");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT,
+ AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY);
+
+ }
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_01() throws Exception {
+ resourceSubCategoryDefinition.setName("At and T");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("At & T");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_02() throws Exception {
+ resourceSubCategoryDefinition.setName("At and t");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("At & T");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_03() throws Exception {
+ resourceSubCategoryDefinition.setName("Atand T");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_04() throws Exception {
+ resourceSubCategoryDefinition.setName("At andT");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("At AndT");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_05() throws Exception {
+ resourceSubCategoryDefinition.setName(" and AttT");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("And AttT");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_06() throws Exception {
+ resourceSubCategoryDefinition.setName("AttT and ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("AttT And");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryReplaceAndWithAmpersand_07() throws Exception {
+ resourceSubCategoryDefinition.setName(" and a");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("And a");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationMaxLength() throws Exception {
+ resourceSubCategoryDefinition.setName("AsdfghjQ234567890@#.&:+-_");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationMaxLengthAfterNormalization() throws Exception {
+ resourceSubCategoryDefinition.setName(" A jQ234 @@@___ +++ At and T and and ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("A JQ234 @_ + At & T & And");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ // bug :
+ // Desc=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
+ // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = " AbdfghBCVa jQ234 @@___
+ // +++ At and T " GROUPING_NAME = "" RESOURCE_TYPE = "Resource" STATUS =
+ // "400" DESC = "SVC4555: Error: Invalid Resource sub-category name
+ // length.">
+ @Test
+ public void subCategoryNameValidationExceedMaxLengthAfterNormalization() throws Exception {
+ resourceSubCategoryDefinition.setName(" AbdfghBCVa jQ234 @@___ +++ At and T ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY);
+ }
+
+ @Test
+ public void subCategoryNameValidationMinLengthAfterNormalization() throws Exception {
+ resourceSubCategoryDefinition.setName(" AT&&&&&&&&&T ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("AT&T");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ // bug
+ // Desc=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
+ // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = " A and T " GROUPING_NAME
+ // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4555: Error:
+ // Invalid Resource sub-category name length.">
+ @Test
+ public void subCategoryNameValidationLessThanMinLengthAfterNormalization() throws Exception {
+ resourceSubCategoryDefinition.setName(" A&&&T ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY);
+ }
+
+ @Test
+ public void subCategoryNameIsEmpty() throws Exception {
+ resourceSubCategoryDefinition.setName("");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT,
+ STATUS_CODE_INVALID_CONTENT, AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY);
+ }
+
+ // bug
+ // Desc=<ACTION = "AddSubCategory" MODIFIER = "Jimmy Hendrix(jh0003)"
+ // CATEGORY_NAME = "Category1" SUB_CATEGORY_NAME = "AbcD123~" GROUPING_NAME
+ // = "" RESOURCE_TYPE = "Resource" STATUS = "400" DESC = "SVC4556: Error:
+ // Invalid Resource sub-category name format.">
+ @Test
+ public void subCategoryNameValidationInvalidCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ resourceSubCategoryDefinition.setName("AbcD123" + invalidChars[i]);
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_INVALID_CONTENT,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditFailure(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, STATUS_CODE_INVALID_CONTENT,
+ AUDIT_RESOURCE_TYPE, AUDIT_RESOURCE_TYPE, SUB_CATEGORY);
+ }
+ }
+
+ @Test
+ public void subCategoryNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception {
+ resourceSubCategoryDefinition.setName("beNNy shaY michEl");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("BeNNy ShaY MichEl");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_01() throws Exception {
+ resourceSubCategoryDefinition.setName(" bank OF america ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Bank of America");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_02() throws Exception {
+ resourceSubCategoryDefinition.setName("THE america bank ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("THE America Bank");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_03() throws Exception {
+ resourceSubCategoryDefinition.setName(" A bank OF america ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("A Bank of America");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_04() throws Exception {
+ resourceSubCategoryDefinition.setName(" bank america is A big ban ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Bank America Is a Big Ban");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_05() throws Exception {
+ resourceSubCategoryDefinition.setName(" aN apple comPany inC ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("AN Apple ComPany InC");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_06() throws Exception {
+ resourceSubCategoryDefinition.setName(" eat AN apple ANAN");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Eat an Apple ANAN");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_07() throws Exception {
+ resourceSubCategoryDefinition.setName(" united states OF americA ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("United States of AmericA");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_08() throws Exception {
+ resourceSubCategoryDefinition.setName(" oF united states OF amer ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("OF United States of Amer");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_09() throws Exception {
+ resourceSubCategoryDefinition.setName(" to Apple TO at&T TOO ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("To Apple to At&T TOO");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_10() throws Exception {
+ resourceSubCategoryDefinition.setName(" eat apple AS you liiikeas ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Eat Apple as You Liiikeas");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_11() throws Exception {
+ resourceSubCategoryDefinition.setName(" as you may want ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("As You May Want");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_12() throws Exception {
+ resourceSubCategoryDefinition.setName(" the bank OF america ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("The Bank of America");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_13() throws Exception {
+ resourceSubCategoryDefinition.setName(" To tel-toto ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("To Tel-toto");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void subCategoryNameValidationConjunctions_14() throws Exception {
+ resourceSubCategoryDefinition.setName(" tel-aviv To la ");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ resourceSubCategoryDefinition.setName("Tel-aviv to La");
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, resourceSubCategoryDefinition);
+
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, resourceCategoryDefinition,
+ resourceSubCategoryDefinition, sdncAdminUserDetails, STATUS_CODE_CREATED, AUDIT_RESOURCE_TYPE);
+ }
+
+ @Test
+ public void createSubCategoryHttpCspUserIdHeaderIsMissing() throws Exception {
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategoryHttpCspAtuUidIsMissing(
+ resourceSubCategoryDefinition, resourceCategoryDefinition, sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_MISSING_INFORMATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_SUB_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(resourceCategoryDefinition.getUniqueId());
+ // String subCategoryName = (resourceSubCategoryDefinition != null ?
+ // resourceSubCategoryDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(resourceSubCategoryDefinition.getName());
+ // String groupingName = (groupingDefinition != null ?
+ // groupingDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_RESOURCE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_SUB_CATEGORY);
+ }
+
+ @Test
+ public void createSubCategoryHttpCspUserIdIsEmpty() throws Exception {
+ User sdncAdminUserDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncAdminUserDetails1.setUserId("");
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails1, RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_MISSING_INFORMATION,
+ createSubCategoryRest.getErrorCode().intValue());
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryNotExistsInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), resourceSubCategoryDefinition);
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(ADD_SUB_CATEGORY);
+ expectedCatrgoryAuditJavaObject.setModifier("");
+ expectedCatrgoryAuditJavaObject.setCategoryName(resourceCategoryDefinition.getUniqueId());
+ // String subCategoryName = (resourceSubCategoryDefinition != null ?
+ // resourceSubCategoryDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(resourceSubCategoryDefinition.getName());
+ // String groupingName = (groupingDefinition != null ?
+ // groupingDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setGroupingName("");
+ expectedCatrgoryAuditJavaObject.setResourceType(AUDIT_RESOURCE_TYPE);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(STATUS_CODE_MISSING_INFORMATION));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, ADD_SUB_CATEGORY);
+ }
+
+ ////////////////////////////////////////////////////////////
+ private void createSubCategorySuccess(CategoryDefinition categoryDefinition,
+ SubCategoryDefinition subCategoryDefinition, User sdncAdminUserDetails, String componentType,
+ String auditType) throws Exception {
+
+ RestResponse createSubCategoryRest = CategoryRestUtils.createSubCategory(subCategoryDefinition,
+ categoryDefinition, sdncAdminUserDetails, componentType);
+ assertEquals("Check response code after create Sub category", STATUS_CODE_CREATED,
+ createSubCategoryRest.getErrorCode().intValue());
+ CategoryValidationUtils.validateCreateSubCategoryResponse(createSubCategoryRest, subCategoryDefinition);
+ // Audit validation
+ AuditValidationUtils.subCategoryAuditSuccess(ADD_SUB_CATEGORY, categoryDefinition, subCategoryDefinition,
+ sdncAdminUserDetails, STATUS_CODE_CREATED, auditType);
+ // get service category and validate that category added as defined
+ // (also set catalog uniqeId)
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails, componentType);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ categoryDefinition.getUniqueId(), subCategoryDefinition); // also
+ // set
+ // catalog
+ // uniqeId
+ }
+
+ @Test
+ public void getResourceCategoryHierarchySuccessFlow() throws Exception {
+ int numOfSubCategories = 3;
+ List<SubCategoryDefinition> subCategories = new ArrayList();
+ RestResponse restResponse;
+ SubCategoryDefinition subCategory;
+ String subName = resourceSubCategoryDefinition.getName();
+ for (int i = 0; i < numOfSubCategories; i++) {
+ resourceSubCategoryDefinition.setName(subName + i);
+ restResponse = CategoryRestUtils.createSubCategory(resourceSubCategoryDefinition,
+ resourceCategoryDefinition, sdncAdminUserDetails, RESOURCE_COMPONENT_TYPE);
+ subCategory = ResponseParser.parseToObject(restResponse.getResponse(), SubCategoryDefinition.class);
+ subCategories.add(subCategory);
+ }
+ RestResponse getAllCategoriesRest = CategoryRestUtils.getAllCategories(sdncAdminUserDetails,
+ RESOURCE_COMPONENT_TYPE);
+ assertEquals("Check response code after get all categories ", STATUS_CODE_SUCCESS,
+ getAllCategoriesRest.getErrorCode().intValue());
+ AuditValidationUtils.GetCategoryHierarchyAuditSuccess(GET_CATEGORY_HIERARCHY, AUDIT_RESOURCE_TYPE,
+ sdncAdminUserDetails, STATUS_CODE_SUCCESS);
+ for (SubCategoryDefinition sub : subCategories) {
+ CategoryValidationUtils.verifySubCategoryExistInGetResponse(getAllCategoriesRest,
+ resourceCategoryDefinition.getUniqueId(), sub);
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
new file mode 100644
index 0000000000..418e8f6dc8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/CRUDExternalAPI.java
@@ -0,0 +1,1011 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpResponseException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.BasicResponseHandler;
+import org.apache.http.util.EntityUtils;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.json.simple.parser.ParseException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+
+import fj.data.Either;
+
+public class CRUDExternalAPI extends ComponentBaseTest {
+
+ private static Logger log = LoggerFactory.getLogger(CRUDExternalAPI.class.getName());
+ protected static final String UPLOAD_ARTIFACT_PAYLOAD = "UHVUVFktVXNlci1LZXktRmlsZS0yOiBzc2gtcnNhDQpFbmNyeXB0aW9uOiBhZXMyNTYtY2JjDQpDb21tZW5wOA0K";
+ protected static final String UPLOAD_ARTIFACT_NAME = "TLV_prv.ppk";
+
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+ protected Gson gson = new Gson();
+ protected JSONParser jsonParser = new JSONParser();
+
+ protected String serviceVersion;
+ protected ResourceReqDetails resourceDetails;
+ protected User sdncUserDetails;
+ protected ServiceReqDetails serviceDetails;
+
+ @BeforeMethod
+ public void init() throws Exception {
+ AtomicOperationUtils.createDefaultConsumer(true);
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CRUDExternalAPI() {
+ super(name, CRUDExternalAPI.class.getName());
+
+ }
+
+ @DataProvider(name = "uploadArtifactOnVFViaExternalAPI")
+ public static Object[][] dataProviderUploadArtifactOnVFViaExternalAPI() {
+ return new Object[][] { { LifeCycleStatesEnum.CHECKIN, "DCAE_JSON" },
+ { LifeCycleStatesEnum.CHECKOUT, "DCAE_POLICY" }, { LifeCycleStatesEnum.CHECKOUT, "DCAE_EVENT" },
+ { LifeCycleStatesEnum.CHECKOUT, "APPC_CONFIG" }, { LifeCycleStatesEnum.CHECKOUT, "DCAE_DOC" },
+ { LifeCycleStatesEnum.CHECKOUT, "DCAE_TOSCA" }, { LifeCycleStatesEnum.CHECKOUT, "YANG_XML" },
+ { LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG" }, { LifeCycleStatesEnum.CHECKOUT, "VF_LICENSE" },
+ { LifeCycleStatesEnum.CHECKOUT, "VENDOR_LICENSE" },
+ { LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE" },
+ { LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC" }, { LifeCycleStatesEnum.CHECKOUT, "OTHER" } };
+ }
+
+ // External API
+ // Upload artifact on VF via external API - happy flow
+ @Test(dataProvider = "uploadArtifactOnVFViaExternalAPI")
+ public void uploadArtifactOnVFViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType)
+ throws Exception {
+ // Method passed variable
+ // artifactType = "YANG_XML";
+ // chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
+
+ // String operationType = "Upload";
+ UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
+ String specificUser = "DESIGNER";
+
+ Component resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser, chosenLifeCycleState);
+
+ String resourceUUID = resourceDetails.getUUID();
+ System.out.println("Resource UUID: " + resourceUUID);
+
+ // get artifact data
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
+
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())), artifactReqDetails);
+
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+
+ // ArtifactDefinition artifactJavaObject =
+ // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
+ // AuditingActionEnum action =
+ // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
+ // ExpectedExternalAudit expectedExternalAudit =
+ // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
+ // action, artifactJavaObject, resourceUUID);
+ // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
+ // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
+ }
+
+ @DataProvider(name = "uploadArtifactOnServiceViaExternalAPI")
+ public static Object[][] dataProviderUploadArtifactOnServiceViaExternalAPI() {
+ return new Object[][] {
+ // {LifeCycleStatesEnum.CHECKOUT, "YANG_XML"},
+ // {LifeCycleStatesEnum.CHECKOUT, "VNF_CATALOG"},
+ // {LifeCycleStatesEnum.CHECKOUT, "MODEL_INVENTORY_PROFILE"},
+ // {LifeCycleStatesEnum.CHECKOUT, "MODEL_QUERY_SPEC"},
+ // {LifeCycleStatesEnum.CHECKOUT, "OTHER"},
+ { LifeCycleStatesEnum.CHECKIN, "YANG_XML" }, { LifeCycleStatesEnum.CHECKIN, "VNF_CATALOG" },
+ { LifeCycleStatesEnum.CHECKIN, "MODEL_INVENTORY_PROFILE" },
+ { LifeCycleStatesEnum.CHECKIN, "MODEL_QUERY_SPEC" }, { LifeCycleStatesEnum.CHECKIN, "OTHER" },
+ { LifeCycleStatesEnum.CERTIFICATIONREQUEST, "YANG_XML" },
+ { LifeCycleStatesEnum.CERTIFICATIONREQUEST, "VNF_CATALOG" },
+ { LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_INVENTORY_PROFILE" },
+ { LifeCycleStatesEnum.CERTIFICATIONREQUEST, "MODEL_QUERY_SPEC" },
+ { LifeCycleStatesEnum.CERTIFICATIONREQUEST, "OTHER" } };
+ }
+
+ @Test(dataProvider = "uploadArtifactOnServiceViaExternalAPI")
+ public void uploadArtifactOnServiceViaExternalAPI(LifeCycleStatesEnum chosenLifeCycleState, String artifactType)
+ throws Exception {
+ Component resourceDetails = getComponentInTargetLifeCycleState("service", UserRoleEnum.DESIGNER,
+ chosenLifeCycleState);
+ double resourceVersion = Double.parseDouble(resourceDetails.getVersion());
+
+ // get artifact data
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
+
+ System.out.println("Service UUID: " + resourceDetails.getUUID());
+ System.out.println("Service Version: " + resourceVersion);
+ System.out.println("Service life cycle state: " + chosenLifeCycleState);
+ System.out.println("Artifact Type: " + artifactReqDetails.getArtifactType());
+
+ RestResponse restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), artifactReqDetails);
+
+ // Check response of external API
+ Integer responseCode = restResponse.getErrorCode();
+ Integer expectedCode = 200;
+ Assert.assertEquals(responseCode, expectedCode, "Response code is not correct.");
+
+ // TODO: Check auditing for upload opeartion
+ // ArtifactDefinition artifactJavaObject =
+ // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
+ // AuditingActionEnum action =
+ // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
+ // ExpectedExternalAudit expectedExternalAudit =
+ // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
+ // action, artifactJavaObject, resourceUUID);
+ // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
+ // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
+
+ // Check Service version (increase by one if not in checkout)
+ if (!chosenLifeCycleState.equals(LifeCycleStatesEnum.CHECKOUT)) {
+ double resourceNewVersion = Double.parseDouble(resourceDetails.getVersion());
+
+ System.out.println(resourceVersion);
+ System.out.println(resourceNewVersion);
+ }
+ }
+
+ @Test
+ public void artifactOperationOnRIViaExternalAPI() throws Exception {
+ // Method passed variable
+ String operationType = "Upload";
+ LifeCycleStatesEnum chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
+ UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
+ String specificUser = "DESIGNER";
+ String artifactType = "OTHER";
+
+ Component resourceDetails = getComponentInTargetLifeCycleState("service", creatorUser, chosenLifeCycleState);
+ Component resourceInstanceDetails = getComponentInTargetLifeCycleState("vf", creatorUser, chosenLifeCycleState);
+ ComponentInstance componentResourceInstanceDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceInstanceDetails, resourceDetails,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+
+ String resourceUUID = resourceDetails.getUUID();
+ System.out.println("Resource UUID: " + resourceUUID);
+
+ // get artifact data
+ ArtifactReqDetails artifactReqDetails = ElementFactory.getArtifactByType("Abcd", artifactType, true);
+
+ RestResponse restResponse = null;
+
+ if (operationType.toLowerCase().equals("upload")) {
+ restResponse = ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())),
+ artifactReqDetails);
+ System.out.println("1234");
+ }
+
+ ArtifactDefinition artifactJavaObject = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
+ AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
+ ExpectedExternalAudit expectedExternalAudit = ElementFactory.getDefaultExternalArtifactAuditSuccess(
+ AssetTypeEnum.RESOURCES, action, artifactJavaObject, resourceUUID);
+ AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
+ AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
+ }
+
+ // @Test
+ // public void artifactViaExternalAPI() throws Exception {
+ // // Method passed variable
+ // String operationType = "Upload";
+ // String assetType = "vf";
+ // LifeCycleStatesEnum chosenLifeCycleState = LifeCycleStatesEnum.CHECKOUT;
+ // String componentInstanceAssetType = "vf";
+ // LifeCycleStatesEnum componentInstanceChosenLifeCycleState =
+ // LifeCycleStatesEnum.CHECKOUT;
+ // UserRoleEnum creatorUser = UserRoleEnum.DESIGNER;
+ // String specificUser = "DESIGNER";
+ // String artifactType = "HEAT";
+ //
+ //
+ // Component resourceDetails = null;
+ // Component resourceInstanceDetails = null;
+ // ComponentInstance componentResourceInstanceDetails = null;
+ //
+ // String resourceUUID = null;
+ // String resourceType = null;
+ // String resourceInstanceName = null;
+ //
+ // // Create resource & resource instance of requested type and state
+ // if (assetType.toLowerCase().equals("vf")) {
+ // resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser,
+ // chosenLifeCycleState);
+ // } else if (assetType.toLowerCase().equals("service")) {
+ // resourceDetails = getComponentInTargetLifeCycleState("service",
+ // creatorUser, chosenLifeCycleState);
+ // } else if (assetType.toLowerCase().equals("ri")) {
+ // resourceInstanceDetails = getComponentInTargetLifeCycleState("vf",
+ // creatorUser, chosenLifeCycleState);
+ // if(componentInstanceAssetType.toLowerCase().equals("vf")) {
+ // resourceDetails = getComponentInTargetLifeCycleState("vf", creatorUser,
+ // componentInstanceChosenLifeCycleState);
+ // componentResourceInstanceDetails =
+ // AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails,
+ // resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ // } else if (componentInstanceAssetType.toLowerCase().equals("service")) {
+ // resourceDetails = getComponentInTargetLifeCycleState("service",
+ // creatorUser, componentInstanceChosenLifeCycleState);
+ // componentResourceInstanceDetails =
+ // AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceInstanceDetails,
+ // resourceDetails, UserRoleEnum.DESIGNER, true).left().value();
+ // } else {
+ // Assert.assertEquals(false, true, "Component instance asset type is
+ // wrong.");
+ // }
+ // } else {
+ // Assert.assertEquals(false, true, "Asset type is wrong.");
+ // }
+ //
+ //
+ // // print uuid & resource instance name
+ // if (assetType.toLowerCase().equals("ri")) {
+ // resourceUUID = resourceDetails.getUUID();
+ // resourceInstanceName =
+ // componentResourceInstanceDetails.getNormalizedName();
+ //
+ //
+ // System.out.println("Resource UUID: " + resourceUUID);
+ // System.out.println("Resource instance name: " + resourceInstanceName);
+ // System.out.println("Resource type: " + resourceType);
+ // } else {
+ // resourceUUID = resourceDetails.getUUID();
+ //
+ // System.out.println("Resource UUID: " + resourceUUID);
+ // System.out.println("Resource type: " + resourceType);
+ // }
+ //
+ // // get artifact data
+ // ArtifactReqDetails artifactReqDetails =
+ // ElementFactory.getArtifactByType("Abcd", artifactType, true);
+ //
+ //// RestResponse restResponse;
+ // // using rest external api
+ //// if(operationType.toLowerCase().equals("upload")) {
+ //// if (!assetType.toLowerCase().equals("ri")) {
+ // RestResponse restResponse =
+ // ArtifactRestUtils.externalAPIUploadArtifactOfTheAsset(resourceDetails,
+ // ElementFactory.getDefaultUser(UserRoleEnum.valueOf(specificUser.toUpperCase())),
+ // artifactReqDetails);
+ // System.out.println("1234");
+ //// } else {
+ ////
+ //// }
+ //// } else {
+ ////
+ //// }
+ //
+ // ArtifactDefinition artifactJavaObject =
+ // ResponseParser.convertArtifactDefinitionResponseToJavaObject(restResponse.getResponse());
+ //// AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
+ // AuditingActionEnum action = AuditingActionEnum.ARTIFACT_UPLOAD_BY_API;
+ // ExpectedExternalAudit expectedExternalAudit =
+ // ElementFactory.getDefaultExternalArtifactAuditSuccess(AssetTypeEnum.RESOURCES,
+ // action, artifactJavaObject, resourceUUID);
+ // AuditValidationUtils.validateExternalAudit(expectedExternalAudit,
+ // AuditingActionEnum.ARTIFACT_UPLOAD_BY_API.getName(), null);
+ //
+ //
+ //
+ //
+ // }
+ //
+
+ @Test
+ public void getResourceAssetMetadataWithNonCertifiedResourceInstancesAndArtifactsSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ // TODO
+ Either<ArtifactDefinition, RestResponse> artifactDefinition = AtomicOperationUtils
+ .uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF, UserRoleEnum.DESIGNER, true,
+ true);
+ resourceVF = ResponseParser.parseToObjectUsingMapper(
+ ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ // AuditValidationUtils.validateAudit(expectedAssetListAudit,
+ // AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+
+ }
+
+ public Component getComponentInTargetLifeCycleState(String componentType, UserRoleEnum creatorUser,
+ LifeCycleStatesEnum targetLifeCycleState) throws Exception {
+ Component resourceDetails = null;
+
+ if (componentType.toLowerCase().equals("vf")) {
+ Either<Resource, RestResponse> createdResource = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, creatorUser, true);
+ resourceDetails = createdResource.left().value();
+ resourceDetails = AtomicOperationUtils
+ .changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft();
+ } else {
+ Either<Service, RestResponse> createdResource = AtomicOperationUtils.createDefaultService(creatorUser,
+ true);
+ resourceDetails = createdResource.left().value();
+ resourceDetails = AtomicOperationUtils
+ .changeComponentState(resourceDetails, creatorUser, targetLifeCycleState, true).getLeft();
+ }
+
+ return resourceDetails;
+ }
+
+ // // External API - Download artifact for resource - negative test
+ // @Test
+ // public void k() throws Exception {
+ // Resource resourceDetailsVF;
+ // Either<Resource, RestResponse> createdResource =
+ // AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF,
+ // NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE,
+ // UserRoleEnum.DESIGNER, true);
+ // resourceDetailsVF = createdResource.left().value();
+ // ArtifactDefinition heatArtifact =
+ // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT,
+ // resourceDetailsVF, UserRoleEnum.DESIGNER, true, true).left().value();
+ // resourceDetails = new ResourceReqDetails(resourceDetailsVF);
+ //
+ // String resourceUUID = resourceDetailsVF.getUUID();
+ // String artifactUUID = heatArtifact.getArtifactUUID();
+ //
+ // System.out.println("Resource UUID: " + resourceUUID);
+ // System.out.println("Artifact UUID: " + artifactUUID);
+ //
+ // RestResponse restResponse =
+ // ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID,
+ // "dfsgfdsg324", ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ // "Resource");
+ //
+ // Integer responseCode = restResponse.getErrorCode();
+ // Integer expectedCode = 200;
+ // Assert.assertEquals(responseCode,expectedCode, "Response code is not
+ // correct.");
+ // }
+ //
+ //
+ //
+ //
+ //
+ // // External API - Download artifact for service - negative test
+ // @Test
+ // public void downloadArtifactFromServiceViaExternalAPI() throws Exception
+ // {
+ //
+ // Service resourceDetailsService;
+ // Either<Service, RestResponse> createdResource =
+ // AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
+ // resourceDetailsService = createdResource.left().value();
+ //
+ // ArtifactDefinition heatArtifact =
+ // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER,
+ // resourceDetailsService, UserRoleEnum.DESIGNER, true,
+ // true).left().value();
+ //
+ // String resourceUUID = resourceDetailsService.getUUID();
+ // String artifactUUID = heatArtifact.getArtifactUUID();
+ //
+ // System.out.println("Resource UUID: " + resourceUUID);
+ // System.out.println("Artifact UUID: " + artifactUUID);
+ //
+ // RestResponse restResponse =
+ // ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID,
+ // artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ // "Service");
+ //
+ // Integer responseCode = restResponse.getErrorCode();
+ // Integer expectedCode = 200;
+ // Assert.assertEquals(responseCode,expectedCode, "Response code is not
+ // correct.");
+ //
+ // String response = restResponse.getResponse();
+ //
+ // String payloadData =
+ // "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ // String decodedPaypload = Decoder.decode(payloadData);
+ //
+ // Assert.assertEquals(response, decodedPaypload, "Response deployment
+ // artifact not correct.");
+ //
+ // String auditAction = "ArtifactDownload";
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new
+ // ExpectedResourceAuditJavaObject();
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceName(resourceDetailsService.getName());
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setStatus("200");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ //
+ // expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
+ // String resource_url =
+ // String.format("/asdc/v1/catalog/services/%s/artifacts/%s", resourceUUID,
+ // artifactUUID);
+ // expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+ //
+ // AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ // }
+ //
+ //
+ //
+ //
+ //
+ //
+ // // External API - Download ComponentInstance artifact of service -
+ // negative test
+ // @Test
+ // public void
+ // downloadArtifactOfComponentInstanceFromServiceViaExternalAPI() throws
+ // Exception {
+ //
+ // Either<Resource, RestResponse> resourceDetailsVF_01e =
+ // AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF,
+ // NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE,
+ // UserRoleEnum.DESIGNER, true);
+ // Component resourceDetailsVF_01 = resourceDetailsVF_01e.left().value();
+ // ArtifactDefinition heatArtifact =
+ // AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT,
+ // resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true).left().value();
+ //
+ // resourceDetailsVF_01 =
+ // AtomicOperationUtils.changeComponentState(resourceDetailsVF_01,
+ // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ //
+ // Service resourceDetailsService;
+ // Either<Service, RestResponse> createdResource =
+ // AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
+ // resourceDetailsService = createdResource.left().value();
+ //
+ //
+ // ComponentInstance resourceDetailsVF1ins_01 =
+ // AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01,
+ // resourceDetailsService, UserRoleEnum.DESIGNER, true).left().value();
+ //
+ //
+ // System.out.println("-----");
+ //
+ //
+ // String resourceUUID = resourceDetailsService.getUUID();
+ // String componentInstanceUID = resourceDetailsVF1ins_01.getUniqueId();
+ // String artifactUUID = heatArtifact.getArtifactUUID();
+ //
+ // System.out.println("Resource UUID: " + resourceUUID);
+ // System.out.println("Component instance UID: " + componentInstanceUID);
+ // System.out.println("Artifact UUID: " + artifactUUID);
+ //
+ // RestResponse restResponse =
+ // ArtifactRestUtils.getComponentInstanceDeploymentArtifactExternalAPI(resourceUUID,
+ // componentInstanceUID, artifactUUID,
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "Service");
+ ////
+ // Integer responseCode = restResponse.getErrorCode();
+ // Integer expectedCode = 200;
+ // Assert.assertEquals(responseCode,expectedCode, "Response code is not
+ // correct.");
+ //
+ // String response = restResponse.getResponse();
+ //
+ // String payloadData =
+ // "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ // String decodedPaypload = Decoder.decode(payloadData);
+ //
+ // Assert.assertEquals(response, decodedPaypload, "Response deployment
+ // artifact not correct.");
+ //
+ // String auditAction = "ArtifactDownload";
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new
+ // ExpectedResourceAuditJavaObject();
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceName(resourceDetailsVF1ins_01.getName());
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setStatus("200");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ //
+ // expectedResourceAuditJavaObject.setCONSUMER_ID("ci");
+ // String resource_url =
+ // String.format("/asdc/v1/catalog/services/%s/resourceInstances/%s/artifacts/%s",
+ // resourceUUID, componentInstanceUID, artifactUUID);
+ // expectedResourceAuditJavaObject.setRESOURCE_URL(resource_url);
+ //
+ // AuditValidationUtils.validateAuditDownloadExternalAPI(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ // }
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ // @Test
+ // public void downloadArtifactFromResourceTest() throws Exception {
+ //
+ // CloseableHttpClient httpclient = HttpClients.createDefault();
+ // try {
+ // String jsonBody = createUploadArtifactBodyJson();
+ //
+ // String resourceId = resourceDetails.getUniqueId();
+ // String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE,
+ // config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ // HttpPost httppost = createPostAddArtifactRequeast(jsonBody, url, true);
+ // HttpResponse response = httpclient.execute(httppost);
+ // int status = response.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("failed to add artifact", 200, status);
+ //
+ // ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonBody);
+ // addArtifactDataFromResponse(response, origArtifact);
+ // String artifactId = origArtifact.getUniqueId();
+ //
+ // url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT,
+ // config.getCatalogBeHost(), config.getCatalogBePort(), resourceId,
+ // artifactId);
+ // HttpGet httpGet = createGetRequest(url);
+ // response = httpclient.execute(httpGet);
+ // status = response.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("failed to download artifact", 200, status);
+ //
+ // InputStream inputStream = response.getEntity().getContent();
+ // ArtifactUiDownloadData artifactUiDownloadData =
+ // getArtifactUiDownloadData(IOUtils.toString(inputStream));
+ // AssertJUnit.assertEquals("Downloaded payload is different from uploaded
+ // one", UPLOAD_ARTIFACT_PAYLOAD,
+ // artifactUiDownloadData.getBase64Contents());
+ // AssertJUnit.assertEquals("Downloaded artifact name is different from
+ // uploaded one", UPLOAD_ARTIFACT_NAME,
+ // artifactUiDownloadData.getArtifactName());
+ //
+ // // validate audit
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // Convertor.constructFieldsForAuditValidation(resourceDetails,
+ // resourceDetails.getVersion(), sdncUserDetails);
+ // String auditAction = "ArtifactDownload";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("200");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact));
+ // expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ // expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ // } finally {
+ // httpclient.close();
+ // }
+ //
+ // }
+ //
+ // @Test
+ // public void downloadArtifactFromServiceTest() throws Exception {
+ //
+ // CloseableHttpClient httpclient = HttpClients.createDefault();
+ //
+ // try {
+ //
+ // String jsonStr = createUploadArtifactBodyJson();
+ //
+ // String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE,
+ // config.getCatalogBeHost(), config.getCatalogBePort(),
+ // serviceDetails.getUniqueId());
+ // HttpPost httpPost = createPostAddArtifactRequeast(jsonStr, url, true);
+ // CloseableHttpResponse result = httpclient.execute(httpPost);
+ // int status = result.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("failed to add artifact", 200, status);
+ //
+ // ArtifactDefinition origArtifact = getArtifactDataFromJson(jsonStr);
+ // addArtifactDataFromResponse(result, origArtifact);
+ // String artifactId = origArtifact.getUniqueId();
+ //
+ // url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT,
+ // config.getCatalogBeHost(), config.getCatalogBePort(),
+ // serviceDetails.getUniqueId(), artifactId);
+ // HttpGet httpGet = createGetRequest(url);
+ // CloseableHttpResponse response2 = httpclient.execute(httpGet);
+ // status = response2.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("failed to download artifact", 200, status);
+ // InputStream inputStream = response2.getEntity().getContent();
+ // ArtifactUiDownloadData artifactUiDownloadData =
+ // getArtifactUiDownloadData(IOUtils.toString(inputStream));
+ // AssertJUnit.assertEquals("Downloaded payload is different from uploaded
+ // one", UPLOAD_ARTIFACT_PAYLOAD,
+ // artifactUiDownloadData.getBase64Contents());
+ // AssertJUnit.assertEquals("Downloaded artifact name is different from
+ // uploaded one", UPLOAD_ARTIFACT_NAME,
+ // artifactUiDownloadData.getArtifactName());
+ //
+ // // validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // AuditValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // serviceDetails.getVersion(), sdncUserDetails);
+ // String auditAction = "ArtifactDownload";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("200");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // expectedResourceAuditJavaObject.setArtifactData(AuditValidationUtils.buildArtifactDataAudit(origArtifact));
+ // expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ // expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ //
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ // } finally {
+ //// RestResponse response = ServiceRestUtils.deleteService(serviceDetails,
+ // serviceVersion, sdncUserDetails );
+ //// checkDeleteResponse(response);
+ // httpclient.close();
+ // }
+ // }
+ //
+ // @Test
+ // public void downloadArtifactFromResourceNotFound() throws Exception {
+ //
+ // CloseableHttpClient httpclient = HttpClients.createDefault();
+ // try {
+ //
+ // String resourceId = resourceDetails.getUniqueId();
+ // String artifactIdNotFound = "11111";
+ //
+ // ArtifactDefinition origArtifact = new ArtifactDefinition();
+ // origArtifact.setUniqueId(artifactIdNotFound);
+ //
+ // String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT,
+ // config.getCatalogBeHost(), config.getCatalogBePort(), resourceId,
+ // artifactIdNotFound);
+ // HttpGet httpGet = createGetRequest(url);
+ // CloseableHttpResponse response = httpclient.execute(httpGet);
+ // int status = response.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("expected 404 not found", 404, status);
+ //
+ // // validate audit
+ // ErrorInfo errorInfo =
+ // ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // Convertor.constructFieldsForAuditValidation(resourceDetails,
+ // resourceDetails.getVersion(), sdncUserDetails);
+ // String auditAction = "ArtifactDownload";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ // expectedResourceAuditJavaObject.setArtifactData("");
+ // expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ // expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ // expectedResourceAuditJavaObject.setPrevArtifactUuid(null);
+ // } finally {
+ // httpclient.close();
+ // }
+ //
+ // }
+ //
+ // @Test
+ // public void downloadArtifactFromServiceNotFound() throws Exception {
+ //
+ // CloseableHttpClient httpclient = HttpClients.createDefault();
+ // try {
+ //
+ // String artifactIdNotFound = "11111";
+ // ArtifactDefinition origArtifact = new ArtifactDefinition();
+ // origArtifact.setUniqueId(artifactIdNotFound);
+ //
+ // String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT,
+ // config.getCatalogBeHost(), config.getCatalogBePort(),
+ // serviceDetails.getUniqueId(), artifactIdNotFound);
+ // HttpGet httpGet = createGetRequest(url);
+ // CloseableHttpResponse response2 = httpclient.execute(httpGet);
+ // int status = response2.getStatusLine().getStatusCode();
+ // AssertJUnit.assertEquals("expected 404 not found", 404, status);
+ //
+ // // validate audit
+ // ErrorInfo errorInfo =
+ // ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name());
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // serviceDetails.getVersion(), sdncUserDetails);
+ // String auditAction = "ArtifactDownload";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ // expectedResourceAuditJavaObject.setArtifactData("");
+ // expectedResourceAuditJavaObject.setCurrArtifactUuid(origArtifact.getUniqueId());
+ // expectedResourceAuditJavaObject.setPrevArtifactUuid("");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ // } finally {
+ // httpclient.close();
+ // }
+ //
+ // }
+ //
+ // @Test
+ // public void addArtifactToResourceTest() throws Exception {
+ //
+ // ArtifactReqDetails defaultArtifact = ElementFactory.getDefaultArtifact();
+ //
+ // RestResponse response =
+ // ArtifactRestUtils.addInformationalArtifactToResource(defaultArtifact,
+ // sdncUserDetails, resourceDetails.getUniqueId());
+ // int status = response.getErrorCode();
+ // AssertJUnit.assertEquals("add informational artifact request returned
+ // status: " + response.getErrorCode(), 200, status);
+ //
+ // RestResponse resourceResp =
+ // ResourceRestUtils.getResource(resourceDetails.getUniqueId());
+ // Resource resource =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ // AssertJUnit.assertNotNull(resource);
+ //
+ // Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ // boolean isExist = false;
+ // for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet())
+ // {
+ // if (entry.getKey().equals(defaultArtifact.getArtifactLabel())) {
+ // isExist = true;
+ //
+ // }
+ // }
+ // AssertJUnit.assertTrue(isExist);
+ // }
+
+ protected String createUploadArtifactBodyJson() {
+ Map<String, Object> jsonBody = new HashMap<String, Object>();
+ jsonBody.put("artifactName", UPLOAD_ARTIFACT_NAME);
+ jsonBody.put("artifactDisplayName", "configure");
+ jsonBody.put("artifactType", "SHELL");
+ jsonBody.put("mandatory", "false");
+ jsonBody.put("description", "ff");
+ jsonBody.put("payloadData", UPLOAD_ARTIFACT_PAYLOAD);
+ jsonBody.put("artifactLabel", "configure");
+ return gson.toJson(jsonBody);
+ }
+
+ protected ArtifactDefinition getArtifactDataFromJson(String json) {
+ Gson gson = new Gson();
+ JsonObject jsonElement = new JsonObject();
+ jsonElement = gson.fromJson(json, jsonElement.getClass());
+ ArtifactDefinition artifact = new ArtifactDefinition();
+ String payload = null;
+ JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
+ if (artifactPayload != null && !artifactPayload.isJsonNull()) {
+ payload = artifactPayload.getAsString();
+ }
+ jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
+ artifact = gson.fromJson(jsonElement, ArtifactDefinition.class);
+ artifact.setPayloadData(payload);
+
+ /*
+ * atifact.setArtifactName(UPLOAD_ARTIFACT_NAME);
+ * artifact.setArtifactDisplayName("configure");
+ * artifact.setArtifactType("SHELL"); artifact.setMandatory(false);
+ * artifact.setDescription("ff");
+ * artifact.setPayloadData(UPLOAD_ARTIFACT_PAYLOAD);
+ * artifact.setArtifactLabel("configure");
+ */
+ return artifact;
+ }
+
+ protected HttpGet createGetRequest(String url) {
+ HttpGet httpGet = new HttpGet(url);
+ httpGet.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httpGet.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ return httpGet;
+ }
+
+ protected String getArtifactUid(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected String getArtifactEsId(HttpResponse response) throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ String esId = (String) responseMap.get("EsId");
+ return esId;
+ }
+
+ protected ArtifactDefinition addArtifactDataFromResponse(HttpResponse response, ArtifactDefinition artifact)
+ throws HttpResponseException, IOException, ParseException {
+ // String responseString = new
+ // BasicResponseHandler().handleResponse(response);
+ HttpEntity entity = response.getEntity();
+ String responseString = EntityUtils.toString(entity);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ artifact.setEsId((String) responseMap.get("esId"));
+ artifact.setUniqueId((String) responseMap.get("uniqueId"));
+ artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType((String) responseMap.get("artifactGroupType")));
+ artifact.setTimeout(((Long) responseMap.get("timeout")).intValue());
+ return artifact;
+ }
+
+ protected String getLifecycleArtifactUid(CloseableHttpResponse response)
+ throws HttpResponseException, IOException, ParseException {
+ String responseString = new BasicResponseHandler().handleResponse(response);
+ JSONObject responseMap = (JSONObject) jsonParser.parse(responseString);
+ responseMap = (JSONObject) responseMap.get("implementation");
+ String artifactId = (String) responseMap.get("uniqueId");
+ return artifactId;
+ }
+
+ protected HttpDelete createDeleteArtifactRequest(String url) {
+ HttpDelete httpDelete = new HttpDelete(url);
+ httpDelete.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ httpDelete.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ return httpDelete;
+ }
+
+ protected HttpPost createPostAddArtifactRequeast(String jsonBody, String url, boolean addMd5Header)
+ throws UnsupportedEncodingException {
+ HttpPost httppost = new HttpPost(url);
+ httppost.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ if (addMd5Header) {
+ httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody));
+ }
+ StringEntity input = new StringEntity(jsonBody);
+ input.setContentType("application/json");
+ httppost.setEntity(input);
+ log.debug("Executing request {}", httppost.getRequestLine());
+ return httppost;
+ }
+
+ protected String createLoadArtifactBody() {
+ Map<String, Object> json = new HashMap<String, Object>();
+ json.put("artifactName", "install_apache2.sh");
+ json.put("artifactType", "SHELL");
+ json.put("description", "ddd");
+ json.put("payloadData", "UEsDBAoAAAAIAAeLb0bDQz");
+ json.put("artifactLabel", "name123");
+
+ String jsonStr = gson.toJson(json);
+ return jsonStr;
+ }
+
+ protected void checkDeleteResponse(RestResponse response) {
+ BaseRestUtils.checkStatusCode(response, "delete request failed", false, 204, 404);
+ }
+
+ protected ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception {
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr,
+ ArtifactUiDownloadData.class);
+ return artifactUiDownloadData;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java
new file mode 100644
index 0000000000..2c9d96d79d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarUpdate.java
@@ -0,0 +1,356 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.imports.ImportCsarResourceTest;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class ImportCsarUpdate extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ImportCsarUpdate() {
+ super(name, ImportCsarUpdate.class.getName());
+ }
+
+ @DataProvider(name = "happyArts")
+ public Object[][] getHappyArtifacts() {
+
+ return new Object[][] { { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet2" },
+ { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet" },
+ { "happy_VF_RI2_G2_two_identical_artifacts_under_heatBaseheatVolheatNet" },
+ { "happy_VF_RI2_G2_two_different_artifacts_under_nested" },
+ { "happy_VF_RI2_G2_two_indentical_nested_under_different_groups" },
+ { "happy_VF_RI2_G2_two_different_nested_under_different_groups" },
+ { "happy_VF_RI2_G2_two_different_nested_under_same_group" },
+
+ };
+ }
+
+ @DataProvider(name = "negativeArts")
+ public Object[][] getNegativeArtifacts() {
+
+ return new Object[][] {
+
+ { "negative_VF_RI2_G2_same_heatVol_different_groups" },
+ { "negative_VF_RI2_G2_same_heatBase_different_envs" },
+ { "negative_VF_RI2_G2_heatBaseHeatVolHeatNet_under_nested" },
+ { "negative_VF_RI2_G2_two_indentical_artifacts_under_nested" },
+ { "negative_VF_RI2_G2_nested_under_nested" }, { "negative_VF_RI2_G2_same_heatVol_different_groups" }, };
+ }
+
+ @BeforeTest
+ public void resumeOrigCsarBefore() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig.csar", "importCsar_2Gartifacts.csar");
+
+ }
+
+ @AfterTest
+ public void resumeOrigCsarAfter() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig.csar", "importCsar_2Gartifacts.csar");
+
+ }
+
+ @Test
+ public void updateVFsearchByCsarIdCheckInState() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true)
+ .getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchByCsarIdCheckInState_checkSum() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true)
+ .getLeft();
+
+ // User sdncModifierDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // RestResponse copyRes =
+ // ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,"updateImportCsar_2Gartifacts_topologyChanged.csar","importCsar_2Gartifacts.csar");
+
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchByCsarIdCheckOutState() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ // Component resourceObject =
+ // AtomicOperationUtils.changeComponentState(resourceFirstImport,
+ // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchByCsarIdCertifyStat() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true)
+ .getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchByCsarStartCertificationState() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils.changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchBySystemNameCheckInState() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true)
+ .getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setName("hardcodedNameChanged");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+ @Test
+ public void updateVFsearchBySystemNameCertifyState() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true)
+ .getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "updateImportCsar_2Gartifacts_topologyChanged.csar", "importCsar_2Gartifacts.csar");
+
+ resourceDetails.setName("hardcodedNameChanged");
+ resourceDetails.setCsarUUID("importCsar_2Gartifacts");
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ }
+
+ @Test
+ public void updateVFsearchBySystemNameCsarIdNotExist() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("hardcodedName");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceFirstImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resourceFirstImport, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true)
+ .getLeft();
+ // User sdncModifierDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // RestResponse copyRes =
+ // ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,"updateImportCsar_2Gartifacts_topologyChanged.csar","importCsar_2Gartifacts.csar");
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+ resourceDetails2.setName("hardcodedName");
+ resourceDetails2.setCsarUUID("importCsar_2Gartifacts");
+ resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails2,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resourceSecondImport = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ // Validation Part
+
+ resourceFirstImport.getGroups().equals(resourceSecondImport.getGroups());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java
new file mode 100644
index 0000000000..49e5950db5
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ImportCsarValidateArtifacts.java
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class ImportCsarValidateArtifacts extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ImportCsarValidateArtifacts() {
+ super(name, ImportCsarValidateArtifacts.class.getName());
+ }
+
+ @DataProvider(name = "happyArts")
+ public Object[][] getHappyArtifacts() {
+
+ return new Object[][] { { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet2" },
+ { "happy_VF_RI2_G2_two_different_artifacts_under_heatBaseheatVolheatNet" },
+ { "happy_VF_RI2_G2_two_identical_artifacts_under_heatBaseheatVolheatNet" },
+ { "happy_VF_RI2_G2_two_different_artifacts_under_nested" },
+ { "happy_VF_RI2_G2_two_indentical_nested_under_different_groups" },
+ { "happy_VF_RI2_G2_two_different_nested_under_different_groups" },
+ { "happy_VF_RI2_G2_two_different_nested_under_same_group" },
+
+ };
+ }
+
+ @DataProvider(name = "negativeArts")
+ public Object[][] getNegativeArtifacts() {
+
+ return new Object[][] {
+
+ { "negative_VF_RI2_G2_same_heatVol_different_groups" },
+ { "negative_VF_RI2_G2_same_heatBase_different_envs" },
+ { "negative_VF_RI2_G2_heatBaseHeatVolHeatNet_under_nested" },
+ { "negative_VF_RI2_G2_two_indentical_artifacts_under_nested" },
+ { "negative_VF_RI2_G2_nested_under_nested" }, { "negative_VF_RI2_G2_same_heatVol_different_groups" }, };
+ }
+
+ @Test(dataProvider = "happyArts")
+ public void createResourceFromCsarArtsHappy(String artifactName) throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(artifactName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ CsarValidationUtils.validateCsarVfArtifact(artifactName, resource);
+
+ }
+
+ @Test(dataProvider = "negativeArts")
+ public void createResourceFromCsarArtsNegative(String artifactName) throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(artifactName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertTrue(createResource.getErrorCode() != 201 && createResource.getErrorCode() != 500);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java
new file mode 100644
index 0000000000..bb86f8f336
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/devCI/ToscaGroupInsideVF.java
@@ -0,0 +1,578 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.devCI;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
+import org.openecomp.sdc.ci.tests.utils.ToscaParserUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+public class ToscaGroupInsideVF extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(ToscaGroupInsideVF.class.getName());
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ToscaGroupInsideVF() {
+ super(name, ToscaGroupInsideVF.class.getName());
+ }
+
+ @Test
+ public void createResourceFromCsarArts() throws Exception {
+
+ // String csar = getCsar();
+ // parseCsar(csar);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VF_RI2_G6_withArtifacts");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ Resource vfManual = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, vfManual, UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.changeComponentState(vfManual, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true)
+ .getLeft();
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceObject, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(vfManual, service, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+ AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CANCELCERTIFICATION, true)
+ .getLeft();
+ AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ }
+
+ @Test
+ public void soferTest() throws Exception {
+
+ // String csar = getCsar();
+ // parseCsar(csar);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("sofer");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ }
+
+ @Test
+ public void createVFwith2VLs() throws Exception {
+
+ // String csar = getCsar();
+ // parseCsar(csar);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VSPPackage");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ Component resourceObject = AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ Resource vfManual = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, vfManual, UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.changeComponentState(vfManual, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true)
+ .getLeft();
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceObject, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(vfManual, service, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+ AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CANCELCERTIFICATION, true)
+ .getLeft();
+ AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true)
+ .getLeft();
+
+ }
+
+ @Test // (enabled = false)
+ public void createResourceFromCsarHappy() throws Exception {
+ // String csarUUID = "VF_RI2_G2_withArtifacts";
+ String csarUUID = "VF_RI2_G1_Invalid";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ }
+
+ @Test // (enabled = false)
+ public void createResourceFromCsarWithProperty() throws Exception {
+ String csarUUID = "VF_RI2_G4_withArtifacts";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarWithNonExistingResourceInstanceFail() throws Exception {
+
+ // String csarUUID = "VF_RI2_G1-RI_NotExist";
+ // String csarUUID = "nested3";
+
+ // String csarUUID = "VF_RI2_G1_Invalid_WithArtifacts";
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifactsRI_FAIL.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails.setName(resource.getName());
+ // resourceDetails.setVendorName("Govnuk");
+ // resourceDetails.setDescription("Other");
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarWithSameCsarDifferentMetadata() throws Exception {
+
+ // User sdncModifierDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // RestResponse copyRes =
+ // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar");
+ // BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ resourceDetails.setName(resource.getName());
+ resourceDetails.setVendorName("Govnuk");
+ resourceDetails.setDescription("Other");
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarWithSameCsar() throws Exception {
+
+ // User sdncModifierDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // RestResponse copyRes =
+ // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar");
+ // BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ resourceDetails.setName(resource.getName());
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarCertifiedVfWithSameCsar() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ Pair<Component, RestResponse> changeComponentState = AtomicOperationUtils.changeComponentState(resource,
+ UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ resource = (Resource) changeComponentState.getLeft();
+
+ resourceDetails.setName(resource.getName());
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarDifferentTosca() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifactsUpdated.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails.setName(resource.getName());
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void UpdateCsarDifferentToscaAndArtifacts() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ String csarUUID = "VF_RI2_G4_withArtifacts.csar";
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_UpdateToscaAndArtifacts.csar",
+ "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails.setName(resource.getName());
+ RestResponse createResource2 = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource2);
+ Resource resource2 = ResponseParser.parseToObjectUsingMapper(createResource2.getResponse(), Resource.class);
+
+ CsarValidationUtils.validateCsarVfArtifact(csarUUID, resource);
+ ToscaDefinition toscaDefinition = ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition, resource);
+
+ // CsarValidationUtils.validateCsarVfArtifact(csarUUID2, resource2);
+ // ToscaDefinition toscaDefinition2 =
+ // ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID2);
+ // CsarValidationUtils.validateToscaDefinitonObjectVsResource(toscaDefinition2,
+ // resource2);
+
+ // Csar csar = parserTocsarObject(csarUUID);
+ // validateCsarVsResourceObj(csar, resource);
+ // csar.node_types();
+
+ }
+
+ @Test // (enabled = false)
+ public void migration() throws Exception {
+ String csarUUID = "VF_RI2_G4_withArtifacts";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setName("Resource1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ resourceDetails.setName("Resource2");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ resourceDetails.setName("Resource3");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceDetails.setName("Resource4");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ resourceDetails.setName("Resource5");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ resourceDetails.setName("Resource6");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true)
+ .getLeft();
+
+ resourceDetails.setName("Resource7");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ logger.debug("7 VF resources were created");
+
+ }
+
+ public static RestResponse copyCsarRest(User sdncModifierDetails, String sourceCsarUuid, String targetCsarUuid)
+ throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.COPY_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(),
+ sourceCsarUuid, targetCsarUuid);
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+
+ RestResponse copyCsarResponse = http.httpSendPost(url, "dummy", headersMap);
+ if (copyCsarResponse.getErrorCode() != 200) {
+ return null;
+ }
+ return copyCsarResponse;
+
+ }
+
+ private static Map<String, String> prepareHeadersMap(String userId) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ if (userId != null) {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
+ }
+ return headersMap;
+ }
+
+ public static void main(String[] args) throws Exception {
+ // String csarUUID = "VF_RI2_G4_withArtifacts";
+ String csarUUID = "node_types";
+ ToscaParserUtils.getToscaDefinitionObjectByCsarUuid(csarUUID);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java
new file mode 100644
index 0000000000..b4a9bb87ce
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/AuthanticationTests.java
@@ -0,0 +1,186 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.distribution;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class AuthanticationTests extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected User sdncUserDetails;
+
+ protected static final String AUTH_SUCCESS = "AUTH_SUCCESS";
+
+ protected static final String AUTH_REQUIRED = "AUTH_REQUIRED";
+
+ // user ci password 123456
+ // protected final String authorizationHeader = "Basic Y2k6MTIzNDU2";
+ // user ci password 123456
+ protected final String USER = "ci";
+ protected final String PASSWORD = "123456";
+ protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50";
+ protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b";
+ protected User sdncAdminUserDetails;
+ protected ConsumerDataDefinition consumerDataDefinition;
+
+ public AuthanticationTests() {
+ super(name, AuthanticationTests.class.getName());
+ }
+
+ @DataProvider
+ private final Object[][] getServiceDepArtType() throws IOException, Exception {
+ return new Object[][] { { ArtifactTypeEnum.YANG_XML.getType() }, { ArtifactTypeEnum.OTHER.getType() } };
+ }
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ resourceDetails = ElementFactory.getDefaultResource();
+ serviceDetails = ElementFactory.getDefaultService();
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ createComponents();
+ consumerDataDefinition = createConsumer();
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ ;
+
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkCreateResponse(createResponse);
+
+ }
+
+ @AfterMethod
+ public void tearDown() throws Exception {
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ ;
+
+ }
+
+ protected ConsumerDataDefinition createConsumer() {
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName(USER);
+ consumer.setConsumerSalt(SALT);
+ consumer.setConsumerPassword(HASHED_PASSWORD);
+ return consumer;
+
+ }
+
+ protected void createComponents() throws Exception {
+ RestResponse response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ ServiceRestUtils.checkCreateResponse(response);
+ }
+
+ @Test(dataProvider = "getServiceDepArtType", description = "mumu")
+ public void downloadServiceArtifactSuccessWithAutantication(String serviceDepArtType) throws Exception {
+ String serviceUniqueId = serviceDetails.getUniqueId();
+
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(serviceDepArtType);
+
+ RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails,
+ sdncUserDetails, serviceUniqueId, ArtifactRestUtils.calculateChecksum(artifactDetails));
+ AssertJUnit.assertEquals("Check response code after adding interface artifact", 200,
+ addArtifactResponse.getErrorCode().intValue());
+
+ String artifactName = ValidationUtils.normalizeFileName(artifactDetails.getArtifactName());
+ // Thread.sleep(5000);
+ Map<String, String> authorizationHeaders = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails,
+ sdncUserDetails, authorizationHeaders);
+ AssertJUnit.assertEquals("Check response code after download resource", 200,
+ restResponse.getErrorCode().intValue());
+
+ List<String> contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER);
+ AssertJUnit.assertNotNull(contDispHeaderList);
+ AssertJUnit.assertEquals("Check content disposition header",
+ new StringBuilder().append("attachment; filename=\"").append(artifactName).append("\"").toString(),
+ contDispHeaderList.get(0));
+
+ String downloadUrl = ArtifactRestUtils
+ .getPartialUrlByArtifactName(serviceDetails, serviceDetails.getVersion(), artifactName).substring(6);
+
+ ExpectedAuthenticationAudit expectedAuthenticationAudit = new ExpectedAuthenticationAudit(downloadUrl, USER,
+ AuditingActionEnum.AUTH_REQUEST.getName(), AUTH_SUCCESS);
+ AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit);
+ }
+
+ @Test(dataProvider = "getServiceDepArtType")
+ public void downloadServiceArtifactWithOutAutantication(String serviceDepArtType) throws Exception {
+ String serviceUniqueId = serviceDetails.getUniqueId();
+
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(serviceDepArtType);
+
+ RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails,
+ sdncUserDetails, serviceUniqueId, ArtifactRestUtils.calculateChecksum(artifactDetails));
+ assertEquals("Check response code after adding interface artifact", 200,
+ addArtifactResponse.getErrorCode().intValue());
+
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails,
+ sdncUserDetails, authorizationHeaders);
+ assertEquals("Check response code after download resource failure", 401,
+ restResponse.getErrorCode().intValue());
+
+ String downloadUrl = ArtifactRestUtils.getPartialUrlByArtifactName(serviceDetails, serviceDetails.getVersion(),
+ artifactDetails.getArtifactName()).substring(6);
+ ExpectedAuthenticationAudit expectedAuthenticationAudit = new ExpectedAuthenticationAudit(downloadUrl, "",
+ AuditingActionEnum.AUTH_REQUEST.getName(), AUTH_REQUIRED);
+ AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java
new file mode 100644
index 0000000000..6cf5626e7e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java
@@ -0,0 +1,542 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.distribution;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipInputStream;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedDistDownloadAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class DistributionDownloadArtifactTest extends ComponentBaseTest {
+
+ protected static ResourceReqDetails resourceDetails;
+ protected static User designerUser;
+ protected static User adminUser;
+ protected static String resourceBaseVersion;
+ // user ci password 123456
+ protected final String authorizationHeader = "Basic Y2k6MTIzNDU2";
+ protected ConsumerDataDefinition consumerDataDefinition;
+
+ @Rule
+ public static TestName name = new TestName();
+ protected static String artifactInterfaceType;
+ protected static String artifactOperationName;
+
+ protected static ServiceReqDetails serviceDetails;
+ protected static String serviceBaseVersion;
+ protected static String serviceUniqueId;
+ protected final String USER = "ci";
+ protected final String PASSWORD = "123456";
+ protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50";
+ protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b";
+
+ public DistributionDownloadArtifactTest() {
+ super(name, DistributionDownloadArtifactTest.class.getName());
+ }
+
+ // @BeforeClass
+ // public static void InitBeforeTest() throws Exception
+ // {
+ //
+ //
+ // resourceBaseVersion = "0.1";
+ // serviceBaseVersion = "0.1";
+ // designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ //// resourceDetails =
+ // ElementFactory.getDefaultResource("tosca.nodes.newnotgenericresource4testNew",
+ // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ // "jh0003");
+ // resourceDetails =
+ // ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ // adminUser);
+ // serviceDetails = ElementFactory.getDefaultService();
+ // serviceUniqueId = "svc_" + serviceDetails.getName().toLowerCase() + "." +
+ // serviceBaseVersion;
+ // artifactInterfaceType = "standard";
+ // artifactOperationName = "start";
+ // }
+
+ @BeforeMethod
+ public void setup() throws Exception {
+
+ resourceBaseVersion = "0.1";
+ serviceBaseVersion = "0.1";
+ designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // resourceDetails =
+ // ElementFactory.getDefaultResource("tosca.nodes.newnotgenericresource4testNew",
+ // NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ // "jh0003");
+ resourceDetails = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, adminUser);
+ serviceDetails = ElementFactory.getDefaultService();
+ serviceUniqueId = "svc_" + serviceDetails.getName().toLowerCase() + "." + serviceBaseVersion;
+ artifactInterfaceType = "standard";
+ artifactOperationName = "start";
+ consumerDataDefinition = createConsumer();
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, adminUser);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, adminUser);
+ BaseRestUtils.checkCreateResponse(createResponse);
+ }
+
+ @Test
+ public void downloadResourceArtifactSuccess() throws Exception {
+ // Create service
+ RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ AssertJUnit.assertEquals("Check response code after creating resource", 201,
+ serviceResponse.getErrorCode().intValue());
+
+ // Create resource
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser);
+ AssertJUnit.assertEquals("Check response code after creating resource", 201,
+ createResource.getErrorCode().intValue());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
+
+ ArtifactReqDetails artifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ // Setting the name to be with space
+ artifactDetails.setArtifactName("test artifact file.yaml");
+ // artifactDetails.set(ArtifactRestUtils.calculateChecksum(artifactDetails));
+
+ RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails,
+ designerUser, resource.getUniqueId(), ArtifactRestUtils.calculateChecksum(artifactDetails));
+ AssertJUnit.assertEquals("Check response code after adding interface artifact", 200,
+ addArtifactResponse.getErrorCode().intValue());
+
+ // Getting expected artifact checksum
+ ArtifactDefinition artifactResp = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addArtifactResponse.getResponse());
+ String expectedPayloadChecksum = artifactResp.getArtifactChecksum();
+
+ Config config = Utils.getConfig();
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion,
+ ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(),
+ artifactResp.getArtifactName()));
+ // String fullUrlFormatted =
+ // String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL,
+ // config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl);
+ // String consumerId = "dummy.ecomp";
+
+ ResourceReqDetails resourceInfo = new ResourceReqDetails();
+ resourceInfo.setName(resource.getName());
+ resourceInfo.setVersion(resource.getVersion());
+
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceInfo,
+ artifactDetails, designerUser, authorizationHeaders);
+ // RestResponse restResponse =
+ // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted,
+ // consumerId,true);
+ AssertJUnit.assertEquals("Check response code after download resource", 200,
+ restResponse.getErrorCode().intValue());
+
+ // Validating headers
+ // content disposition
+ List<String> contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER);
+ AssertJUnit.assertNotNull(contDispHeaderList);
+ AssertJUnit
+ .assertEquals(
+ "Check content disposition header", new StringBuilder().append("attachment; filename=\"")
+ .append(artifactResp.getArtifactName()).append("\"").toString(),
+ contDispHeaderList.get(0));
+
+ // content type
+ List<String> contTypeHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_TYPE_HEADER);
+ AssertJUnit.assertNotNull(contTypeHeaderList);
+ AssertJUnit.assertEquals("Check content type", "application/octet-stream", contTypeHeaderList.get(0));
+
+ String actualContents = restResponse.getResponse();
+
+ // Contents - comparing decoded content
+ AssertJUnit.assertEquals(artifactDetails.getPayload(), Base64.encodeBase64String(actualContents.getBytes()));
+
+ // validating checksum
+ String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(actualContents.getBytes());
+ AssertJUnit.assertEquals(expectedPayloadChecksum, actualPayloadChecksum);
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ BaseRestUtils.ecomp, relativeUrl, "200", "OK");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ protected void download_serviceNameNotFound_inner(String serviceName, String serviceVersion, String resourceName,
+ String resourceVersion) throws Exception {
+ Config config = Utils.getConfig();
+ String artifactName = "kuku";
+ ArtifactReqDetails artifact = new ArtifactReqDetails();
+ artifact.setArtifactName(artifactName);
+ String relativeUrl;
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ ServiceReqDetails serviceInfo = new ServiceReqDetails();
+ serviceInfo.setName(serviceName);
+ serviceInfo.setVersion(serviceVersion);
+ RestResponse restResponse = null;
+ if (resourceName != null) {
+ ResourceReqDetails resourceDetailes = new ResourceReqDetails();
+ resourceDetailes.setName(resourceName);
+ resourceDetailes.setVersion(resourceVersion);
+ relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceName), serviceVersion,
+ ValidationUtils.convertToSystemName(resourceName), resourceVersion, artifactName));
+ restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceInfo, resourceDetailes, artifact,
+ designerUser, authorizationHeaders);
+ } else {
+ relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceName), serviceVersion, artifactName));
+ restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceInfo, artifact, designerUser,
+ authorizationHeaders);
+ }
+
+ // RestResponse restResponse =
+ // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted,
+ // consumerId,true);
+ AssertJUnit.assertEquals("Check response code after download resource", 404,
+ restResponse.getErrorCode().intValue());
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ BaseRestUtils.ecomp, relativeUrl, "404", "SVC4503: Error: Requested '"
+ + ValidationUtils.convertToSystemName(serviceName) + "' service was not found.");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ protected void download_serviceVersionNotFound_inner(String serviceName, String serviceVersion, String resourceName,
+ String resourceVersion) throws Exception {
+ Config config = Utils.getConfig();
+ String artifactName = "kuku";
+ String relativeUrl;
+ ArtifactReqDetails artifact = new ArtifactReqDetails();
+ artifact.setArtifactName(artifactName);
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ ServiceReqDetails serviceInfo = new ServiceReqDetails();
+ serviceInfo.setName(serviceName);
+ serviceInfo.setVersion(serviceVersion);
+ RestResponse restResponse = null;
+ if (resourceName != null) {
+ ResourceReqDetails resourceDetailes = new ResourceReqDetails();
+ resourceDetailes.setName(resourceName);
+ resourceDetailes.setVersion(resourceVersion);
+ relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceName), serviceVersion,
+ ValidationUtils.convertToSystemName(resourceName), resourceVersion, artifactName));
+ restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceInfo, resourceDetailes, artifact,
+ designerUser, authorizationHeaders);
+ } else {
+ relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceName), serviceVersion, artifactName));
+ restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceInfo, artifact, designerUser,
+ authorizationHeaders);
+ }
+ // String fullUrlFormatted =
+ // String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL,
+ // config.getCatalogBeHost(),config.getCatalogBePort(), relativeUrl);
+ // String consumerId = "dummy.ecomp";
+
+ // RestResponse restResponse =
+ // artifactUtils.downloadResourceArtifact(designerUser,fullUrlFormatted,
+ // consumerId,true);
+ AssertJUnit.assertEquals("Check response code after download resource", 404,
+ restResponse.getErrorCode().intValue());
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ BaseRestUtils.ecomp, relativeUrl, "404",
+ "SVC4504: Error: Service version " + serviceVersion + " was not found.");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ protected String encodeUrlForDownload(String url) {
+ return url.replaceAll(" ", "%20");
+ }
+
+ protected ConsumerDataDefinition createConsumer() {
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName(USER);
+ consumer.setConsumerSalt(SALT);
+ consumer.setConsumerPassword(HASHED_PASSWORD);
+ return consumer;
+
+ }
+
+ @Test(enabled = false)
+ public void downloadServiceArtifactSuccess() throws Exception {
+ // Create service
+ RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue());
+ serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse())
+ .getUniqueId();
+
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultDeploymentArtifactForType("MURANO_PKG");
+
+ RestResponse addArtifactResponse = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails,
+ designerUser, serviceUniqueId, ArtifactRestUtils.calculateMD5Header(artifactDetails));
+ assertEquals("Check response code after adding interface artifact", 200,
+ addArtifactResponse.getErrorCode().intValue());
+
+ // Getting expected artifact checksum
+
+ // ArtifactResJavaObject artifactResp =
+ // artifactUtils.parseInformationalArtifactResp(addArtifactResponse);
+ String expectedPayloadChecksum = ResponseParser
+ .convertArtifactDefinitionResponseToJavaObject(addArtifactResponse.getResponse()).getArtifactChecksum();
+
+ String artifactName = ValidationUtils.normalizeFileName(artifactDetails.getArtifactName());
+
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion, artifactName));
+
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, artifactDetails,
+ designerUser, authorizationHeaders);
+ assertEquals("Check response code after download resource", 200, restResponse.getErrorCode().intValue());
+
+ // Validating headers
+ // content disposition
+ List<String> contDispHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_DISPOSITION_HEADER);
+ assertNotNull(contDispHeaderList);
+ assertEquals("Check content disposition header",
+ new StringBuilder().append("attachment; filename=\"").append(artifactName).append("\"").toString(),
+ contDispHeaderList.get(0));
+
+ // content type
+ List<String> contTypeHeaderList = restResponse.getHeaderFields().get(Constants.CONTENT_TYPE_HEADER);
+ assertNotNull(contTypeHeaderList);
+ assertEquals("Check content type", "application/octet-stream", contTypeHeaderList.get(0));
+
+ String actualContents = restResponse.getResponse();
+
+ assertEquals(artifactDetails.getPayload(), Base64.encodeBase64String(actualContents.getBytes()));
+
+ // validating checksum
+ byte[] bytes = actualContents.getBytes();
+ String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(bytes);
+ assertEquals(expectedPayloadChecksum, actualPayloadChecksum);
+
+ // validating valid zip
+ InputStream is = new ByteArrayInputStream(bytes);
+ InputStream zis = new ZipInputStream(is);
+ zis.close();
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ ResourceRestUtils.ecomp, encodeUrlForDownload(relativeUrl), "200", "OK");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ @Test
+ public void downloadResourceArtifact_NoConsumerId() throws Exception {
+
+ String artifactName = "kuku";
+ ArtifactReqDetails artifact = new ArtifactReqDetails();
+ artifact.setArtifactName(artifactName);
+ ResourceReqDetails resource = new ResourceReqDetails();
+ resource.setName("notExisting");
+ resource.setVersion("0.1");
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion,
+ ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), artifactName));
+ serviceDetails.setVersion("0.1");
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resource, artifact,
+ designerUser, authorizationHeaders, false);
+ assertEquals("Check response code after download resource", 400, restResponse.getErrorCode().intValue());
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction, "",
+ relativeUrl, "400", "POL5001: Error: Missing 'X-ECOMP-InstanceID' HTTP header.");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ @Test
+ public void downloadResourceArtifact_ResourceNameNotFound() throws Exception {
+
+ String artifactName = "kuku";
+ ArtifactReqDetails artifact = new ArtifactReqDetails();
+ artifact.setArtifactName(artifactName);
+ ResourceReqDetails resource = new ResourceReqDetails();
+ resource.setName("notExisting");
+ resource.setVersion("0.1");
+ serviceDetails.setVersion("0.1");
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
+ ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), artifactName));
+
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resource, artifact,
+ designerUser, authorizationHeaders);
+
+ assertEquals("Check response code after download resource", 404, restResponse.getErrorCode().intValue());
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ BaseRestUtils.ecomp, relativeUrl, "404",
+ "SVC4063: Error: Requested 'Notexisting' resource was not found.");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ @Test
+ public void downloadResourceArtifact_ResourceVersionNotFound() throws Exception {
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue());
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
+ ResourceReqDetails resourceDetailes = new ResourceReqDetails();
+ resourceDetailes.setName(resource.getName());
+ resourceDetailes.setVersion("0.2");
+
+ serviceDetails.setVersion("0.1");
+
+ String artifactName = "kuku";
+ ArtifactReqDetails artifact = new ArtifactReqDetails();
+ artifact.setArtifactName(artifactName);
+
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL,
+ ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceBaseVersion,
+ ValidationUtils.convertToSystemName(resourceDetailes.getName()), resourceDetailes.getVersion(),
+ artifactName));
+
+ Map<String, String> authorizationHeaders = new HashMap<String, String>();
+ authorizationHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceDetailes,
+ artifact, designerUser, authorizationHeaders);
+ assertEquals("Check response code after download resource", 404, restResponse.getErrorCode().intValue());
+
+ // validate audit
+ String auditAction = "DArtifactDownload";
+
+ ExpectedDistDownloadAudit expectedDistDownloadAudit = new ExpectedDistDownloadAudit(auditAction,
+ BaseRestUtils.ecomp, relativeUrl, "404", "SVC4504: Error: Resource version 0.2 was not found.");
+ AuditValidationUtils.validateAudit(expectedDistDownloadAudit, auditAction);
+ }
+
+ @Test
+ public void downloadResourceArtifact_ServiceNameNotFound() throws Exception {
+ // Create resource
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
+ download_serviceNameNotFound_inner("notExistingServiceName", serviceBaseVersion, resource.getName(),
+ resource.getVersion());
+
+ }
+
+ @Test
+ public void downloadResourceArtifact_ServiceVersionNotFound() throws Exception {
+ // Create resource
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, createResource.getErrorCode().intValue());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
+
+ // Create service
+ RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue());
+ serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse())
+ .getUniqueId();
+
+ download_serviceVersionNotFound_inner(serviceDetails.getName(), "0.3", resource.getName(),
+ resource.getVersion());
+ }
+
+ @Test
+ public void downloadServiceArtifact_ServiceNameNotFound() throws Exception {
+ download_serviceNameNotFound_inner("notExistingServiceName", serviceBaseVersion, null, null);
+
+ }
+
+ @Test
+ public void downloadServiceArtifact_ServiceVersionNotFound() throws Exception {
+
+ // Create service
+ RestResponse serviceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ assertEquals("Check response code after creating resource", 201, serviceResponse.getErrorCode().intValue());
+ serviceUniqueId = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse())
+ .getUniqueId();
+
+ download_serviceVersionNotFound_inner(serviceDetails.getName(), "0.2", null, null);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java
new file mode 100644
index 0000000000..3325227ebc
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/externalapi/DownloadArtifactsTest.java
@@ -0,0 +1,338 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.externalapi;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.Assert;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class DownloadArtifactsTest extends ComponentBaseTest {
+ @Rule
+ public static TestName name = new TestName();
+
+ Gson gson = new Gson();
+
+ public DownloadArtifactsTest() {
+ super(name, DownloadArtifactsTest.class.getName());
+ }
+
+ private User sdncDesignerDetails;
+ private User sdncAdminDetails;
+ private ImportReqDetails resourceDetailsVF_01;
+ private ResourceReqDetails resourceDetailsVF_02;
+ private ResourceReqDetails resourceDetailsVF_03;
+ private ResourceReqDetails resourceDetailsCP_01;
+ private ServiceReqDetails serviceDetails_01;
+ private ServiceReqDetails serviceDetails_02;
+ public static String rootPath = System.getProperty("user.dir");
+
+ @BeforeMethod(alwaysRun = true)
+ public void before() throws Exception {
+ init();
+ createComponents();
+ }
+
+ private void createComponents() throws Exception {
+ createAtomicResource(resourceDetailsCP_01);
+ importVfWithArtifacts(resourceDetailsVF_01);
+ createVF(resourceDetailsVF_03);
+ createVF(resourceDetailsVF_02);
+ createService(serviceDetails_01);
+ }
+
+ public void init() {
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ resourceDetailsVF_01 = ElementFactory.getDefaultImportResourceByType("VF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsVF_02 = ElementFactory.getDefaultResourceByType("VF200", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsVF_03 = ElementFactory.getDefaultResourceByType("VF300", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("CP100", NormativeTypesEnum.PORT, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(), ResourceTypeEnum.CP.toString());
+ serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId());
+ serviceDetails_02 = ElementFactory.getDefaultService("newtestservice2", ServiceCategoriesEnum.MOBILITY, sdncDesignerDetails.getUserId());
+ }
+
+ @Test
+ public void downloadResourceInstanceArtifactsFromServiceTest() throws Exception {
+ Service service = createServiceWithRIsWithArtifacts();
+ Map<String, ArtifactDefinition> deploymentArtifacts;
+ List<ComponentInstance> resourceInstances = service.getComponentInstances();
+ for (ComponentInstance ri : resourceInstances) {
+ deploymentArtifacts = ri.getDeploymentArtifacts();
+ for (ArtifactDefinition artifact : deploymentArtifacts.values()) {
+ assertNotNull(downloadResourceInstanceArtifact(service, ri, artifact));
+ }
+ }
+ }
+
+ @Test
+ public void downloadServiceArtifactsTest() throws Exception {
+ Service service = createServiceWithArtifacts();
+ Map<String, ArtifactDefinition> deploymentArtifacts = service.getDeploymentArtifacts();
+ for (ArtifactDefinition artifact : deploymentArtifacts.values()) {
+ assertNotNull(downloadServiceArtifact(service, artifact));
+ }
+
+ }
+
+ private Service createServiceWithArtifacts() throws Exception {
+
+ ArtifactReqDetails otherArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.OTHER.getType());
+
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(otherArtifactDetails, sdncDesignerDetails, serviceDetails_01.getUniqueId());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ ArtifactReqDetails yangXmlArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.YANG_XML.getType());
+
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(yangXmlArtifactDetails, sdncDesignerDetails, serviceDetails_01.getUniqueId());
+ assertTrue("response code is not BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + addInformationalArtifactToService.getErrorCode(), addInformationalArtifactToService.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ RestResponse createServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ return ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse());
+ }
+
+ private RestResponse downloadResourceInstanceArtifact(Service service, ComponentInstance ri, ArtifactDefinition artifact) throws Exception {
+ String url = String.format(Urls.GET_DOWNLOAD_SERVICE_RI_ARTIFACT, "localhost", "8080", service.getUUID(), ri.getNormalizedName(), artifact.getArtifactUUID());
+ String userId = sdncDesignerDetails.getUserId();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
+ headersMap.put("X-ECOMP-InstanceID", "test");
+ if (userId != null) {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
+ }
+ sendAuthorizationRequest();
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendGet(url, headersMap);
+ if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
+ return null;
+ }
+ return response;
+ }
+
+ private RestResponse downloadServiceArtifact(Service service, ArtifactDefinition artifact) throws Exception {
+ String url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT, "localhost", "8080", service.getUUID(), artifact.getArtifactUUID());
+ String userId = sdncDesignerDetails.getUserId();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), "Basic dGVzdDoxMjM0NTY=");
+ headersMap.put("X-ECOMP-InstanceID", "test");
+ if (userId != null) {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
+ }
+ sendAuthorizationRequest();
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendGet(url, headersMap);
+ if (response.getErrorCode() != 200 && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) {
+ return null;
+ }
+ return response;
+
+ }
+
+ private RestResponse sendAuthorizationRequest() throws IOException {
+ String url = String.format(Urls.POST_AUTHORIZATION, "localhost", "8080");
+ String userId = sdncAdminDetails.getUserId();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
+ if (userId != null) {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
+ }
+
+ HttpRequest http = new HttpRequest();
+ RestResponse response = http.httpSendPost(url, "{\"consumerName\":\"test\",\"consumerPassword\":\"0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b\",\"consumerSalt\":\"2a1f887d607d4515d4066fe0f5452a50\"}", headersMap);
+ if (response.getErrorCode() != 201) {
+ return null;
+ }
+ return response;
+ }
+
+ private Service createServiceWithRIsWithArtifacts() throws Exception {
+ serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId());
+ createTreeCheckedinVFInstances();
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncDesignerDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01, sdncDesignerDetails);
+ RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(updateServiceResp);
+ getComponentAndValidateRIs(serviceDetails_01, 5, 0);
+
+ return ResponseParser.convertServiceResponseToJavaObject(updateServiceResp.getResponse());
+ }
+
+ private void createTreeCheckedinVFInstances() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createSecondVFInstResp);
+ RestResponse createThirdVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_03, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createThirdVFInstResp);
+ }
+
+ private Component getComponentAndValidateRIs(ComponentReqDetails componentDetails, int numberOfRIs, int numberOfRelations) throws IOException, Exception {
+
+ RestResponse getResponse = null;
+ Component component = null;
+ if (componentDetails instanceof ResourceReqDetails) {
+ getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (componentDetails instanceof ServiceReqDetails) {
+ getResponse = ServiceRestUtils.getService((ServiceReqDetails) componentDetails, sdncAdminDetails);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else if (componentDetails instanceof ProductReqDetails) {
+ getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
+ } else {
+ Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
+ }
+ ResourceRestUtils.checkSuccess(getResponse);
+ int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size() : 0;
+ int numberOfActualRelations = component.getComponentInstancesRelations() != null ? component.getComponentInstancesRelations().size() : 0;
+ assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
+ assertEquals("Check number of RI relations meet the expected number", numberOfRelations, numberOfActualRelations);
+
+ return component;
+ }
+
+ private void createVFInstanceAndAtomicResourceInstanceWithoutCheckin(ResourceReqDetails vf, ResourceReqDetails atomicResource, User user) throws Exception {
+ RestResponse createVFInstance = createVFInstance(serviceDetails_01, vf, user);
+ ResourceRestUtils.checkCreateResponse(createVFInstance);
+ RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, atomicResource, user);
+ ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
+ }
+
+ private RestResponse createCheckedinVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ changeResourceLifecycleState(compInstOriginDetails, modifier.getUserId(), LifeCycleStatesEnum.CHECKIN);
+ return createVFInstance(containerDetails, compInstOriginDetails, modifier);
+ }
+
+ private RestResponse createVFInstance(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ private RestResponse createAtomicInstanceForService(ServiceReqDetails containerDetails, ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ private RestResponse createComponentInstance(ComponentReqDetails containerDetails, ComponentReqDetails compInstOriginDetails, User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel) throws IOException, Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(compInstOriginDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum);
+ return createResourceInstanceResponse;
+ }
+
+ private void changeResourceLifecycleState(ResourceReqDetails resourceDetails, String userId, LifeCycleStatesEnum lifeCycleStates) throws Exception {
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userId, lifeCycleStates);
+ LifecycleRestUtils.checkLCS_Response(response);
+ }
+
+ private void createAtomicResource(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceResponse);
+
+ }
+
+ private void createVF(ResourceReqDetails resourceDetails) throws Exception {
+ createVF(resourceDetails, sdncDesignerDetails);
+
+ }
+
+ private void createVF(ResourceReqDetails resourceDetails, User sdncModifier) throws Exception {
+ RestResponse createVfResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifier);
+ ResourceRestUtils.checkCreateResponse(createVfResponse);
+ }
+
+ private void createService(ServiceReqDetails serviceDetails) throws Exception {
+ createService(serviceDetails, sdncDesignerDetails);
+ }
+
+ private void createService(ServiceReqDetails serviceDetails, User sdncModifier) throws Exception {
+ RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, sdncModifier);
+ ResourceRestUtils.checkCreateResponse(createServiceResponse);
+ }
+
+ private void importVfWithArtifacts(ImportReqDetails resourceDetailsVF_01) throws Exception {
+ String payloadName = "VF_RI2_G4_withArtifacts.csar";
+ Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetailsVF_01.setPayloadData(payloadData);
+
+ resourceDetailsVF_01.setPayloadName(payloadName);
+ resourceDetailsVF_01.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetailsVF_01, sdncDesignerDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
new file mode 100644
index 0000000000..83a50baeeb
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/BasicHttpAuthenticationTest.java
@@ -0,0 +1,403 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+//US505653
+package org.openecomp.sdc.ci.tests.execute.general;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class BasicHttpAuthenticationTest extends ComponentBaseTest {
+
+ protected static final String AUTH_FAILED_INVALID_AUTHENTICATION_HEADER = "AUTH_FAILED_INVALID_AUTHENTICATION_HEADER";
+
+ protected static final String AUTH_SUCCESS = "AUTH_SUCCESS";
+
+ protected static final String AUTH_FAILED_INVALID_PASSWORD = "AUTH_FAILED_INVALID_PASSWORD";
+
+ protected static final String AUTH_FAILED_USER_NOT_FOUND = "AUTH_FAILED_USER_NOT_FOUND";
+
+ protected static final String AUTH_REQUIRED = "AUTH_REQUIRED";
+
+ protected static final String WWW_AUTHENTICATE = "WWW-Authenticate";
+
+ // user ci password 123456
+ // protected final String authorizationHeader = "Basic Y2k6MTIzNDU2";
+ // user ci password 123456
+ protected final String USER = "ci";
+
+ protected final String PASSWORD = "123456";
+
+ protected final String SALT = "2a1f887d607d4515d4066fe0f5452a50";
+
+ protected final String HASHED_PASSWORD = "0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b";
+
+ protected User sdncAdminUserDetails;
+
+ protected ConsumerDataDefinition consumerDataDefinition;
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected User sdncUserDetails;
+
+ protected ArtifactReqDetails deploymentArtifact;
+
+ protected ExpectedAuthenticationAudit expectedAuthenticationAudit;
+
+ protected final String auditAction = "HttpAuthentication";
+
+ protected String expectedDownloadServiceUrl;
+ protected String expectedDownloadResourceUrl;
+ protected ComponentInstanceReqDetails componentInstanceReqDetails;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public BasicHttpAuthenticationTest() {
+ super(name, BasicHttpAuthenticationTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ Resource resourceObject = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetails = new ResourceReqDetails(resourceObject);
+ Service serviceObject = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ serviceDetails = new ServiceReqDetails(serviceObject);
+
+ deploymentArtifact = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(deploymentArtifact, sdncUserDetails, resourceDetails.getUniqueId());
+ AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), response.getErrorCode() == 200);
+
+ componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+ // certified resource
+ response = LifecycleRestUtils.certifyResource(resourceDetails);
+ AssertJUnit.assertTrue("certify resource request returned status:" + response.getErrorCode(), response.getErrorCode() == 200);
+
+ // add resource instance with HEAT deployment artifact to the service
+ componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncUserDetails, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ AssertJUnit.assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201);
+ expectedAuthenticationAudit = new ExpectedAuthenticationAudit();
+
+ // RestResponse addDeploymentArtifactResponse =
+ // ArtifactRestUtils.addInformationalArtifactToService(deploymentArtifact,
+ // sdncUserDetails, serviceDetails.getUniqueId());
+ // assertEquals("didn't succeed to upload deployment artifact", 200,
+ // addDeploymentArtifactResponse.getErrorCode().intValue());
+ //
+ // downloadUrl =
+ // String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL,
+ // ValidationUtils.convertToSystemName(serviceDetails.getServiceName()),
+ // serviceDetails.getVersion(),
+ // ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
+
+ expectedDownloadResourceUrl = String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
+ ValidationUtils.convertToSystemName(resourceDetails.getName()), resourceDetails.getVersion(), ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
+ expectedDownloadResourceUrl = expectedDownloadResourceUrl.substring("/asdc/".length(), expectedDownloadResourceUrl.length());
+
+ expectedDownloadServiceUrl = String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceDetails.getVersion(),
+ ValidationUtils.normalizeFileName(deploymentArtifact.getArtifactName()));
+ expectedDownloadServiceUrl = expectedDownloadServiceUrl.substring("/asdc/".length(), expectedDownloadServiceUrl.length());
+
+ sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ consumerDataDefinition = createConsumer();
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ ;
+
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkCreateResponse(createResponse);
+
+ }
+
+ @AfterMethod
+ public void tearDown() throws Exception {
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ ;
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_success() throws Exception, Exception {
+ DbUtils.cleanAllAudits();
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD);
+ // RestResponse restResponse =
+ // ArtifactRestUtils.downloadServiceArtifact(serviceDetails,
+ // deploymentArtifact, sdncUserDetails, authorizationHeader);
+ RestResponse restResponse = ArtifactRestUtils.downloadResourceArtifact(serviceDetails, resourceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ AssertJUnit.assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+ AssertJUnit.assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue()));
+
+ validateAuditAuthentication(USER, AUTH_SUCCESS, ComponentTypeEnum.RESOURCE);
+
+ }
+
+ protected void validateAuditAuthentication(String userName, String AuthStatus, ComponentTypeEnum compType) throws Exception {
+ if (compType.equals(ComponentTypeEnum.RESOURCE)) {
+ expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadResourceUrl, userName, auditAction, AuthStatus);
+ } else {
+ expectedAuthenticationAudit = new ExpectedAuthenticationAudit(expectedDownloadServiceUrl, userName, auditAction, AuthStatus);
+ }
+ AuditValidationUtils.validateAuthenticationAudit(expectedAuthenticationAudit);
+ }
+
+ protected ConsumerDataDefinition createConsumer() {
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName(USER);
+ consumer.setConsumerSalt(SALT);
+ consumer.setConsumerPassword(HASHED_PASSWORD);
+ return consumer;
+
+ }
+
+ @Test
+ public void sendAuthenticatedRequestWithoutHeadersTest() throws Exception, Exception {
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, new HashMap<String, String>());
+ assertEquals("Check response code after download artifact", 401, restResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_REQUIRED.name(), new ArrayList<String>(), restResponse.getResponse());
+ assertTrue(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
+ List<String> getAuthenticateHeader = restResponse.getHeaderFields().get(WWW_AUTHENTICATE);
+ assertEquals("www-authenticate header contains more then one value", 1, getAuthenticateHeader.size());
+ assertTrue(getAuthenticateHeader.get(0).equals("Basic realm=" + "\"ASDC\""));
+
+ validateAuditAuthentication("", AUTH_REQUIRED, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_userIsNotProvsioned() throws Exception, Exception {
+ String userName = "shay";
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, "123456");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList<String>(), restResponse.getResponse());
+ assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
+
+ validateAuditAuthentication(userName, AUTH_FAILED_USER_NOT_FOUND, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_userIsNull() throws Exception, Exception {
+ String userName = "";
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, "123456");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList<String>(), restResponse.getResponse());
+ assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
+
+ validateAuditAuthentication(userName, AUTH_FAILED_USER_NOT_FOUND, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_passwordIsNull() throws Exception, Exception {
+ String userName = "ci";
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(userName, "");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList<String>(), restResponse.getResponse());
+ assertFalse(restResponse.getHeaderFields().containsKey(WWW_AUTHENTICATE));
+
+ validateAuditAuthentication(userName, AUTH_FAILED_INVALID_PASSWORD, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_passowrdIsNotValidated() throws Exception, Exception {
+ String userCi = "ci";
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(userCi, "98765");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 403, restResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.AUTH_FAILED.name(), new ArrayList<String>(), restResponse.getResponse());
+ assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue()));
+
+ validateAuditAuthentication(userCi, AUTH_FAILED_INVALID_PASSWORD, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test
+ public void sendAuthenticatedRequestTest_InvalidHeader() throws Exception, Exception {
+ String userCredentials = USER + ":" + PASSWORD;
+ byte[] encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
+ String encodedUserCredentials = new String(encodeBase64);
+ Map<String, String> authorizationHeader = new HashMap<String, String>();
+ authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 400, restResponse.getErrorCode().intValue());
+ assertFalse(restResponse.getHeaderFields().containsKey(HttpHeaderEnum.WWW_AUTHENTICATE.getValue()));
+
+ validateAuditAuthentication("", AUTH_FAILED_INVALID_AUTHENTICATION_HEADER, ComponentTypeEnum.SERVICE);
+ }
+
+ @Test(enabled = false)
+ public void sendTwoAuthenticatedRequestsTest() throws Exception, Exception {
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(USER, PASSWORD);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+
+ RestResponse secondRestResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after second download artifact", 200, secondRestResponse.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void sendAuthenticatedRequestTest_userValidation_1() throws Exception, Exception {
+
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName("cI2468");
+ consumer.setConsumerPassword(HASHED_PASSWORD);
+ consumer.setConsumerSalt(SALT);
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkCreateResponse(createResponse);
+
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(consumer.getConsumerName(), PASSWORD);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+
+ deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ }
+
+ // ECOMP Consumer Name - UTF-8 string up to 255 characters containing the
+ // following characters : ( maybe to limit 4-64 chars ? )
+ // Lowercase characters {a-z}
+ // Uppercase characters {A-Z}
+ // Numbers {0-9}
+ // Dash {-}; this character is not supported as the first character in the
+ // user name
+ // Period {.}; this character is not supported as the first character in the
+ // user name
+ // Underscore {_}
+ // @Ignore("add manually user:password 24-!68:123456 to
+ // users-configuration.yaml in runtime")
+ @Test(enabled = false)
+ public void sendAuthenticatedRequestTest_userValidation_2() throws Exception, Exception {
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName("24-!68");
+ consumer.setConsumerPassword(HASHED_PASSWORD);
+ consumer.setConsumerSalt(SALT);
+ RestResponse deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkCreateResponse(createResponse);
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader(consumer.getConsumerName(), PASSWORD);
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+
+ deleteResponse = ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails);
+ BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed", false, 404, 200);
+ }
+
+ // this is invalide becouse we do not use the : any more
+ // @Ignore("can't exectue, yaml file does not allow to enter more then one
+ // colon continuously (\":\") ")
+ @Test(enabled = false)
+ public void sendAuthenticatedRequestTest_userValidation_3() throws Exception, Exception {
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader("a:", "123456");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+ }
+
+ //
+ // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value (
+ // SALT + "real" password ) => maximal length 256 bytes = 32 characters
+ // Before storing/comparing please convert upper case letter to lower.
+ // The "normalized" encrypted password should match the following format :
+ // [a-z0-9]
+ // @Ignore("add manually user:password 2468:123:456 to
+ // users-configuration.yaml in runtime")
+ @Test(enabled = false)
+ public void sendAuthenticatedRequestTest_passwordValidation_1() throws Exception, Exception {
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader("A1", "123:456");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+ }
+
+ // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value (
+ // SALT + "real" password ) => maximal length 256 bytes = 32 characters
+ // Before storing/comparing please convert upper case letter to lower.
+ // The "normalized" encrypted password should match the following format :
+ // [a-z0-9]
+ @Test(enabled = false)
+ // @Ignore("add manually user:password 2468:Sq123a456B to
+ // users-configuration.yaml in runtime")
+ public void sendAuthenticatedRequestTest_passwordValidation_2() throws Exception, Exception {
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader("B2", "Sq123a456B");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+ }
+
+ // * ECOMP Consumer Password - expected to be SHA-2 256 encrypted value (
+ // SALT + "real" password ) => maximal length 256 bytes = 32 characters
+ // Before storing/comparing please convert upper case letter to lower.
+ // The "normalized" encrypted password should match the following format :
+ // [a-z0-9]
+ @Test
+ // @Ignore("add C3:111T-0-*# to file")
+ public void sendAuthenticatedRequestTest_passwordValidation_3() throws Exception, Exception {
+ Map<String, String> authorizationHeader = BaseRestUtils.addAuthorizeHeader("C3", "111T-0-*#");
+ RestResponse restResponse = ArtifactRestUtils.downloadServiceArtifact(serviceDetails, deploymentArtifact, sdncUserDetails, authorizationHeader);
+ assertEquals("Check response code after download artifact", 200, restResponse.getErrorCode().intValue());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java
new file mode 100644
index 0000000000..e4f7d396be
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/FeProxyTest.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.general;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.Test;
+
+public class FeProxyTest extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public FeProxyTest() {
+ super(name, FeProxyTest.class.getName());
+ }
+
+ @Test
+ public void testFeProxy() throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ RestResponse allCategoriesTowardsFe = CategoryRestUtils.getAllCategoriesTowardsFe(defaultUser,
+ BaseRestUtils.RESOURCE_COMPONENT_TYPE);
+ AssertJUnit.assertEquals("Check response code after get categories towards FE", 200,
+ allCategoriesTowardsFe.getErrorCode().intValue());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java
new file mode 100644
index 0000000000..9e1b151c49
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/ManageEcompConsumerCredentials.java
@@ -0,0 +1,1388 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.general;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.util.HashMap;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ManageEcompConsumerCredentials extends ComponentBaseTest {
+
+ protected static final String ADD_ECOMP_USER_CREDENTIALS = "AddECOMPUserCredentials";
+ protected static final String DELETE_ECOMP_USER_CREDENTIALS = "DeleteECOMPUserCredentials";
+ protected static final String GET_ECOMP_USER_CREDENTIALS = "GetECOMPUserCredentials";
+
+ public static final String contentTypeHeaderData = "application/json";
+ public static final String acceptHeaderData = "application/json";
+
+ public static final int STATUS_CODE_SUCCESS = 200;
+ public static final int STATUS_CODE_SUCSESS_CREATED = 201;
+ public static final int STATUS_CODE_SUCCESS_DELETE_GET = 200;
+ public static final int STATUS_CODE_INVALID_CONTENT = 400;
+ public static final int STATUS_CODE_MISSING_DATA = 400;
+ public static final int STATUS_CODE_MISSING_INFORMATION = 403;
+ public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
+
+ public static final int STATUS_CODE_NOT_FOUND = 404;
+ public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
+
+ protected static Gson gson = new Gson();
+ protected ConsumerDataDefinition consumerDataDefinition;
+ protected User sdncAdminUserDetails;
+ protected User sdncDesignerUserDetails;
+ protected User sdncTesterUserDetails;
+ protected User sdncGovernorUserDetails;
+ protected User sdncOpsUserDetails;
+
+ public ManageEcompConsumerCredentials() {
+ super(name, ManageEcompConsumerCredentials.class.getName());
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ protected String salt = "123456789012345678901234567890ab";
+ protected String password = "123456789012345678901234567890ab123456789012345678901234567890ab";
+ protected String ecompUser = "benny";
+
+ protected Long consumerDetailsLastupdatedtime;
+
+ @BeforeMethod
+ public void init() throws Exception {
+ sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncDesignerUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncTesterUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncGovernorUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ sdncOpsUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+
+ consumerDataDefinition = new ConsumerDataDefinition();
+ consumerDataDefinition.setConsumerName(ecompUser);
+ consumerDataDefinition.setConsumerPassword(password);
+ consumerDataDefinition.setConsumerSalt(salt);
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+
+ }
+
+ // US563681 manage ECOMP consumer credentials - DELETE/GET
+ @Test
+ public void deleteEcompCredentialsMethodDelete() throws Exception {
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ AssertJUnit.assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ // DbUtils.deleteFromEsDbByPattern("_all");
+ DbUtils.cleanAllAudits();
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET);
+ // Get Consumer to verify that consumer user does not exist
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ AssertJUnit.assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ //// US561728 CREATE ECOMP consumer credentials
+ @Test
+ public void createEcompCredentialsMethodPost() throws Exception {
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ // Validate actual consumerData to returned from response
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ }
+
+ @Test(enabled = false)
+ public void createEcompCredentialsUserAlreayExist() throws Exception {
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+
+ // Create consumer which already exists with different password and Salt
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerPassword("zxcvb");
+ consumerDataDefinition.setConsumerSalt("1234567890qwertyuiop1234567890as");
+ createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer with new data
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsByDesigner() throws Exception { // HttpCspUserId header contains Designer UserId
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncDesignerUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ }
+
+ @Test
+ public void createEcompCredentialsByTester() throws Exception { // HttpCspUserId header contains Tester UserId
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncTesterUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION, createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND, getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition, sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ }
+
+ @Test
+ public void createEcompCredentialsByOps() throws Exception { // HttpCspUserId header contains OPS UserId
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, sdncOpsUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ }
+
+ @Test
+ public void createEcompCredentialsByGovernor() throws Exception { // HttpCspUserId header contains Governor UserId Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncGovernorUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ }
+
+ @Test
+ public void createEcompCredentialsByNoExistingIUser() throws Exception {
+ User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ noSdncUserDetails.setRole("blabla");
+ noSdncUserDetails.setUserId("bt750h");
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition, noSdncUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(
+ consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase()
+ + "," + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ // user name
+ @Test
+ public void createEcompCredentialsUserNameIsNull() throws Exception {
+ consumerDataDefinition.setConsumerName(null); // SVC4528
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA,
+ createConsumerRest.getErrorCode().intValue());
+ // verify taht consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerSalt().toLowerCase() + ","
+ + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer name"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameIsEmpty() throws Exception {
+ consumerDataDefinition.setConsumerName("");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerSalt().toLowerCase() + ","
+ + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer name"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameIsNotUTF8() throws Exception {
+ consumerDataDefinition.setConsumerName("בני"); // SVC4528
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameMaxLength() throws Exception {
+ consumerDataDefinition.setConsumerName(
+ "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.-"); // SVC4528
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Validate actual consumerData to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameExceedMaxLength() throws Exception {
+ consumerDataDefinition.setConsumerName(
+ "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.EXCEEDS_LIMIT, "Consumer name", "255");
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameLastCharIsDash() throws Exception { // allowed
+ consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew-");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject , Validate actual consumerData
+ // to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameLastCharIsPeriod() throws Exception {
+ consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew.");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject , Validate actual consumerData
+ // to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameLastCharIsUnderscore() throws Exception {
+ consumerDataDefinition.setConsumerName("ABCD34567890pf34567890poiutrew_");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject , Validate actual consumerData
+ // to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameFirstCharIsUnderscore() throws Exception {
+ consumerDataDefinition.setConsumerName("_ABCD34567890pf34567890poiutre");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject , Validate actual consumerData
+ // to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameFirstCharIsPeriod() throws Exception {
+ consumerDataDefinition.setConsumerName(".ABCD34567890pf34567890poiutre");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name");
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameFirstCharIsDash() throws Exception { // Not
+ // allowed
+ consumerDataDefinition.setConsumerName("-ABCD34567890pf34567890poiutre");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name");
+ }
+
+ /// Password
+ @Test
+ public void createEcompCredentialsPasswordIsNull() throws Exception {
+ consumerDataDefinition.setConsumerPassword(null);
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA,
+ createConsumerRest.getErrorCode().intValue());
+ // verify taht consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer password"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsPasswordIsEmpty() throws Exception {
+ consumerDataDefinition.setConsumerPassword("");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA,
+ createConsumerRest.getErrorCode().intValue());
+ // verify taht consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer password"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsPasswordMaxLength() throws Exception { // password
+ // must
+ // be
+ // 64
+ // chars
+ consumerDataDefinition.setConsumerPassword("123456789012345678901234567890ab123456789012345678901234567890ab");
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ // Validate actual consumerData to returned from response
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ // Delete Consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsPasswordExceeedMaxLength() throws Exception { // password
+ // must
+ // be
+ // 64
+ // chars
+ consumerDataDefinition.setConsumerPassword("123456789012345678901234567890ab123456789012345678901234567890ab1");
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer password", "64");
+ }
+
+ @Test
+ public void createEcompCredentiaPasswordValid() throws Exception {
+ // Password Contains lowercase/uppercase characters and numbers -
+ // convert upper case letter to lower
+ consumerDataDefinition.setConsumerPassword("ABCabc1234567890POImnb12345678901234567890POIUzxcvbNMASDFGhjkl12");
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+
+ }
+
+ //// Salt
+ @Test
+ public void createEcompCredentialsSaltIsNull() throws Exception {
+ // Length must be 32 characters
+ consumerDataDefinition.setConsumerSalt(null);
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerPassword().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+
+ }
+
+ @Test
+ public void createEcompCredentialsSaltIsEmpty() throws Exception {
+ consumerDataDefinition.setConsumerSalt("");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_DATA,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerPassword().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsSaltLengthLessThan32() throws Exception {
+ consumerDataDefinition.setConsumerSalt("123456789012345678901234567890a");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer salt");
+
+ }
+
+ // Bug
+ @Test
+ public void createEcompCredentialsSaltLengthMoreThan32() throws Exception { // Length
+ // must
+ // be
+ // 32
+ // characters
+ // -
+ // SVC4529
+ // "Error:
+ // Invalid
+ // Content.
+ // %1
+ // exceeds
+ // limit
+ // of
+ // %2
+ // characters."
+ consumerDataDefinition.setConsumerSalt("123456789012345678901234567890abc");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_LENGTH, "Consumer salt");
+
+ }
+
+ @Test
+ public void createEcompCredentialsSaltUppercaseCharacters() throws Exception {
+ // Contains uppercase characters– exception invalid content
+ consumerDataDefinition.setConsumerSalt("123456789012345678901234567890AB");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // verify that consumer didn't created
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT_PARAM.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject
+ .setModifier(sdncAdminUserDetails.getFullName() + "(" + sdncAdminUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ // USER_ID (USER_ID is taken from USER_ID header)
+
+ @Test
+ public void createEcompCredentialsHttpCspUserIdIsEmpty() throws Exception {
+ // USER_ID is taken from USER_ID header
+ sdncAdminUserDetails.setUserId("");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject.setModifier("");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsHttpCspUserIdIsNull() throws Exception { // USER_ID is taken from USER_ID header
+ sdncAdminUserDetails.setUserId(null);
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject.setModifier("");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void createEcompCredentialsHttpCspUserIdHeaderIsMissing() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumerHttpCspAtuUidIsMissing(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName() + ","
+ + consumerDataDefinition.getConsumerSalt() + "," + consumerDataDefinition.getConsumerPassword());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc("Consumer salt"));
+ expectedEcomConsumerAuditJavaObject.setModifier("");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ ADD_ECOMP_USER_CREDENTIALS);
+ }
+
+ // add USER_ID in json body
+ @Test
+ public void createEcompCredentiaJsonBodyContainLastModfierAtuid() throws Exception {
+ // Add USER_ID (not admin) to json - we will ignore and create the user
+ HashMap<String, String> jsonMap = new HashMap<String, String>();
+ jsonMap.put("consumerName", "benny");
+ jsonMap.put("consumerPassword", "123456789012345678901234567890ab123456789012345678901234567890ab");
+ jsonMap.put("consumerSalt", "123456789012345678901234567890ab");
+ jsonMap.put("lastModfierAtuid", "cs0008"); // designer
+ Gson gson = new Gson();
+ ConsumerDataDefinition consumer = gson.fromJson(jsonMap.toString(), ConsumerDataDefinition.class);
+
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumer, sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Validate actual consumerData to returned from response
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumer, getConsumerDataObject);
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumer, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumer, sdncAdminUserDetails,
+ STATUS_CODE_SUCSESS_CREATED);
+ // Delete consumer
+ ConsumerRestUtils.deleteConsumer(consumer, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void createEcompCredentialsUserNameNotAllowedCharacters() throws Exception {
+ char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/',
+ '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName(invalidChars[i] + "ABCdef123");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer name");
+ }
+ }
+
+ @Test
+ public void createEcompCredentialsPasswordIsInvalid() throws Exception {
+ char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/',
+ '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerPassword(
+ "ABC" + invalidChars[i] + "ABCabc1234567890POImnb12345678901234567890POIUzxcvbNMASDFGhj");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer password");
+ }
+ }
+
+ @Test
+ public void createEcompCredentialsSaltNotAllowedCharacters() throws Exception { // Salt
+ // must
+ // be
+ // 32
+ // chars
+ char invalidChars[] = { '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/',
+ '"', ':', '}', ']', '[', '{', '|', '\\', ' ', '\t', '\n' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerSalt(invalidChars[i] + "1234567890123456789012345678901");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_INVALID_CONTENT,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.createEcompConsumerAuditFailure(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.INVALID_CONTENT_PARAM, "Consumer salt");
+ }
+ }
+
+ @Test
+ public void createEcompCredentialsPasswordEncoded() throws Exception {
+ consumerDataDefinition.setConsumerPassword("0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ // Validate actual consumerData to returned from response
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(ADD_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCSESS_CREATED);
+ }
+
+ //
+
+ @Test
+ public void deleteEcompUserAlreayDeleted() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete ECOMP consumer
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Try to delete ECOMP consumer already deleted
+ DbUtils.deleteFromEsDbByPattern("_all");
+ deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void deleteEcompUserByTester() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncTesterUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Verify that consumer is not deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteEcompUserByOps() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncOpsUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Verify that consumer is not deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteEcompUserByGovernor() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncGovernorUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Verify that consumer is not deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteEcompUserByDesigner() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncDesignerUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Verify that consumer is not deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteEcompUserByNoExistingIUser() throws Exception {
+ User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ noSdncUserDetails.setRole("blabla");
+ noSdncUserDetails.setUserId("bt750h");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition, noSdncUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_ACCESS,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(ADD_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ DELETE_ECOMP_USER_CREDENTIALS);
+ // Verify that consumer is not deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteEcompCredentialsUserDoesNotExist() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+
+ }
+
+ @Test
+ public void deleteEcompCredentialsUserNameIsNull() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName(null);
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void deleteEcompCredentialsUserNameMaxLength() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName(
+ "_BCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void deleteEcompCredentialsUserNameExceedMaxLength() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName(
+ "_XXXBCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.--"); // SVC4528
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void deleteEcompCredentialsHttpCspUserIdHeaderIsMissing() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse createConsumerRest = ConsumerRestUtils.deleteConsumerHttpCspAtuUidIsMissing(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_MISSING_INFORMATION,
+ createConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(DELETE_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc());
+ expectedEcomConsumerAuditJavaObject.setModifier("");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ DELETE_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void deleteEcompCredentialsNameIsUpperCase() throws Exception {
+ consumerDataDefinition.setConsumerName("benny");
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName("BENNY");
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ deleteConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(DELETE_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ // Get Consumer to verify that consumer user was not deleted
+ consumerDataDefinition.setConsumerName("benny");
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ }
+
+ @Test
+ public void getEcompCredentialsMethodGet() throws Exception {
+ // Create Consumer
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ // Validate actual consumerData to returned from response
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET);
+ // Delete consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void getEcompUserAlreayDeleted() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Delete ECOMP consumer
+ RestResponse deleteConsumerRest = ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS_DELETE_GET,
+ deleteConsumerRest.getErrorCode().intValue());
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // Try to get ECOMP consumer already deleted
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void getEcompUserByTester() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer by Tester user
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncTesterUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncTesterUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Get Consumer by Admin
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void getEcompUserByOps() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer by Ops user
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncOpsUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncOpsUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Get Consumer by Admin
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void getEcompUserByGovernor() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer by Ops user
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncGovernorUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncGovernorUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Get Consumer by Admin
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void getEcompUserByDesigner() throws Exception {
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // Get Consumer by Designer user
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncDesignerUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_OPERATION,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncDesignerUserDetails, ActionStatus.RESTRICTED_OPERATION);
+ // Get Consumer by Admin
+ getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+
+ @Test
+ public void getEcompUserByNoExistingIUser() throws Exception {
+ User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ noSdncUserDetails.setRole("blabla");
+ noSdncUserDetails.setUserId("bt750h");
+ // Get Consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, noSdncUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_RESTRICTED_ACCESS,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(GET_ECOMP_USER_CREDENTIALS);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(""));
+ expectedEcomConsumerAuditJavaObject.setModifier("(" + noSdncUserDetails.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject,
+ GET_ECOMP_USER_CREDENTIALS);
+ }
+
+ @Test
+ public void getEcompCredentialsUserDoesNotExist() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+
+ }
+
+ @Test
+ public void getEcompCredentialsUserNameIsNull() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ consumerDataDefinition.setConsumerName(null);
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_NOT_FOUND,
+ getConsumerRest.getErrorCode().intValue());
+ // Audit validation
+ AuditValidationUtils.deleteEcompConsumerAuditFailure(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, ActionStatus.ECOMP_USER_NOT_FOUND, consumerDataDefinition.getConsumerName());
+ }
+
+ @Test
+ public void getEcompCredentialsUserNameMaxLength() throws Exception {
+ consumerDataDefinition.setConsumerName(
+ "_ABCD-.abcdqwertyuiopasdfghjklzxcvbnmqw1234567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfg34567890pf34567890poiutrewasdfghjklqwertyuiopzaiutrewasdfgghjklqwertyuiopzaiutrewasdfghjklqwertyuiopzasxcdferf123456.-"); // SVC4528
+ RestResponse createConsumerRest = ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ sdncAdminUserDetails);
+ assertEquals("Check response code after create Consumer", STATUS_CODE_SUCSESS_CREATED,
+ createConsumerRest.getErrorCode().intValue());
+ // parse updated response to javaObject
+ ConsumerDataDefinition getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(createConsumerRest);
+ // Validate actual consumerData to returned from response
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Get Consumer
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse getConsumerRest = ConsumerRestUtils.getConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ assertEquals("Check response code after get Consumer", STATUS_CODE_SUCCESS,
+ getConsumerRest.getErrorCode().intValue());
+ getConsumerDataObject = ConsumerRestUtils.parseComsumerResp(getConsumerRest);
+ ConsumerRestUtils.validateConsumerReqVsResp(consumerDataDefinition, getConsumerDataObject);
+ // Audit validation
+ AuditValidationUtils.ecompConsumerAuditSuccess(GET_ECOMP_USER_CREDENTIALS, consumerDataDefinition,
+ sdncAdminUserDetails, STATUS_CODE_SUCCESS_DELETE_GET);
+ // Delete consumer
+ ConsumerRestUtils.deleteConsumer(consumerDataDefinition, sdncAdminUserDetails);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java
new file mode 100644
index 0000000000..acb7e15c6c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/general/UuidTest.java
@@ -0,0 +1,104 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.general;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.UUID;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.AssertJUnit;
+import org.testng.annotations.Test;
+
+public class UuidTest extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public UuidTest() {
+ super(name, UuidTest.class.getName());
+ config = Config.instance();
+ }
+
+ @Test
+ public void testE2EUuidHeaderReturnedAndPreserved() throws IOException {
+ UUID randomUUID = UUID.randomUUID();
+ String uuidStr = randomUUID.toString();
+ RestResponse allTagsTowardsCatalogFe = CatalogRestUtils.getAllCategoriesTowardsCatalogFeWithUuid(uuidStr);
+ AssertJUnit.assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(200));
+ List<String> list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER);
+ // check that header is returned
+ AssertJUnit.assertTrue(list != null && !list.isEmpty());
+ String receivedUuid = list.get(0);
+ // Check that same uuid returned
+ AssertJUnit.assertEquals(uuidStr, receivedUuid);
+ }
+
+ @Test
+ public void testUuidHeaderGeneratedBe() throws IOException {
+ RestResponse allTagsTowardsCatalogBe = CatalogRestUtils.getAllCategoriesTowardsCatalogBe();
+ List<String> list = allTagsTowardsCatalogBe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER);
+ // check that response was OK
+ assertEquals(allTagsTowardsCatalogBe.getErrorCode(), new Integer(200));
+ // check that header is returned
+ assertTrue(list != null && !list.isEmpty());
+ String uuid = list.get(0);
+ // Check there is no conversion error
+ UUID.fromString(uuid);
+ }
+
+ @Test
+ public void testE2EOptionsNoUuid() throws IOException {
+ RestResponse allTagsTowardsCatalogFe = ResourceRestUtils.sendOptionsTowardsCatalogFeWithUuid();
+ assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(200));
+ List<String> list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER);
+ // check that header is returned (generated by BE)
+ assertTrue(list != null && !list.isEmpty());
+ String receivedUuid = list.get(0);
+ // Check there is no conversion error
+ UUID.fromString(receivedUuid);
+ }
+
+ @Test
+ public void testE2EMethodNotAllowedWithUuid() throws IOException {
+ UUID randomUUID = UUID.randomUUID();
+ String uuidStr = randomUUID.toString();
+ RestResponse allTagsTowardsCatalogFe = ResourceRestUtils
+ .putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(uuidStr);
+ assertEquals(allTagsTowardsCatalogFe.getErrorCode(), new Integer(405));
+ List<String> list = allTagsTowardsCatalogFe.getHeaderFields().get(Constants.X_ECOMP_REQUEST_ID_HEADER);
+ // check that header is returned (generated by BE)
+ assertTrue(list != null && !list.isEmpty());
+ String receivedUuid = list.get(0);
+ // Check that same uuid returned
+ assertEquals(uuidStr, receivedUuid);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
new file mode 100644
index 0000000000..7aae0e9a4e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/CsarUtilsTest.java
@@ -0,0 +1,430 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.common.util.YamlToObjectConverter;
+import org.testng.annotations.Test;
+import org.yaml.snakeyaml.Yaml;
+
+public class CsarUtilsTest extends ComponentBaseTest {
+
+ public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CsarUtilsTest() {
+ super(name, CsarUtilsTest.class.getName());
+ }
+
+ @Test(enabled = true)
+ public void createServiceCsarBasicTest() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER, true, true);
+ resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
+
+ csarBasicValidation(service, downloadCSAR);
+ }
+
+ @Test(enabled = true)
+ public void createResourceCsarBasicTest() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ resourceVF = (Resource) AtomicOperationUtils.changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF);
+
+ csarBasicValidation(resourceVF, downloadCSAR);
+ }
+
+ @Test(enabled = true)
+ public void createServiceCsarInclDeploymentArtTest() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resourceVF2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
+ resourceVF1 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceVF2 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF1, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER, true);
+
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, service, UserRoleEnum.DESIGNER, true, true);
+
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, service);
+
+ csarBasicValidation(service, downloadCSAR);
+
+ validateServiceCsar(resourceVF1, resourceVF2, service, downloadCSAR, 3, 5, 1);
+ }
+
+ @Test(enabled = true)
+ public void createResourceCsarInclDeploymentArtTest() throws Exception {
+
+ Resource resourceVF1 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceVF1, UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_ARTIFACT, resourceVF1, UserRoleEnum.DESIGNER, true, true);
+ resourceVF1 = (Resource) AtomicOperationUtils.changeComponentState(resourceVF1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ byte[] downloadCSAR = downloadCSAR(sdncModifierDetails, resourceVF1);
+
+ csarBasicValidation(resourceVF1, downloadCSAR);
+ //TODO when feature is integrated to OS should modify expected deployment artifacts in csar Artifacts folder to (0,1,1)
+ validateVFCsar(resourceVF1, downloadCSAR, 1, 0, 0, 0);
+ }
+
+ private void csarBasicValidation(Component mainComponent, byte[] downloadCSAR) {
+ try (ByteArrayInputStream ins = new ByteArrayInputStream(downloadCSAR); ZipInputStream zip = new ZipInputStream(ins);) {
+
+ String resourceYaml = null;
+ byte[] buffer = new byte[1024];
+ ZipEntry nextEntry = zip.getNextEntry();
+ StringBuffer sb = new StringBuffer();
+ int len;
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+
+ sb.setLength(0);
+ nextEntry = zip.getNextEntry();
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ resourceYaml = sb.toString();
+
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+ ArtifactDefinition artifactDefinition = mainComponent.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
+ String fileName = artifactDefinition.getArtifactName();
+ assertEquals("Tosca-Template file name: ", "Definitions/" + fileName, nextEntry.getName());
+ assertTrue("Tosca template Yaml validation: ", yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
+
+ ins.close();
+ zip.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void validateServiceCsar(Component certifiedVFC1, Component certifiedVFC2, Service fetchedService, byte[] resultByte, int toscaEntryIndexToPass, int generatorEntryIndexToPass, int deploymentArtifactIndexToPass) {
+
+ // TODO Test to validate everything is right (comment out after testing)
+ /*
+ * try { FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); }
+ */
+
+ try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte); ZipInputStream zip = new ZipInputStream(ins);) {
+
+ String resourceYaml = null;
+ byte[] buffer = new byte[1024];
+ ZipEntry nextEntry = zip.getNextEntry();
+ StringBuffer sb = new StringBuffer();
+ int len;
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+
+ int toscaEntryIndex = 0;
+ int generatorEntryIndex = 0;
+ int deploymentArtifactIndex = 0;
+ String fileName = null;
+ ArtifactDefinition artifactDefinition;
+ Component componentToValidate = null;
+
+ artifactDefinition = fetchedService.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
+ String serviceFileName = artifactDefinition.getArtifactName();
+ artifactDefinition = certifiedVFC1.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
+ String vfc1FileName = artifactDefinition.getArtifactName();
+ artifactDefinition = certifiedVFC2.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
+ String vfc2FileName = artifactDefinition.getArtifactName();
+
+ while ((nextEntry = zip.getNextEntry()) != null) {
+ sb.setLength(0);
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ String entryName = nextEntry.getName();
+
+ resourceYaml = sb.toString();
+ if (entryName.contains(serviceFileName)) {
+ componentToValidate = fetchedService;
+ fileName = "Definitions/" + serviceFileName;
+
+ assertEquals("Validate entry Name", (fileName), nextEntry.getName());
+ assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
+ validateContent(resourceYaml, componentToValidate);
+ ++toscaEntryIndex;
+ continue;
+ }
+
+ if (entryName.contains(vfc1FileName)) {
+ componentToValidate = certifiedVFC1;
+ fileName = "Definitions/" + vfc1FileName;
+
+ assertEquals("Validate entry Name", (fileName), nextEntry.getName());
+ assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
+ validateContent(resourceYaml, componentToValidate);
+ ++toscaEntryIndex;
+ continue;
+ }
+ if (entryName.contains(vfc2FileName)) {
+ componentToValidate = certifiedVFC2;
+ fileName = "Definitions/" + vfc2FileName;
+
+ assertEquals("Validate entry Name", (fileName), nextEntry.getName());
+ assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
+ validateContent(resourceYaml, componentToValidate);
+ ++toscaEntryIndex;
+ continue;
+ }
+
+ if (entryName.contains(".xml") && !entryName.startsWith("Artifacts/AAI")) {
+ ++deploymentArtifactIndex;
+ continue;
+ }
+
+ if (entryName.startsWith("Artifacts/AAI")) {
+ ++generatorEntryIndex;
+ continue;
+ }
+
+ assertTrue("Unexpected entry: " + entryName, true);
+ }
+ assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex);
+ assertEquals("Validate amount of generated AAI artifacts", generatorEntryIndexToPass, generatorEntryIndex);
+ assertEquals("Validate amount of generated Deployment artifacts", deploymentArtifactIndexToPass, deploymentArtifactIndex);
+
+ ins.close();
+ zip.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void validateVFCsar(Component certifiedVF, byte[] resultByte, int toscaEntryIndexToPass, int ymlDeploymentArtifactIndexToPass, int xmlDeploymentArtifactIndexToPass, int heatEnvDeploymentArtifactIndexToPass) {
+
+ // TODO Test to validate everything is right (comment out after testing)
+ /*
+ * try { FileUtils.writeByteArrayToFile(new File("c:/TestCSAR/" + fetchedService.getName() + ".zip"), resultByte); } catch (IOException e) { // Auto-generated catch block e.printStackTrace(); }
+ */
+
+ try (ByteArrayInputStream ins = new ByteArrayInputStream(resultByte); ZipInputStream zip = new ZipInputStream(ins);) {
+
+ String resourceYaml = null;
+ byte[] buffer = new byte[1024];
+ ZipEntry nextEntry = zip.getNextEntry();
+ StringBuffer sb = new StringBuffer();
+ int len;
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ assertTrue(nextEntry.getName().equals("TOSCA-Metadata/TOSCA.meta"));
+
+ YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
+
+ int toscaEntryIndex = 0;
+ int ymlEntryIndex = 0;
+ int xmlArtifactsIndex = 0;
+ int heatEnvDeploymentArtifactIndex = 0;
+ String fileName = null;
+ ArtifactDefinition artifactDefinition;
+ Component componentToValidate = null;
+
+ artifactDefinition = certifiedVF.getToscaArtifacts().get(ASSET_TOSCA_TEMPLATE);
+ String vfFileName = artifactDefinition.getArtifactName();
+
+ while ((nextEntry = zip.getNextEntry()) != null) {
+ sb.setLength(0);
+
+ while ((len = zip.read(buffer)) > 0) {
+ sb.append(new String(buffer, 0, len));
+ }
+
+ String entryName = nextEntry.getName();
+
+ resourceYaml = sb.toString();
+ if (entryName.contains(vfFileName)) {
+ componentToValidate = certifiedVF;
+ fileName = "Definitions/" + vfFileName;
+
+ assertEquals("Validate entry Name", (fileName), nextEntry.getName());
+ assertTrue(yamlToObjectConverter.isValidYaml(resourceYaml.getBytes()));
+ validateContent(resourceYaml, componentToValidate);
+ ++toscaEntryIndex;
+ continue;
+ }
+
+ if (entryName.contains(".xml") && entryName.startsWith("Artifacts/")) {
+ ++xmlArtifactsIndex;
+ continue;
+ }
+
+ if (entryName.contains(".sh") && entryName.startsWith("Artifacts/")) {
+ ++heatEnvDeploymentArtifactIndex;
+ continue;
+ }
+
+ if (entryName.contains(".yml") && entryName.startsWith("Artifacts/")) {
+ ++ymlEntryIndex;
+ continue;
+ }
+
+ assertTrue("Unexpected entry: " + entryName, false);
+ }
+ assertEquals("Validate amount of entries", toscaEntryIndexToPass, toscaEntryIndex);
+ assertEquals("Validate amount of YAML artifacts", ymlDeploymentArtifactIndexToPass, ymlEntryIndex);
+ assertEquals("Validate amount of generated XML artifacts", xmlDeploymentArtifactIndexToPass, xmlArtifactsIndex);
+ assertEquals("Validate amount of generated HEAT ENV artifacts", heatEnvDeploymentArtifactIndexToPass, heatEnvDeploymentArtifactIndex);
+
+ ins.close();
+ zip.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void validateContent(String content, Component component) {
+ Yaml yaml = new Yaml();
+
+ InputStream inputStream = new ByteArrayInputStream(content.getBytes());
+ @SuppressWarnings("unchecked")
+ Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
+ @SuppressWarnings("unchecked")
+ Map<String, Object> metadata = (Map<String, Object>) load.get("metadata");
+ assertNotNull(metadata);
+
+ String name = (String) metadata.get("name");
+ assertNotNull(name);
+ assertEquals("Validate component name", component.getName(), name);
+
+ String invariantUUID = (String) metadata.get("invariantUUID");
+ assertNotNull(invariantUUID);
+ assertEquals("Validate component invariantUUID", component.getInvariantUUID(), invariantUUID);
+
+ String UUID = (String) metadata.get("UUID");
+ assertNotNull(UUID);
+ assertEquals("Validate component invariantUUID", component.getUUID(), UUID);
+
+ String type = (String) metadata.get("type");
+ assertNotNull(type);
+ if (component.getComponentType().equals(ComponentTypeEnum.SERVICE)) {
+ assertEquals("Validate component type", component.getComponentType().getValue(), type);
+ } else {
+ assertEquals("Validate component type", ((Resource) component).getResourceType(), ResourceTypeEnum.valueOf(type));
+ }
+ }
+
+ private byte[] downloadCSAR(User sdncModifierDetails, Component createdComponent) throws Exception {
+
+ String artifactUniqeId = createdComponent.getToscaArtifacts().get("assettoscacsar").getUniqueId();
+ RestResponse getCsarResponse = null;
+
+ switch (createdComponent.getComponentType()) {
+ case RESOURCE:
+ getCsarResponse = ArtifactRestUtils.downloadResourceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
+ break;
+ case SERVICE:
+ getCsarResponse = ArtifactRestUtils.downloadServiceArtifactInternalApi(createdComponent.getUniqueId(), sdncModifierDetails, artifactUniqeId);
+ break;
+ default:
+ break;
+ }
+
+ assertNotNull(getCsarResponse);
+ BaseRestUtils.checkSuccess(getCsarResponse);
+
+ ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(getCsarResponse.getResponse(), ArtifactUiDownloadData.class);
+
+ assertNotNull(artifactUiDownloadData);
+
+ byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
+ byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload);
+
+ return decodeBase64;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
new file mode 100644
index 0000000000..e4360329ad
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ExportToscaTest.java
@@ -0,0 +1,333 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.Test;
+import org.yaml.snakeyaml.Yaml;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonParser;
+
+public class ExportToscaTest extends ComponentBaseTest {
+ @Rule
+ public static TestName name = new TestName();
+
+ public ExportToscaTest() {
+ super(name, ExportToscaTest.class.getName());
+ }
+
+ @Test(enabled = true)
+ public void exportVfModuleTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ Resource createdResource = createVfFromCSAR(sdncModifierDetails, "VSPPackage");
+
+ Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
+ assertNotNull(load);
+ Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
+ assertNotNull(topology_template);
+ Map<String, Object> groups = (Map<String, Object>) topology_template.get("groups");
+ assertNotNull(groups);
+ List<GroupDefinition> groupsOrigin = createdResource.getGroups();
+
+ assertEquals("Validate groups size", groupsOrigin.size(), groups.size());
+ for (GroupDefinition group : groupsOrigin) {
+ Map<String, Object> groupTosca = (Map<String, Object>) groups.get(group.getName());
+ assertNotNull(groupTosca);
+
+ Map<String, Object> metadata = (Map<String, Object>) groupTosca.get("metadata");
+ assertNotNull(metadata);
+
+ String invariantUUID;
+ String name;
+ String UUID;
+ String version;
+ Map<String, Object> properties = (Map<String, Object>) groupTosca.get("properties");
+
+ if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) {
+ invariantUUID = (String) metadata.get("vfModuleModelInvariantUUID");
+ name = (String) metadata.get("vfModuleModelName");
+ UUID = (String) metadata.get("vfModuleModelUUID");
+ version = (String) metadata.get("vfModuleModelVersion");
+ assertNotNull(properties);
+
+ String vf_module_type = (String) properties.get("vf_module_type");
+ List<GroupProperty> props = group.getProperties();
+ for (GroupProperty prop : props) {
+ if (prop.getName().equals(Constants.IS_BASE)) {
+ String value = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue();
+ boolean bvalue = Boolean.parseBoolean(value);
+ if (bvalue) {
+ assertEquals("Validate vf_module_type", "Base", vf_module_type);
+ } else {
+ assertEquals("Validate vf_module_type", "Expansion", vf_module_type);
+ }
+ break;
+ }
+ }
+ String vf_module_description = (String) properties.get("vf_module_description");
+ assertEquals("Validate vf_module_description", group.getDescription(), vf_module_description);
+
+ Boolean volume_group = (Boolean) properties.get("volume_group");
+ boolean isVolume = false;
+ List<String> artifactsList = group.getArtifacts();
+ List<ArtifactDefinition> artifacts = new ArrayList<>();
+ if (artifactsList != null && !artifactsList.isEmpty()) {
+ ArtifactDefinition masterArtifact = findMasterArtifact(createdResource.getDeploymentArtifacts(),
+ artifacts, artifactsList);
+ if (masterArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())) {
+ isVolume = true;
+ }
+ }
+ assertEquals("Validate volume_group", isVolume, volume_group);
+
+ } else {
+ invariantUUID = (String) metadata.get("invariantUUID");
+ name = (String) metadata.get("name");
+ UUID = (String) metadata.get("UUID");
+ version = (String) metadata.get("version");
+ assertNull(properties);
+
+ }
+ assertEquals("Validate InvariantUUID", group.getInvariantUUID(), invariantUUID);
+ assertEquals("Validate name", group.getName(), name);
+ assertEquals("Validate UUID", group.getGroupUUID(), UUID);
+ assertEquals("Validate version", group.getVersion(), version);
+
+ }
+ }
+
+ @Test(enabled = true)
+ public void exportCsarInputsTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ Resource createdResource = createVfFromCSAR(sdncModifierDetails, "csar_1");
+ Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, createdResource);
+ assertNotNull(load);
+
+ Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
+ assertNotNull(topology_template);
+
+ Map<String, Object> inputs = (Map<String, Object>) topology_template.get("inputs");
+ assertNotNull(inputs);
+
+ List<InputDefinition> inputsFromResource = createdResource.getInputs();
+ assertEquals("validate inputs size", inputsFromResource.size(), inputs.size());
+ for (InputDefinition inputDef : inputsFromResource) {
+ Map<String, Object> inputInFile = (Map<String, Object>) inputs.get(inputDef.getName());
+ assertNotNull(inputInFile);
+ validateInput(inputDef, inputInFile);
+ }
+ List<ComponentInstance> componentInstances = createdResource.getComponentInstances();
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = createdResource
+ .getComponentInstancesProperties();
+ Map<String, Object> node_templates = (Map<String, Object>) topology_template.get("node_templates");
+ assertNotNull(node_templates);
+
+ JsonParser jsonParser = new JsonParser();
+
+ for (Map.Entry<String, List<ComponentInstanceProperty>> entry : componentInstancesProperties.entrySet()) {
+
+ Optional<ComponentInstance> findFirst = componentInstances.stream()
+ .filter(ci -> ci.getUniqueId().equals(entry.getKey())).findFirst();
+ assertTrue(findFirst.isPresent());
+ String resourceName = findFirst.get().getName();
+ Map<String, Object> instance = (Map<String, Object>) node_templates.get(resourceName);
+ assertNotNull(instance);
+ Map<String, Object> properties = (Map<String, Object>) instance.get("properties");
+
+ for (ComponentInstanceProperty cip : entry.getValue()) {
+ if (cip.getValueUniqueUid() != null && !cip.getValueUniqueUid().isEmpty()) {
+ assertNotNull(properties);
+ if (cip.getValue().contains("get_input")) {
+ Object prop = properties.get(cip.getName());
+ assertNotNull(prop);
+
+ Gson gson = new Gson();
+ String json = gson.toJson(prop);
+ assertEquals("validate json property", cip.getValue(), json);
+ }
+
+ }
+ }
+
+ }
+
+ }
+
+ @Test
+ public void importExportCsarWithJsonPropertyType() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "jsonPropertyTypeTest.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/jsonPropertyTypeTest.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ ComponentInstance pmaaServer = resource.getComponentInstances().stream()
+ .filter(p -> p.getName().equals("pmaa_server_0")).findAny().get();
+ ComponentInstanceProperty jsonProp = resource.getComponentInstancesProperties().get(pmaaServer.getUniqueId())
+ .stream().filter(p -> p.getType().equals(ToscaPropertyType.JSON.getType())).findAny().get();
+ String jsonValue = "{\"pmaa.sb_nic\":{\"address\":{\"get_input\":\"pmaa_dpu_fixed_ip\"},\"cidr\":{\"get_input\":\"pmaa_dpu_cidr\"},\"gateway\":{\"get_input\":\"pmaa_dpu_gateway\"}}}";
+ assertEquals(jsonProp.getValue(), jsonValue);
+ // download and compare
+ Map<String, Object> load = downloadAndParseToscaTemplate(sdncModifierDetails, resource);
+ assertNotNull(load);
+ Map<String, Object> topology_template = (Map<String, Object>) load.get("topology_template");
+ assertNotNull(topology_template);
+ Map<String, Object> nodes = (Map<String, Object>) topology_template.get("node_templates");
+ assertNotNull(nodes);
+ Map<String, Object> pmaaServerObj = (Map<String, Object>) nodes.get("pmaa_server_0");
+ assertNotNull(pmaaServerObj);
+ Map<String, Object> props = (Map<String, Object>) pmaaServerObj.get("properties");
+ assertNotNull(props);
+ Map<String, Object> jsonPropObj = (Map<String, Object>) props.get("metadata");
+ assertNotNull(jsonPropObj);
+ Gson gson = new Gson();
+ String json = gson.toJson(jsonPropObj);
+ assertEquals(json, jsonValue);
+ }
+
+ private void validateInput(InputDefinition inputDef, Map<String, Object> inputInFile) {
+ assertEquals("validate input type", inputDef.getType(), (String) inputInFile.get("type"));
+
+ if (inputDef.getDefaultValue() == null) {
+ assertNull(inputInFile.get("default"));
+ } else {
+ assertNotNull(inputInFile.get("default"));
+ String value = inputDef.getDefaultValue().replace("\"", "");
+ value = value.replace(" ", "");
+ String expValue = inputInFile.get("default").toString().replace(" ", "");
+ assertEquals("validate input default", value, expValue);
+ }
+ assertEquals("validate input description", inputDef.getDescription(), (String) inputInFile.get("description"));
+ }
+
+ // ----------------------------------------
+ private Map<String, Object> downloadAndParseToscaTemplate(User sdncModifierDetails, Resource createdResource)
+ throws Exception {
+ String artifactUniqeId = createdResource.getToscaArtifacts().get("assettoscatemplate").getUniqueId();
+
+ RestResponse toscaTemplate = ArtifactRestUtils.downloadResourceArtifactInternalApi(
+ createdResource.getUniqueId(), sdncModifierDetails, artifactUniqeId);
+ ArtifactUiDownloadData artifactUiDownloadData = ResponseParser.parseToObject(toscaTemplate.getResponse(),
+ ArtifactUiDownloadData.class);
+ byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
+ byte[] decodeBase64 = Base64.decodeBase64(fromUiDownload);
+ Yaml yaml = new Yaml();
+
+ InputStream inputStream = new ByteArrayInputStream(decodeBase64);
+
+ Map<String, Object> load = (Map<String, Object>) yaml.load(inputStream);
+ return load;
+ }
+
+ private Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
+ // create new resource from Csar
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+
+ resourceDetails.setCsarUUID(csarId);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
+ return createdResource;
+ }
+
+ public ArtifactDefinition findMasterArtifact(Map<String, ArtifactDefinition> deplymentArtifact,
+ List<ArtifactDefinition> artifacts, List<String> artifactsList) {
+ for (String artifactUid : artifactsList) {
+ for (Entry<String, ArtifactDefinition> entry : deplymentArtifact.entrySet()) {
+ ArtifactDefinition artifact = entry.getValue();
+ if (artifactUid.equalsIgnoreCase(artifact.getUniqueId())) {
+ artifacts.add(artifact);
+ }
+
+ }
+ }
+ ArtifactDefinition masterArtifact = null;
+ for (ArtifactDefinition artifactInfo : artifacts) {
+ String atrifactType = artifactInfo.getArtifactType();
+ if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType())
+ || atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType())) {
+ masterArtifact = artifactInfo;
+ continue;
+ }
+ if (atrifactType.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) {
+ masterArtifact = artifactInfo;
+ break;
+ }
+ }
+ return masterArtifact;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
new file mode 100644
index 0000000000..eab4e5bed2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportCsarResourceTest.java
@@ -0,0 +1,1538 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang.WordUtils;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.GroupProperty;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.GroupRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ImportCsarResourceTest extends ComponentBaseTest {
+ private static Logger log = LoggerFactory.getLogger(ImportCsarResourceTest.class.getName());
+ @Rule
+ public static TestName name = new TestName();
+
+ Gson gson = new Gson();
+
+ public ImportCsarResourceTest() {
+ super(name, ImportCsarResourceTest.class.getName());
+ }
+
+ private String buildAssertMessage(String expectedString, String actualString) {
+ return String.format("expected is : %s , actual is: %s", expectedString, actualString);
+ }
+
+ /**
+ *
+ * User Story : US640615 [BE] - Extend create VF API with Import TOSCA CSAR
+ */
+
+ @Test(enabled = true)
+ public void createResourceFromCsarHappy() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("AF7F231969C5463F9C968570070E8877");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void emptyStringInCsarUUIDFieldTest() throws Exception {
+ String emptyString = "";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(emptyString);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(null, resource.getComponentInstances());
+
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(emptyString, resource.getCsarUUID()), resource.getCsarUUID() == emptyString);
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(emptyString, getResource.getCsarUUID()), getResource.getCsarUUID() == emptyString);
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromScratchTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(null, resource.getComponentInstances());
+
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(null, resource.getCsarUUID()), resource.getCsarUUID() == null);
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(null, getResource.getCsarUUID()), getResource.getCsarUUID() == null);
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void fileNotCsarTypeTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("valid_vf_zip");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_NOT_FOUND.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void missingToscaMetadataFolderTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("toscaFolderNotExists");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void missingToscaMetaFileTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("toscaMetaFileNotExists");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void toscaMetaFileOutsideTheFolderTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("toscaMetaOutsideTheFolder");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void caseSensitiveTest_1() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("caseSensitiveTest_1");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void caseSensitiveTest_2() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("caseSensitiveTest_2");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void missingOneLineInToscaMetaFileTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("missingOneLineInToscaMeta");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void noCSARVersionTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("noCSARVersion");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void noCreatedByValueTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("noCreatedByValue");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void noEntryDefinitionsValueTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("noEntryDefinitionsValue");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void noTOSCAMetaFileVersionValueTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("noTOSCAMetaFileVersionValue");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void invalidCsarVersionInMetaFileTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("invalidCsarVersion");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+
+ resourceDetails.setCsarUUID("invalidCsarVersion2");
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+
+ resourceDetails.setCsarUUID("invalidCsarVersion3");
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+
+ resourceDetails.setCsarUUID("invalidCsarVersion4");
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+
+ resourceDetails.setCsarUUID("invalidCsarVersion5");
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+
+ }
+
+ @Test(enabled = true)
+ public void validCsarVersionInMetaFileTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("validCsarVersion");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void underscoreInToscaMetaFileVersionNameTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("underscoreInsteadOfDash");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void missingEntryDefintionInMetaFileTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("missingEntryDefintionPair");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = false)
+ public void noNewLineAfterBLock0Test() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("noNewLineAfterBLock0");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void moreThanOneYamlFileTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("moreThenOneYamlFile");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void moreThanOneMetaFileTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("moreThanOneMetaFile");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void csarNotContainsYamlAndMetaFilesTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("notContainYamlAndMetaFiles");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void csarNotContainsYamlFileTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("notContainYamlFile");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ variables.add("Definitions/tosca_mock_vf.yaml");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.YAML_NOT_FOUND_IN_CSAR.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void missingCsarFileTest() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("abc");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_NOT_FOUND.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void longNamesInToscaMetaFileTest_1() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("longNamesInToscaMetaFile1");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void longNamesInToscaMetaFileTest_2() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("longNamesInToscaMetaFile2");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void longNamesInToscaMetaFileTest_3() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("longNamesInToscaMetaFile3");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void longNamesInToscaMetaFileTest_4() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("longNamesInToscaMetaFile4");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void longNamesInToscaMetaFileTest_5() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("longNamesInToscaMetaFile5");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ // possible to have more than four lines in block 0
+ // @Test (enabled = true)
+ public void fiveLinesAsBlock0Test() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ resourceDetails.setCsarUUID("fiveLinesAsBlock0");
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ List<String> variables = new ArrayList<String>();
+ variables.add(resourceDetails.getCsarUUID());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.CSAR_INVALID_FORMAT.name(), variables, createResource.getResponse());
+ }
+
+ @Test(enabled = true)
+ public void lifecycleChangingToResourceFromCsarTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("valid_vf");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertTrue("0.1".equals(resource.getVersion()));
+ assertTrue(LifeCycleStatesEnum.CHECKOUT.getComponentState().equals(resource.getLifecycleState().toString()));
+
+ String designerUserId = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId();
+ String testerUserId = ElementFactory.getDefaultUser(UserRoleEnum.TESTER).getUserId();
+ String csarUniqueId = resourceDetails.getUniqueId();
+ assertNotNull(csarUniqueId);
+
+ RestResponse lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.STARTCERTIFICATION);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUserId, LifeCycleStatesEnum.CERTIFY);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUserId, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+
+ resource = ResponseParser.parseToObjectUsingMapper(lifecycleChangeResponse.getResponse(), Resource.class);
+ Map<String, String> allVersions = resource.getAllVersions();
+ assertEquals(2, allVersions.keySet().size());
+ assertEquals(2, allVersions.values().size());
+ Set<String> keySet = allVersions.keySet();
+ assertTrue(keySet.contains("1.0"));
+ assertTrue(keySet.contains("1.1"));
+ }
+
+ @Test(enabled = true)
+ public void csarWithJsonPromEnvTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VSPPackageJsonProp.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ }
+
+ @Test(enabled = true)
+ public void uploadArtifactToResourceFromCsarTest() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("valid_vf");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact("firstArtifact");
+ String firstArtifactLabel = artifactDetails.getArtifactLabel();
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, designer, resourceDetails.getUniqueId());
+ ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource);
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resourceDetails.getUniqueId());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ Map<String, ArtifactDefinition> informationalArtifacts = resource.getArtifacts();
+ assertEquals(1, informationalArtifacts.keySet().size());
+ Set<String> keySet = informationalArtifacts.keySet();
+ assertTrue(keySet.contains(firstArtifactLabel.toLowerCase()));
+ Collection<ArtifactDefinition> values = informationalArtifacts.values();
+ assertEquals(1, values.size());
+ Iterator<ArtifactDefinition> iterator = values.iterator();
+ while (iterator.hasNext()) {
+ ArtifactDefinition actualArtifact = iterator.next();
+ assertTrue(firstArtifactLabel.equals(actualArtifact.getArtifactDisplayName()));
+ }
+
+ RestResponse lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designer.getUserId(), LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+ lifecycleChangeResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designer.getUserId(), LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(lifecycleChangeResponse);
+
+ ArtifactReqDetails artifactDetails2 = ElementFactory.getDefaultArtifact("secondArtifact");
+ artifactDetails2.setArtifactName("secondArtifact");
+ addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails2, designer, resourceDetails.getUniqueId());
+ ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource);
+
+ getResourceResponse = ResourceRestUtils.getResource(resourceDetails.getUniqueId());
+ resource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ informationalArtifacts = resource.getArtifacts();
+ assertEquals(2, informationalArtifacts.keySet().size());
+ keySet = informationalArtifacts.keySet();
+ assertTrue(keySet.contains(firstArtifactLabel.toLowerCase()));
+ assertTrue(keySet.contains(artifactDetails2.getArtifactLabel().toLowerCase()));
+ values = informationalArtifacts.values();
+ assertEquals(2, values.size());
+ ArtifactDefinition[] actualArtifacts = values.toArray(new ArtifactDefinition[2]);
+ assertTrue(firstArtifactLabel.equals(actualArtifacts[0].getArtifactDisplayName()));
+ assertTrue(artifactDetails2.getArtifactLabel().equals(actualArtifacts[1].getArtifactDisplayName()));
+ }
+
+ /*
+ * // @Test (enabled = true) public void createUpdateImportResourceFromCsarArtifactsWereNotChangedTest() throws Exception { // User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); // //back original scar RestResponse
+ * copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar"); BaseRestUtils.checkSuccess(copyRes);
+ *
+ * // resourceDetails.setResourceType(ResourceTypeEnum.VF.name()); // RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails); resourceDetails.setName("test5");
+ * resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); resourceDetails.setCsarVersion("1"); // String invariantUUID = resource.getInvariantUUID(); // // RestResponse changeResourceState =
+ * LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN); // assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ *
+ * // BaseRestUtils.checkSuccess(copyRes); // //change name (temporary) resourceDetails.setCsarVersion("2"); resourceDetails.setName("test6"); createResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ * resourceDetails.getUniqueId()); Resource updatedResource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class); Map<String, ArtifactDefinition> updatedArtifacts = updatedResource.getDeploymentArtifacts(); for
+ * (Entry<String, ArtifactDefinition> artifactEntry : resource.getDeploymentArtifacts().entrySet()) { if (updatedArtifacts.containsKey(artifactEntry.getKey())) { ArtifactDefinition currArt = updatedArtifacts.get(artifactEntry.getKey());
+ * assertEquals(currArt.getArtifactVersion(), artifactEntry.getValue().getArtifactVersion()); assertEquals(currArt.getArtifactUUID(), artifactEntry.getValue().getArtifactUUID()); assertEquals(currArt.getArtifactChecksum(),
+ * artifactEntry.getValue().getArtifactChecksum()); } } // resourceDetails = ElementFactory.getDefaultResource(); // resourceDetails.setName("test5"); // resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar"); }
+ */
+
+ @Test(enabled = true)
+ public void createImportResourceFromCsarDissotiateArtifactFromGroupTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+
+ // create new resource from Csar
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ String invariantUUID = resource.getInvariantUUID();
+
+ // add artifact from metadata (resource metadata should be updated)
+ // RestResponse addInformationalArtifactToResource =
+ // ArtifactRestUtils.addInformationalArtifactToResource(ElementFactory.getDefaultArtifact(),
+ // sdncModifierDetails, resourceDetails.getUniqueId());
+ // ArtifactRestUtils.checkSuccess(addInformationalArtifactToResource);
+ resourceDetails.setName("test4");
+ RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+
+ // wrong RI (without node types, resource shouldn't be updated)
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_dissociate.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ // change name (temporary)
+ resourceDetails.setName("test4");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ @Test(enabled = true)
+ public void createImportResourceFromCsarNewgroupTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+
+ // create new resource from Csar
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ String invariantUUID = resource.getInvariantUUID();
+
+ // update scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_UpdateToscaAndArtifacts.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails.setName("test2");
+ // change resource metaData (resource should be updated)
+ resourceDetails.setDescription("It is new description bla bla bla");
+ RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ @Test(enabled = true)
+ public void createImportResourceFromCsarGetGroupTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // RestResponse copyRes =
+ // copyCsarRest(sdncModifierDetails,"VF_RI2_G4_withArtifacts_a.csar","VF_RI2_G4_withArtifacts.csar");
+
+ // create new resource from Csar
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("VSPPackage");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ String invariantUUID = resource.getInvariantUUID();
+ List<GroupDefinition> groups = resource.getGroups();
+
+ GroupDefinition groupWithArtifact = groups.stream().filter(p -> p.getArtifacts() != null && !p.getArtifacts().isEmpty()).findFirst().get();
+
+ RestResponse groupRest = GroupRestUtils.getGroupById(resource, groupWithArtifact.getUniqueId(), sdncModifierDetails);
+ BaseRestUtils.checkSuccess(groupRest);
+
+ GroupDefinition groupWithoutArtifact = groups.stream().filter(p -> p.getArtifacts() == null || p.getArtifacts().isEmpty()).findFirst().get();
+
+ groupRest = GroupRestUtils.getGroupById(resource, groupWithoutArtifact.getUniqueId(), sdncModifierDetails);
+ BaseRestUtils.checkSuccess(groupRest);
+ }
+
+ @Test(enabled = true)
+ public void createImportResourceFromCsarUITest() throws Exception {
+ RestResponse getResource = null;
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "valid_vf.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ // create new resource from Csar
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change composition (resource should be updated)
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_b.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ // change name
+ resourceDetails.setName("test1");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(2, resource.getComponentInstances().size());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change name
+ resourceDetails.setName("test2");
+ // change resource metaData (resource should be updated)
+ resourceDetails.setDescription("It is new description bla bla bla");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(2, resource.getComponentInstances().size());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // wrong RI (without node types, resource shouldn't be updated)
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_c.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ // change name
+ resourceDetails.setName("test3");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber");
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(null, resource);
+ getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion());
+ BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3");
+
+ // create new resource from other Csar
+ resourceDetails = ElementFactory.getDefaultImportResource();
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setPayloadName("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setName("test4");
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // wrong RI (with node types) resource shouldn't be created
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts_b.csar");
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/VF_RI2_G4_withArtifacts_b.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setPayloadName("VF_RI2_G4_withArtifacts_b.csar");
+ resourceDetails.setName("test5");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/VF_RI2_G1.yaml", "ps04_port_0", "org.openecomp.resource.cp.nodes.heat.network.neutron.Portur");
+ }
+
+ @Test(enabled = true)
+ public void createUpdateImportResourceFromCsarUITest() throws Exception {
+ RestResponse getResource = null;
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "valid_vf.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ // create new resource from Csar
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change composition and update resource
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_b.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setUniqueId(resource.getUniqueId());
+ // change name
+ RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(2, resource.getComponentInstances().size());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change name
+ resourceDetails.setName("test2");
+ // change resource metaData (resource should be updated)
+ resourceDetails.setDescription("It is new description bla bla bla");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(2, resource.getComponentInstances().size());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // try to update resource with wrong RI (without node types, resource
+ // shouldn't be updated)
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_c.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ // change name
+ resourceDetails.setName("test3");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber");
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(null, resource);
+ getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion());
+ BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3");
+ }
+
+ @Test(enabled = true)
+ public void createUpdateImportResourceFromCsarTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = null;
+ RestResponse getResource = null;
+ ResourceReqDetails resourceDetails = null;
+ RestResponse updateResource = null;
+ RestResponse createResource = null;
+ Resource resource = null;
+ RestResponse changeResourceState = null;
+
+ // create new resource from Csar
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar");
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("valid_vf.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+ String invariantUUID = resource.getInvariantUUID();
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change composition and update resource
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_b.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ // change name
+ resourceDetails.setName("test1");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(2, resource.getComponentInstances().size());
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ // change name
+ resourceDetails.setName("test2");
+ // change resource metaData and update resource
+ resourceDetails.setDescription("It is new description bla bla bla");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ // try to update resource with wrong RI (without node types, resource
+ // shouldn't be updated)
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_c.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ // change name (temporary)
+ resourceDetails.setName("test3");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resource.getUniqueId());
+ BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/tosca_mock_vf.yaml", "nodejs", "tosca.nodes.Weber");
+
+ getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test3", resourceDetails.getVersion());
+ BaseRestUtils.checkErrorResponse(getResource, ActionStatus.RESOURCE_NOT_FOUND, "test3");
+ getResource = ResourceRestUtils.getResourceByNameAndVersion(sdncModifierDetails.getUserId(), "test2", resourceDetails.getVersion());
+ BaseRestUtils.checkSuccess(getResource);
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ // create new resource from Csar
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // scar with wrong RI
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_b.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ // wrong RI (with node types) resource shouldn't be created
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkErrorResponse(updateResource, ActionStatus.INVALID_NODE_TEMPLATE, "Definitions/VF_RI2_G1.yaml", "ps04_port_0", "org.openecomp.resource.cp.nodes.heat.network.neutron.Portur");
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ @Test(enabled = true)
+ public void createUpdateImportResourceFromCsarWithArtifactsTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = null;
+ ResourceReqDetails resourceDetails = null;
+ RestResponse updateResource = null;
+ RestResponse createResource = null;
+ Resource resource = null;
+ RestResponse changeResourceState = null;
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts.csar");
+ resourceDetails.setCsarVersion("1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ // create new resource from Csar
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ List<String> requiredArtifactsOld = resource.getDeploymentArtifacts().get("heat5").getRequiredArtifacts();
+ assertTrue(requiredArtifactsOld != null && !requiredArtifactsOld.isEmpty() && requiredArtifactsOld.size() == 3);
+ assertTrue(requiredArtifactsOld.contains("hot-nimbus-pcm-volumes_v1.0.yaml"));
+ assertTrue(requiredArtifactsOld.contains("nested-pcm_v1.0.yaml"));
+ assertTrue(requiredArtifactsOld.contains("hot-nimbus-oam-volumes_v1.0.yaml"));
+
+ // update scar with new artifacts
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_updated.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ resourceDetails.setCsarVersion("2");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+
+ List<String> requiredArtifactsNew = resource.getDeploymentArtifacts().get("heat5").getRequiredArtifacts();
+ assertTrue(requiredArtifactsNew != null && !requiredArtifactsNew.isEmpty() && requiredArtifactsNew.size() == 3);
+ assertTrue(requiredArtifactsNew.contains("hot-nimbus-swift-container_v1.0.yaml"));
+ assertTrue(requiredArtifactsNew.contains("hot-nimbus-oam-volumes_v1.0.yaml"));
+ assertTrue(requiredArtifactsNew.contains("nested-oam_v1.0.yaml"));
+
+ // back original scar
+ copyRes = copyCsarRest(sdncModifierDetails, "VF_RI2_G4_withArtifacts_a.csar", "VF_RI2_G4_withArtifacts.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ @Test(enabled = true)
+ public void createUpdateImportWithPropertiesFromCsarUITest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "valid_vf.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ // create new resource from Csar
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change composition (add new RI with specified property values)
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_d.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ // change name
+ resourceDetails.setName("test1");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(6, resource.getComponentInstances().size());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ // change composition (add new specified property values to existing RI)
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/valid_vf_f.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ // change name
+ resourceDetails.setName("test2");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(6, resource.getComponentInstances().size());
+
+ }
+
+ public static RestResponse copyCsarRest(User sdncModifierDetails, String sourceCsarUuid, String targetCsarUuid) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.COPY_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), sourceCsarUuid, targetCsarUuid);
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+
+ RestResponse copyCsarResponse = http.httpSendPost(url, "dummy", headersMap);
+ if (copyCsarResponse.getErrorCode() != 200) {
+ return null;
+ }
+ return copyCsarResponse;
+
+ }
+
+ public static RestResponse getCsarRest(User sdncModifierDetails, String sourceCsarUuid) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), sourceCsarUuid);
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+
+ RestResponse copyCsarResponse = http.httpSendGet(url, headersMap);
+ if (copyCsarResponse.getErrorCode() != 200) {
+ return null;
+ }
+ return copyCsarResponse;
+
+ }
+
+ @Test(enabled = true)
+ public void updateResourceFromCsarHappy() throws Exception {
+ RestResponse copyRes = copyCsarRest(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), "valid_vf_a.csar", "valid_vf.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ // create
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("valid_vf");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getResource(resource.getUniqueId());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+
+ RestResponse updateResource = ResourceRestUtils.updateResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarWithGroupsHappy() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroups");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ assertEquals("verify there are 2 groups", 2, resource.getGroups().size());
+
+ Map<String, String> compNameToUniqueId = resource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId()));
+
+ // Verify 2 members on group1
+ // members: [ app_server, mongo_server ]
+ String[] membersNameGroup1 = { "app_server", "mongo_server" };
+ verifyMembersInResource(resource, compNameToUniqueId, "group1", membersNameGroup1);
+ // Verify 4 members on group2
+ // members: [ mongo_db, nodejs, app_server, mongo_server ]
+ String[] membersNameGroup2 = { "app_server", "mongo_server", "mongo_db", "nodejs" };
+ verifyMembersInResource(resource, compNameToUniqueId, "group2", membersNameGroup2);
+
+ // Check OUT
+ resourceDetails.setUniqueId(resource.getUniqueId());
+ RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ changeResourceState = LifecycleRestUtils.changeResourceState(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+
+ Resource checkedOutResource = ResponseParser.parseToObjectUsingMapper(changeResourceState.getResponse(), Resource.class);
+ compNameToUniqueId = checkedOutResource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId()));
+
+ // Verify 2 members on group1
+ // members: [ app_server, mongo_server ]
+ verifyMembersInResource(checkedOutResource, compNameToUniqueId, "group1", membersNameGroup1);
+ // Verify 4 members on group2
+ // members: [ mongo_db, nodejs, app_server, mongo_server ]
+ verifyMembersInResource(checkedOutResource, compNameToUniqueId, "group2", membersNameGroup2);
+
+ }
+
+ private void verifyMembersInResource(Resource resource, Map<String, String> compNameToUniqueId, String groupName, String[] membersName) {
+ GroupDefinition groupDefinition = resource.getGroups().stream().filter(p -> p.getName().equals(groupName)).findFirst().get();
+ assertEquals("Verify number of members", membersName.length, groupDefinition.getMembers().size());
+ Map<String, String> createdMembers = groupDefinition.getMembers();
+ Arrays.asList(membersName).forEach(p -> {
+ assertTrue("check member name exist", createdMembers.containsKey(p));
+ });
+
+ verifyMembers(createdMembers, compNameToUniqueId);
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarWithGroupsAndPropertiesHappy() throws Exception {
+
+ RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN);
+ // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsWithProps");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+
+ assertEquals("verify there are 2 groups", 2, resource.getGroups().size());
+
+ Map<String, String> compNameToUniqueId = resource.getComponentInstances().stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getUniqueId()));
+
+ // Verify 2 members on group1
+ // members: [ app_server, mongo_server ]
+ List<GroupDefinition> groupDefinition1 = resource.getGroups().stream().filter(p -> p.getName().equals("group1")).collect(Collectors.toList());
+ assertEquals("Verify number of members", 2, groupDefinition1.get(0).getMembers().size());
+ Map<String, String> createdMembers = groupDefinition1.get(0).getMembers();
+ verifyMembers(createdMembers, compNameToUniqueId);
+
+ List<GroupProperty> properties = groupDefinition1.get(0).getProperties();
+ assertEquals("Verify number of members", 2, properties.size());
+
+ GroupProperty heatFiles = properties.stream().filter(p -> p.getName().equals("heat_files")).findFirst().get();
+ assertNotNull("check heat files not empty", heatFiles);
+ List<String> heatFilesValue = new ArrayList<>();
+ heatFilesValue.add("heat1.yaml");
+ heatFilesValue.add("heat2.yaml");
+ String heatFilesJson = gson.toJson(heatFilesValue);
+ log.debug(heatFiles.getValue());
+ assertEquals("check heat files value", heatFilesJson, heatFiles.getValue());
+
+ GroupProperty urlCredential = properties.stream().filter(p -> p.getName().equals("url_credential")).findFirst().get();
+ assertNotNull("check heat files not empty", urlCredential);
+ log.debug(urlCredential.getValue());
+ assertEquals("check url credential", "{\"protocol\":\"protocol1\",\"keys\":{\"keya\":\"valuea\",\"keyb\":\"valueb\"}}", urlCredential.getValue());
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarWithGroupsAndPropertyInvalidValue() throws Exception {
+
+ RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN);
+ // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsInvalidPropertyValue");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400);
+
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarWithGroupsAndInvalidPropertyName() throws Exception {
+
+ RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack1", UserRoleEnum.ADMIN);
+ // BaseRestUtils.checkCreateResponse(importNewGroupTypeByName);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsPropertyNotExist");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_PROPERTY_NOT_FOUND, "url_credential111", "group1", "org.openecomp.groups.MyHeatStack1");
+
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarGroupTypeNotExist() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsInvalidGroupType");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_TYPE_IS_INVALID, "org.openecomp.groups.stamGroupType");
+
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarMemberNotExist() throws Exception {
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsInvalidMember");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, "mycomp", "mygroup", ValidationUtils.normaliseComponentName(resourceDetails.getName()), "VF");
+
+ }
+
+ @Test(enabled = true)
+ public void createResourceFromCsarMemberNotAllowed() throws Exception {
+
+ RestResponse importNewGroupTypeByName = ImportRestUtils.importNewGroupTypeByName("myHeatStack2", UserRoleEnum.ADMIN);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("csarWithGroupsNotAllowedMember");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+
+ BaseRestUtils.checkStatusCode(createResource, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.GROUP_INVALID_TOSCA_NAME_OF_COMPONENT_INSTANCE, "nodejs", "group1", "org.openecomp.groups.MyHeatStack2");
+
+ }
+
+ @Test(enabled = true)
+ public void getResourceFromCsarUuidHappy() throws Exception {
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("tam");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(6, resource.getComponentInstances().size());
+
+ String expectedCsarUUID = resourceDetails.getCsarUUID();
+ String expectedToscaResourceName = "org.openecomp.resource.vf." + WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, resource.getCsarUUID()), expectedCsarUUID.equals(resource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, resource.getToscaResourceName()), expectedToscaResourceName.equals(resource.getToscaResourceName()));
+
+ RestResponse getResourceResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(resource.getCsarUUID());
+ Resource getResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(), Resource.class);
+ assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID, getResource.getCsarUUID()), expectedCsarUUID.equals(getResource.getCsarUUID()));
+ assertTrue("toscaResourceName : " + buildAssertMessage(expectedToscaResourceName, getResource.getToscaResourceName()), expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+ }
+
+ @Test(enabled = true)
+ public void getResourceFromCsarResourceNotFound() throws Exception {
+ String csarUUID = "tam";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+
+ RestResponse resResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(csarUUID);
+
+ BaseRestUtils.checkStatusCode(resResponse, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(resResponse, ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUUID);
+
+ }
+
+ @Test(enabled = true)
+ public void getResourceFromMissingCsar() throws Exception {
+ String csarUUID = "abcdefg12345";
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID(csarUUID);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+
+ RestResponse resResponse = ResourceRestUtils.getLatestResourceFromCsarUuid(csarUUID);
+
+ BaseRestUtils.checkStatusCode(resResponse, "Check bad request error", false, 400);
+ BaseRestUtils.checkErrorResponse(resResponse, ActionStatus.RESOURCE_FROM_CSAR_NOT_FOUND, csarUUID);
+
+ }
+
+ @Test(enabled = true)
+ public void createUpdateCertifiedImportResourceFromCsarTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes = copyCsarRest(sdncModifierDetails, "valid_vf_a.csar", "valid_vf.csar");
+ RestResponse updateResponse = null;
+ String oldName = null;
+ // create new resource from Csar
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setCsarUUID("valid_vf.csar");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+ String invariantUUID = resource.getInvariantUUID();
+
+ // change metadata
+ // resource name, icon, vendor name, category, template derivedFrom
+ oldName = resourceDetails.getName();
+ resourceDetails.setName("test1");
+ resourceDetails.setIcon("newicon");
+ resourceDetails.setVendorName("newname");
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.VSP_ALREADY_EXISTS, "valid_vf.csar", oldName);
+
+ updateResponse = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResponse);
+
+ LifecycleRestUtils.certifyResource(resourceDetails);
+ // change metadata
+ // resource name, icon, vendor name, category, template derivedFrom
+ resourceDetails.setName("test2");
+ resourceDetails.setIcon("new icon1");
+ resourceDetails.setVendorName("new name1");
+ resourceDetails.setDescription("bla bla bla");
+ updateResponse = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResponse);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResponse.getResponse(), Resource.class);
+ assertEquals(5, resource.getComponentInstances().size());
+ assertEquals(invariantUUID, resource.getInvariantUUID());
+ assertEquals(resource.getName(), "test1");
+ assertEquals(resource.getIcon(), "newicon");
+ assertEquals(resource.getVendorName(), "newname");
+ assertEquals(resource.getDescription(), "bla bla bla");
+ assertEquals(resource.getTags().contains("test2"), false);
+ }
+
+ @Test
+ public void createImportRIRelationByCapNameFromCsarUITest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "vmmc_relate_by_cap_name.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/vmmc_relate_by_cap_name.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ // create new resource from Csar
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ // assert all relations created
+ assertEquals(80, resource.getComponentInstancesRelations().size());
+ }
+
+ @Test
+ public void createImportRIRelationByCapNameFromCsarUITest2() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "vf_relate_by_cap_name.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ String rootPath = System.getProperty("user.dir");
+ Path path = null;
+ byte[] data = null;
+ String payloadData = null;
+
+ path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_relate_by_cap_name.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ // create new resource from Csar
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ // assert relations created: 1.by name: virtual_linkable. 2.by name:
+ // link
+ Map<String, ComponentInstance> nodes = resource.getComponentInstances().stream().collect(Collectors.toMap(n -> n.getName(), n -> n));
+ Map<String, CapabilityDefinition> capabilities = nodes.get("elinenode").getCapabilities().get("tosca.capabilities.network.Linkable").stream().collect(Collectors.toMap(e -> e.getName(), e -> e));
+ String cp1Uid = nodes.get("cp1node").getUniqueId();
+ String cp2Uid = nodes.get("cp2node").getUniqueId();
+ Map<String, List<RequirementCapabilityRelDef>> mappedByReqOwner = resource.getComponentInstancesRelations().stream().collect(Collectors.groupingBy(e -> e.getFromNode()));
+ assertEquals(mappedByReqOwner.get(cp1Uid).get(0).getRelationships().get(0).getCapabilityUid(), capabilities.get("virtual_linkable").getUniqueId());
+ assertEquals(mappedByReqOwner.get(cp2Uid).get(0).getRelationships().get(0).getCapabilityUid(), capabilities.get("link").getUniqueId());
+ }
+
+ private void verifyMembers(Map<String, String> createdMembers, Map<String, String> compNameToUniqueId) {
+ for (Map.Entry<String, String> entry : createdMembers.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ String comparedValue = compNameToUniqueId.get(key);
+
+ assertEquals("compare instance ids", comparedValue, value);
+ }
+
+ }
+
+ private static Map<String, String> prepareHeadersMap(String userId) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ if (userId != null) {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId);
+ }
+ return headersMap;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java
new file mode 100644
index 0000000000..873d33979f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportGenericResourceCITest.java
@@ -0,0 +1,599 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.http.HttpStatus;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.entity.mime.content.StringBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.TODO.ImportCapabilityTypeCITest;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+import fj.data.Either;
+
+public class ImportGenericResourceCITest extends ComponentBaseTest {
+ private static Logger log = LoggerFactory.getLogger(ImportGenericResourceCITest.class.getName());
+ private static final String FILE_NAME_MY_COMPUTE = "tosca.nodes.MyCompute";
+ private static final String RESOURCE_NAME_UPDATE_COMPUTE = "userUpdateCompute";
+ private static final String RESOURCE_NAME_MY_COMPUTE = "myCompute";
+ private static final String RESOURCE_NAME_USER_COMPUTE = "userCompute";
+ private static final String FILE_NAME_USER_COMPUTE = "tosca.nodes.userCompute";
+ @Rule
+ public static TestName name = new TestName();
+
+ public ImportGenericResourceCITest() {
+ super(name, ImportGenericResourceCITest.class.getName());
+ }
+
+ @BeforeClass
+ public static void beforeImportClass() throws IOException {
+ ImportCapabilityTypeCITest.importAllCapabilityTypes();
+ // removeAllNormativeTypeResources();
+ // importAllNormativeTypesResources(UserRoleEnum.ADMIN);
+ }
+
+ static Config config = Config.instance();
+
+ public static Map<NormativeTypesEnum, Boolean> removeAllNormativeTypeResources() throws ClientProtocolException, IOException {
+ Map<NormativeTypesEnum, Boolean> normativeExistInDB = new HashMap<>();
+
+ for (NormativeTypesEnum current : NormativeTypesEnum.values()) {
+ Boolean existedBeforeDelete = ImportRestUtils.removeNormativeTypeResource(current);
+ normativeExistInDB.put(current, existedBeforeDelete);
+ }
+ return normativeExistInDB;
+ }
+
+ public static Either<String, Boolean> getNormativeTypeResource(NormativeTypesEnum current) throws ClientProtocolException, IOException {
+ return getResource(current.getNormativeName(), "1.0");
+ }
+
+ @Test
+ public void importAllTestResources() throws Exception {
+ for (ImportTestTypesEnum currResource : ImportTestTypesEnum.values()) {
+ DbUtils.cleanAllAudits();
+
+ RestResponse importResponse = ImportRestUtils.importTestResource(currResource, UserRoleEnum.ADMIN);
+ // System.err.println("import Resource
+ // "+"<"+currResource+">"+"response:
+ // "+importResponse.getErrorCode());
+ ImportRestUtils.validateImportTestTypesResp(currResource, importResponse);
+ if (currResource.getvalidateAudit() == true) {
+ // validate audit
+ String baseVersion = "1.0";
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName());
+ expectedResourceAuditJavaObject.setResourceName(currResource.getNormativeName());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion(baseVersion);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.toString());
+ expectedResourceAuditJavaObject.setComment(null);
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction);
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------------------
+ protected void validateMyComputeCapabilities(Map<String, Object> map) {
+ assertTrue(map.containsKey("capabilities"));
+ Map<String, Object> capabilities = (Map<String, Object>) map.get("capabilities");
+ assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
+ List<Object> hostCapList = (List<Object>) capabilities.get("tosca.capabilities.Container");
+ assertFalse(hostCapList.isEmpty());
+ Map<String, Object> hostCap = (Map<String, Object>) hostCapList.get(0);
+ validateField(hostCap, "type", "tosca.capabilities.Container");
+ validateField(hostCap, "name", "host");
+ validateField(hostCap, "validSourceTypes", Arrays.asList(new String[] { "tosca.nodes.SoftwareComponent" }));
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin"));
+ List<Object> endPointCapList = (List<Object>) capabilities.get("tosca.capabilities.Endpoint.Admin");
+ assertFalse(endPointCapList.isEmpty());
+ Map<String, Object> endPointCap = (Map<String, Object>) endPointCapList.get(0);
+ validateField(endPointCap, "name", "endpoint");
+ validateField(endPointCap, "type", "tosca.capabilities.Endpoint.Admin");
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.OperatingSystem"));
+ List<Object> osCapList = (List<Object>) capabilities.get("tosca.capabilities.OperatingSystem");
+ assertFalse(osCapList.isEmpty());
+ Map<String, Object> osCap = (Map<String, Object>) osCapList.get(0);
+ validateField(osCap, "name", "os");
+ validateField(osCap, "type", "tosca.capabilities.OperatingSystem");
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.Scalable"));
+ List<Object> scalableCapList = (List<Object>) capabilities.get("tosca.capabilities.Scalable");
+ assertFalse(scalableCapList.isEmpty());
+ Map<String, Object> scalableCap = (Map<String, Object>) scalableCapList.get(0);
+ validateField(scalableCap, "name", "scalable");
+ validateField(scalableCap, "type", "tosca.capabilities.Scalable");
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.network.Bindable"));
+ List<Object> bindingCapList = (List<Object>) capabilities.get("tosca.capabilities.network.Bindable");
+ assertFalse(bindingCapList.isEmpty());
+ Map<String, Object> bindingCap = (Map<String, Object>) bindingCapList.get(0);
+ validateField(bindingCap, "name", "binding");
+ validateField(bindingCap, "type", "tosca.capabilities.network.Bindable");
+
+ }
+
+ protected void validateMyComputeResource(String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException {
+ Either<String, Boolean> eitherMyCompute = getResource(resourceName, resourceVersion);
+ assertTrue(eitherMyCompute.isLeft());
+ String testComputeYml = eitherMyCompute.left().value();
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map = (Map<String, Object>) new Gson().fromJson(testComputeYml, map.getClass());
+
+ validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState);
+
+ validateMyComputeCapabilities(map);
+
+ validateMyComputeRequirements(map);
+ validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion);
+
+ }
+
+ protected void validateMyComputeResource(String uid, String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException {
+ RestResponse resourceResponse = ResourceRestUtils.getResource(uid);
+ ResourceRestUtils.checkSuccess(resourceResponse);
+ String testComputeYml = resourceResponse.getResponse();
+
+ // Either<String, Boolean> eitherMyCompute = getResource(resourceName,
+ // resourceVersion);
+ // assertTrue( eitherMyCompute.isLeft() );
+ // String testComputeYml = eitherMyCompute.left().value();
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map = (Map<String, Object>) new Gson().fromJson(testComputeYml, map.getClass());
+
+ validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState);
+
+ validateMyComputeCapabilities(map);
+
+ validateMyComputeRequirements(map);
+ validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion);
+
+ }
+
+ protected void validateMyComputeResourceAfterUpdate(String uid, String resourceName, String resourceVersion, String expectedState) throws ClientProtocolException, IOException {
+ RestResponse resourceResponse = ResourceRestUtils.getResource(uid);
+ ResourceRestUtils.checkSuccess(resourceResponse);
+ String testComputeYml = resourceResponse.getResponse();
+
+ // Either<String, Boolean> eitherMyCompute = getResource(resourceName,
+ // resourceVersion);
+ // assertTrue( eitherMyCompute.isLeft() );
+
+ // String testComputeYml = eitherMyCompute.left().value();
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map = (Map<String, Object>) new Gson().fromJson(testComputeYml, map.getClass());
+
+ validateMyComputeBasicFields(map, resourceName, resourceVersion, expectedState);
+ validateField(map, RespJsonKeysEnum.DESCRIPTION.getRespJsonKeyName(), "Short description");
+ validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), "UserVendor");
+ validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(), "1.1.2");
+
+ // validateMyComputeCapabilities(map);
+ // AssertJUnit.assertTrue(map.containsKey("capabilities"));
+ // Map<String, Object> capabilities = (Map<String, Object>)
+ // map.get("capabilities");
+ // AssertJUnit.assertTrue(capabilities.containsKey("host"));
+ // Map<String, Object> hostCap = (Map<String, Object>)
+ // capabilities.get("host");
+ // validateField(hostCap, "type", "tosca.capabilities.Container");
+ // validateField(hostCap, "validSourceTypes", Arrays.asList(new
+ // String[]{"tosca.nodes.SoftwareComponent"}));
+ //
+ // AssertJUnit.assertTrue(capabilities.containsKey("endpoint"));
+ // Map<String, Object> endPointCap = (Map<String, Object>)
+ // capabilities.get("endpoint");
+ // validateField(endPointCap, "type",
+ // "tosca.capabilities.Endpoint.Admin");
+
+ assertTrue(map.containsKey("capabilities"));
+ Map<String, Object> capabilities = (Map<String, Object>) map.get("capabilities");
+ assertTrue(capabilities.containsKey("tosca.capabilities.Container"));
+ List<Object> hostCapList = (List<Object>) capabilities.get("tosca.capabilities.Container");
+ assertFalse(hostCapList.isEmpty());
+ Map<String, Object> hostCap = (Map<String, Object>) hostCapList.get(0);
+ validateField(hostCap, "type", "tosca.capabilities.Container");
+ validateField(hostCap, "name", "host");
+ validateField(hostCap, "validSourceTypes", Arrays.asList(new String[] { "tosca.nodes.SoftwareComponent" }));
+
+ assertTrue(capabilities.containsKey("tosca.capabilities.Endpoint.Admin"));
+ List<Object> endPointCapList = (List<Object>) capabilities.get("tosca.capabilities.Endpoint.Admin");
+ assertFalse(endPointCapList.isEmpty());
+ Map<String, Object> endPointCap = (Map<String, Object>) endPointCapList.get(0);
+ validateField(endPointCap, "name", "endpoint");
+ validateField(endPointCap, "type", "tosca.capabilities.Endpoint.Admin");
+
+ validateMyComputeRequirements(map);
+ validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceVersion);
+
+ }
+
+ protected void validateMyComputeRequirements(Map<String, Object> map) {
+ assertTrue(map.containsKey("requirements"));
+ Map<String, Object> requirements = (Map<String, Object>) map.get("requirements");
+
+ assertTrue(requirements.containsKey("tosca.capabilities.Attachment"));
+ List<Object> localStorageReqList = (List<Object>) requirements.get("tosca.capabilities.Attachment");
+ assertFalse(localStorageReqList.isEmpty());
+ Map<String, Object> localStorageReq = (Map<String, Object>) localStorageReqList.get(0);
+ validateField(localStorageReq, "capability", "tosca.capabilities.Attachment");
+ validateField(localStorageReq, "node", "tosca.nodes.BlockStorage");
+ validateField(localStorageReq, "relationship", "tosca.relationships.AttachesTo");
+ validateField(localStorageReq, "name", "local_storage");
+ }
+
+ protected void validateMyComputeBasicFields(Map<String, Object> map, String resourceName, String resourceVersion, String expectedState) {
+ validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(), false);
+ // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(),
+ // categoryDefinition);
+ // validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(),
+ // UniqueIdBuilder.buildResourceUniqueId(resourceName,
+ // resourceVersion));
+ validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceName);
+ validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), Arrays.asList(new String[] { resourceName }));
+ validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(), expectedState);
+
+ validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), Arrays.asList(new String[] { "tosca.nodes.Root" }));
+ }
+
+ protected static void validateField(Map<String, Object> map, String jsonField, Object expectedValue) {
+ if (expectedValue == null) {
+ assertTrue(!map.containsKey(jsonField));
+ } else {
+ assertTrue("map does not contain field " + jsonField, map.containsKey(jsonField));
+ Object foundValue = map.get(jsonField);
+ compareElements(expectedValue, foundValue);
+ }
+ }
+
+ protected static void compareElements(Object expectedValue, Object foundValue) {
+ if (expectedValue instanceof String) {
+ assertTrue(foundValue instanceof String);
+ assertTrue(foundValue.equals(expectedValue));
+ }
+
+ else if (expectedValue instanceof Boolean) {
+ assertTrue(foundValue instanceof Boolean);
+ assertTrue(foundValue == expectedValue);
+ } else if (expectedValue instanceof Map) {
+ assertTrue(foundValue instanceof Map);
+ Map<String, Object> foundMap = (Map<String, Object>) foundValue;
+ Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
+ assertTrue(foundMap.size() == excpectedMap.size());
+ Iterator<String> foundkeyItr = foundMap.keySet().iterator();
+ while (foundkeyItr.hasNext()) {
+ String foundKey = foundkeyItr.next();
+ assertTrue(excpectedMap.containsKey(foundKey));
+ compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey));
+ }
+
+ } else if (expectedValue instanceof List) {
+ assertTrue(foundValue instanceof List);
+ List<Object> foundList = (List<Object>) foundValue;
+ List<Object> excpectedList = (List<Object>) expectedValue;
+ assertTrue(foundList.size() == excpectedList.size());
+ for (int i = 0; i < foundList.size(); i++) {
+ compareElements(excpectedList.get(i), foundList.get(i));
+ }
+
+ } else if (expectedValue instanceof CategoryDefinition) {
+ assertTrue(foundValue instanceof Map);
+ CategoryDefinition expCat = (CategoryDefinition) expectedValue;
+ Map<String, Object> actCat = (Map<String, Object>) foundValue;
+ assertEquals(expCat.getName(), actCat.get("name"));
+
+ // assertEquals(expCat.getSubcategories().get(0).getName(),
+ // actCat.get("subcategories").getName());
+ } else {
+ assertTrue(foundValue.equals(expectedValue));
+ }
+ }
+
+ public static void restoreToOriginalState(Map<NormativeTypesEnum, Boolean> originalState, UserRoleEnum userRole) throws IOException {
+ removeAllNormativeTypeResources();
+
+ Iterator<Entry<NormativeTypesEnum, Boolean>> iterator = originalState.entrySet().iterator();
+ while (iterator.hasNext()) {
+ Entry<NormativeTypesEnum, Boolean> entry = iterator.next();
+ Boolean isExistBeforeDelete = entry.getValue();
+ if (isExistBeforeDelete) {
+ importNormativeResource(entry.getKey(), userRole);
+ }
+ }
+
+ }
+
+ public static void importAllNormativeTypesResources(UserRoleEnum userRole) throws IOException {
+ for (NormativeTypesEnum currResource : NormativeTypesEnum.values()) {
+ Either<String, Boolean> resource = getResource(currResource.getNormativeName(), "1.0");
+ if (resource.isRight()) {
+ importNormativeResource(currResource, userRole);
+ }
+ }
+
+ }
+
+ protected static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) throws IOException {
+ return importResource(resource.getFolderName(), userRole, true);
+ }
+
+ protected static Integer importResource(String folderName, UserRoleEnum userRole, boolean isNormative) throws IOException {
+ Config config = Utils.getConfig();
+ CloseableHttpResponse response = null;
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getZipFile(folderName)));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getJsonStringOfFile(folderName, folderName + ".json"), ContentType.APPLICATION_JSON));
+
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort());
+ if (!isNormative) {
+ url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+ }
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ httpPost.addHeader("USER_ID", userRole.getUserId());
+ httpPost.setEntity(mpBuilder.build());
+ response = client.execute(httpPost);
+ return response.getStatusLine().getStatusCode();
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+ }
+
+ public static void closeHttpClient(CloseableHttpClient client) {
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (IOException e) {
+ log.debug("failed to close client or response: ", e);
+ }
+ }
+
+ public static void closeResponse(CloseableHttpResponse response) {
+ try {
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException e) {
+ log.debug("failed to close client or response: ", e);
+ }
+ }
+
+ protected static String getJsonStringOfFile(String folderName, String fileName) throws IOException {
+ String sourceDir = config.getImportResourceConfigDir();
+ sourceDir += File.separator + "normative-types";
+
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName);
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String content = new String(fileContent);
+ return content;
+ }
+
+ protected static File getZipFile(String elementName) throws IOException {
+ String sourceDir = config.getImportResourceConfigDir();
+ sourceDir += File.separator + "normative-types";
+
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip");
+ return filePath.toFile();
+ }
+
+ protected static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
+ String sourceDir = config.getImportResourceTestsConfigDir();
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName);
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String content = new String(fileContent);
+ return content;
+ }
+
+ protected static File getTestZipFile(String elementName) throws IOException {
+ String sourceDir = config.getImportResourceTestsConfigDir();
+
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip");
+ return filePath.toFile();
+ }
+
+ protected static Either<String, Boolean> getResource(String name, String version) throws IOException {
+ RestResponse resource = ResourceRestUtils.getResourceByNameAndVersion(UserRoleEnum.DESIGNER.getUserId(), name, version);
+ if (resource.getErrorCode() == ImportRestUtils.STATUS_CODE_GET_SUCCESS) {
+ return Either.left(resource.getResponse());
+ // return Either.right(true);
+
+ }
+ return Either.right(false);
+ }
+
+ @Test
+ public void testImportWithRequirmentsAndCapabilities() throws IOException {
+ String fileName = FILE_NAME_MY_COMPUTE;
+ RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED");
+ }
+
+ @Test
+ public void testImportWithUpdateNormativeType() throws IOException {
+ String fileName = FILE_NAME_MY_COMPUTE;
+ RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == BaseRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED");
+
+ // update
+ response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.ADMIN);
+ statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS);
+ uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "2.0", "CERTIFIED");
+
+ }
+
+ @Test
+ public void testImportWithInvalidDefaultValue() throws IOException {
+ RestResponse response = ImportRestUtils.importNewResourceByName("portInvalidDefaultValue", UserRoleEnum.DESIGNER);
+ assertTrue(response.getErrorCode() == HttpStatus.SC_BAD_REQUEST);
+ }
+
+ @Test
+ public void testImportUserResource() throws IOException {
+ String fileName = FILE_NAME_USER_COMPUTE;
+ RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT");
+
+ }
+
+ @Test
+ public void testImportAndUpdateUserResource() throws IOException {
+ String fileName = FILE_NAME_USER_COMPUTE;
+ RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT");
+ response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_UPDATE_COMPUTE, UserRoleEnum.DESIGNER);
+ statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS);
+ uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResourceAfterUpdate(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT");
+
+ }
+
+ @Test
+ public void testImportAndUpdateChangesUserResource() throws IOException {
+ String fileName = FILE_NAME_USER_COMPUTE;
+ RestResponse response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT");
+ // Either<String, Boolean> resource = getResource(fileName, "0.1");
+ // assertTrue(resource.isLeft());
+
+ response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_UPDATE_COMPUTE, UserRoleEnum.DESIGNER);
+ statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS);
+ validateMyComputeResourceAfterUpdate(uid, fileName, "0.1", "NOT_CERTIFIED_CHECKOUT");
+
+ }
+
+ @Test
+ public void testImportCheckoutAndUpdateUserResource() throws IOException {
+ String fileName = FILE_NAME_USER_COMPUTE;
+ RestResponse response = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.ADMIN);
+ Integer statusCode = response.getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.STATUS_CODE_IMPORT_SUCCESS);
+ String uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "1.0", "CERTIFIED");
+
+ response = ImportRestUtils.importNewResourceByName(RESOURCE_NAME_USER_COMPUTE, UserRoleEnum.DESIGNER);
+ statusCode = response.getErrorCode();
+ assertEquals("check response code after update resource", ImportRestUtils.STATUS_CODE_UPDATE_SUCCESS, statusCode.intValue());
+ uid = ResponseParser.getUniqueIdFromResponse(response);
+ validateMyComputeResource(uid, fileName, "1.1", "NOT_CERTIFIED_CHECKOUT");
+
+ }
+
+ @Test
+ public void importNormativeTypesTesterUserRole() throws Exception {
+ Integer statusCode = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.TESTER).getErrorCode();
+ assertTrue(statusCode == ImportRestUtils.RESTRICTED_OPERATION);
+ }
+
+ @Test
+ public void importNormativeTypesDesignerUserRole() throws Exception {
+ Integer statusCode = ImportRestUtils.importNormativeResourceByName(RESOURCE_NAME_MY_COMPUTE, UserRoleEnum.DESIGNER).getErrorCode();
+ assertTrue(statusCode == 409);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java
new file mode 100644
index 0000000000..ec335fa65f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java
@@ -0,0 +1,1431 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpStatus;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ImportNewResourceCITest extends ComponentBaseTest {
+
+ // public static UserUtils userUtils = new UserUtils();
+ // public ResourceUtils resourceUtils = new ResourceUtils();
+ // public AuditValidationUtils AuditValidationUtils = new
+ // AuditValidationUtils();
+ // protected ArtifactUtils artifactUtils = new ArtifactUtils();
+
+ protected String resourceVersion = null;
+ protected String auditAction = null;
+ public User sdncModifierDetails = new User();
+ protected String artifactName1 = "data_artifact1.sh";
+ protected String artifactName2 = "data_artifact2.sh";
+ protected String interfaze = "standard";
+ protected String interfaceArtifactName = "data_interface1.sh";
+
+ private String SPECIAL_CHARACTERS = "~!#@~$%^*()[];:'\"|\\/";
+
+ public ResourceReqDetails resourceDetails = new ResourceReqDetails();
+
+ public Gson gson = new Gson();
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ImportNewResourceCITest() {
+ super(name, ImportNewResourceCITest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+
+ // init user
+ sdncModifierDetails.setUserId(UserRoleEnum.ADMIN.getUserId());
+ // init resource details
+ resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
+ }
+
+ @Test
+ public void importAllTestResources_toValidateNewAPI() throws Exception {
+
+ for (ImportTestTypesEnum currResource : ImportTestTypesEnum.values()) {
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import testResources trough newResource API
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName(currResource.getFolderName(), UserRoleEnum.ADMIN);
+ System.err.println("import Resource " + "<" + currResource.getFolderName() + ">" + "response: " + importResponse.getErrorCode());
+
+ // validate response
+ ImportRestUtils.validateImportTestTypesResp(currResource, importResponse);
+ if (currResource.getvalidateAudit() == true) {
+ // validate audit
+ // String baseVersion="0.1";
+ String baseVersion = "";
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName());
+ expectedResourceAuditJavaObject.setResourceName(currResource.getNormativeName());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion(baseVersion);
+ expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setComment(null);
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAuditImport(expectedResourceAuditJavaObject, auditAction);
+ }
+ }
+ }
+
+ protected RestResponse importNewResource(UserRoleEnum userRoleEnum) throws Exception {
+
+ // init user
+ sdncModifierDetails.setUserId(userRoleEnum.getUserId());
+ // init resource details
+ resourceDetails = ElementFactory.getDefaultResource("importResource4test", NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
+ // clean ES DB
+ DbUtils.cleanAllAudits();
+ // import new resource (expected checkOut state)
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4test", userRoleEnum);
+ return importResponse;
+ }
+
+ @Test(enabled = false)
+ public void importUIResource() throws IOException {
+ String payload = "tosca_definitions_version: tosca_simple_yaml_1_0_0\r\n" + "node_types: \r\n" + " org.openecomp.resource.importResource4test:\r\n" + " derived_from: tosca.nodes.Root\r\n" + " description: someDesc";
+
+ String encodedPayload = new String(Base64.encodeBase64(payload.getBytes()));
+
+ String json = "{\r\n" + " \"resourceName\": \"importResource4test\",\r\n" + " \"payloadName\": \"importResource4test.yml\",\r\n"
+ + " \"categories\": [{\"name\": \"Application L4+\",\"normalizedName\": \"application l4+\",\"uniqueId\": \"resourceNewCategory.application l4+\",\"subcategories\": [{\"name\": \"Web Server\"}]}],\r\n"
+ + " \"description\": \"ResourceDescription\",\r\n" + " \"vendorName\": \"VendorName\",\r\n" + " \"vendorRelease\": \"VendorRelease\",\r\n" + " \"contactId\": \"AT1234\",\r\n" + " \"icon\": \"router\",\r\n" + " \"tags\": [\r\n"
+ + " \"importResource4test\"\r\n" + " ],\r\n" + " \"payloadData\": \"" + encodedPayload + "\"\r\n" + "}";
+
+ String md5 = GeneralUtility.calculateMD5ByString(json);
+
+ Map<String, String> headers = new HashMap<String, String>();
+ headers.put(Constants.MD5_HEADER, md5);
+ headers.put(Constants.USER_ID_HEADER, UserRoleEnum.ADMIN.getUserId());
+ headers.put(Constants.CONTENT_TYPE_HEADER, "application/json");
+
+ String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ HttpRequest httpUtil = new HttpRequest();
+ RestResponse httpSendPost = httpUtil.httpSendPost(url, json, headers);
+ Integer errorCode = httpSendPost.getErrorCode();
+ assertTrue(errorCode == HttpStatus.SC_CREATED);
+
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_suc() throws Exception {
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ // validate response
+
+ resourceVersion = "0.1";
+
+ // ResourceRespJavaObject resourceRespJavaObject =
+ // Convertor.constructFieldsForRespValidation(resourceDetails,
+ // resourceVersion);
+ // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // ResourceValidationUtils.validateResp(importResponse,
+ // resourceRespJavaObject);
+ //
+ // //validate get response
+ //
+ // RestResponse resourceGetResponse =
+ // ResourceRestUtils.getResource(sdncModifierDetails, resourceVersion);
+ // ResourceValidationUtils.validateResp(resourceGetResponse,
+ // resourceRespJavaObject);
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromImport);
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // validate
+ ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
+
+ // validate audit
+ resourceDetails.setVersion(resourceDetails.getVersion());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+
+ auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void importNewResource_byTester_failed() throws Exception {
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.TESTER);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 409, importResponse.getErrorCode().intValue());
+
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existInCheckout_updateVendorName_updateCategory() throws Exception {
+
+ // import new resource
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4testUpdateVendorNameAndCategory", UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue());
+
+ // validate response
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromImport);
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // validate
+ ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
+
+ // validate audit
+ resourceDetails.setVersion(resourceDetails.getVersion());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+
+ auditAction = "ResourceImport";
+ resourceVersion = "0.1";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void importNewResource_perfromByAdmin_ownedBy_diffrentUser() throws Exception {
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.DESIGNER);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), importResponse.getErrorCode());
+
+ String[] split = resourceFromImport.getLastUpdaterFullName().split(" ");
+ String firstName = split[0];
+ String lastName = split[1];
+ List<String> variables = Arrays.asList(resourceFromImport.getName(), "resource", firstName, lastName, resourceFromImport.getLastUpdaterUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name(), variables, importResponse.getResponse());
+
+ }
+
+ @Test
+ public void importNewResource_perfromByDesigner_ownedBy_diffrentUser() throws Exception {
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ importResponse = importNewResource(UserRoleEnum.DESIGNER);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name());
+ assertEquals("Check response code after adding artifact", errorInfo.getCode(), importResponse.getErrorCode());
+
+ String[] split = resourceFromImport.getLastUpdaterFullName().split(" ");
+ String firstName = split[0];
+ String lastName = split[1];
+ List<String> variables = Arrays.asList(resourceFromImport.getName(), "resource", firstName, lastName, resourceFromImport.getLastUpdaterUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CHECKOUT_STATE.name(), variables, importResponse.getResponse());
+
+ }
+
+ @Test(enabled = false)
+ public void importNewResource_nameSpace_vf() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVF", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VF));
+
+ }
+
+ @Test
+ public void importNewResource_nameSpace_vfc() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVFC", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VFC));
+ }
+
+ @Test
+ public void importNewResource_nameSpace_vl() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testVL", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VL));
+
+ }
+
+ @Test
+ public void importNewResource_nameSpace_cp() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testCP", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.CP));
+ }
+
+ @Test
+ public void importNewResource_nameSpace_unknown() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertTrue(resourceRespJavaObject.getResourceType().equals(ResourceTypeEnum.VFC));
+
+ }
+
+ @Test
+ public void importNewResource_MissingNameSpace() throws Exception {
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName("importResource4testMissingNameSpace", UserRoleEnum.DESIGNER);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 400, importResponse.getErrorCode().intValue());
+
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existInCheckOut() throws Exception {
+
+ // import new resource
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in CHECKOUT state
+
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue());
+
+ // validate response
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromImport);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // validate
+ ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
+
+ // validate audit
+ resourceDetails.setVersion(resourceDetails.getVersion());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+
+ auditAction = "ResourceImport";
+ resourceVersion = "0.1";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existIn_CheckIn_state() throws Exception {
+
+ // import new resource
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ // checkIn resource
+
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in CHECKIN state
+
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue());
+
+ // validate response
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromImport);
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // validate
+ ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
+
+ // validate audit
+ resourceDetails.setVersion(resourceDetails.getVersion());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails);
+
+ resourceVersion = "0.2";
+ auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void importNewResource_existIn_Ready4cert_state_performByTester() throws Exception {
+ // import new resource
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ // add mandatory artifacts
+ // // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(checkInResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(checkInResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in CHECKIN state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.TESTER);
+
+ // validate response
+ resourceVersion = resourceDetails.getVersion();
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ assertNotNull("check response object is not null after create resouce", importResponse);
+ assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, importResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setResourceName("");
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existIn_Ready4cert_state_performByDesigner() throws Exception {
+ // import new resource
+
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION.name());
+ assertNotNull("check response object is not null after create resouce", importResponse);
+ assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode());
+ String[] split = resourceFromGet.getLastUpdaterFullName().split(" ");
+ String firstName = split[0];
+ String lastName = split[1];
+ List<String> variables = Arrays.asList(resourceFromGet.getName(), "resource", firstName, lastName, resourceFromGet.getLastUpdaterUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SENT_FOR_CERTIFICATION.name(), variables, importResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.DESIGNER.getUserName());
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.READY_FOR_CERTIFICATION).toString());
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existIn_Ready4cert_state_performByAdmin() throws Exception {
+
+ // import new resource
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 200, importResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+ resourceVersion = resourceDetails.getVersion();
+ // resourceVersion="0.2";
+
+ // validate response
+ Resource resourceFromImport = ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ assertNotNull(resourceFromImport);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ // validate get response
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceRespJavaObject.getUniqueId());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // validate
+ ResourceValidationUtils.validateModelObjects(resourceFromImport, resourceFromGet);
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void importNewResource_existIn_CerInProgress_state_performByTester() throws Exception {
+
+ // import new resource
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // startCert
+ RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertNotNull("check response object is not null after resource request start certification", startCert);
+ assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.TESTER);
+
+ // validate response
+ resourceVersion = resourceDetails.getVersion();
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ assertNotNull("check response object is not null after create resouce", importResponse);
+ assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, importResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setResourceName("");
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existIn_CerInProgress_state_performByDesigner() throws Exception {
+
+ User sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // import new resource
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // startCert
+ RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertNotNull("check response object is not null after resource request start certification", startCert);
+ assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+ resourceVersion = resourceDetails.getVersion();
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.DESIGNER);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name());
+ assertNotNull("check response object is not null after create resouce", importResponse);
+ assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode());
+ List<String> variables = Arrays.asList(resourceDetails.getName(), "resource", sdncAdminUser.getFirstName(), sdncAdminUser.getLastName(), sdncAdminUser.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name(), variables, importResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.DESIGNER.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.DESIGNER.getUserName());
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.CERTIFICATION_IN_PROGRESS).toString());
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ // TODO DE171337
+ @Test(enabled = false)
+ public void importNewResource_existIn_CerInProgress_state_performByAdmin() throws Exception {
+
+ User sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // import new resource
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // checkIn resource
+ resourceVersion = resourceDetails.getVersion();
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ // startCert
+ RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertNotNull("check response object is not null after resource request start certification", startCert);
+ assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+ resourceVersion = resourceDetails.getVersion();
+
+ // clean audit
+ DbUtils.cleanAllAudits();
+
+ // import new resource while resource already exist in other state
+ importResponse = ImportRestUtils.importNewResourceByName("importResource4test", UserRoleEnum.ADMIN);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name());
+ assertNotNull("check response object is not null after create resouce", importResponse);
+ assertNotNull("check error code exists in response after create resource", importResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), importResponse.getErrorCode());
+ List<String> variables = Arrays.asList(resourceDetails.getName(), "resource", sdncAdminUser.getFirstName(), sdncAdminUser.getLastName(), sdncAdminUser.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_IN_CERT_IN_PROGRESS_STATE.name(), variables, importResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "ResourceImport";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName());
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.CERTIFICATION_IN_PROGRESS).toString());
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ // TODO DE171337
+ // @Test(enabled = false)
+ // public void
+ // importNewResource_existIn_Certified_state_chnage_reqAndCap_byDesigner()
+ // throws Exception{
+ //
+ // // Andrey - set default artifact details
+ // ArtifactDefinition artifactDefinition =
+ // artifactUtils.constructDefaultArtifactInfo();
+ //
+ // // import new resource
+ // RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+ // assertNotNull("check response object is not null after import resource",
+ // importResponse);
+ // assertNotNull("check error code exists in response after import
+ // resource", importResponse.getErrorCode());
+ // assertEquals("Check response code after import resource", 201,
+ // importResponse.getErrorCode().intValue());
+ // String resourceId =
+ // ResponseParser.getUniqueIdFromResponse(importResponse);
+ // resourceDetails =
+ // ResponseParser.parseToObject(importResponse.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceVersion = resourceDetails.getVersion();
+ // RestResponse resourceGetResponse =
+ // ResourceRestUtils.getResource(sdncModifierDetails,
+ // resourceDetails.getUniqueId());
+ // assertEquals("Check response code after get resource", 200,
+ // resourceGetResponse.getErrorCode().intValue());
+ // Resource resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ // assertNotNull(resourceFromGet);
+ //
+ // // add mandatory artifacts
+ // // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ // resourceDetails.getUniqueId());
+ // assertEquals("Check response code after get resource", 200,
+ // resourceGetResponse.getErrorCode().intValue());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ // assertNotNull(resourceFromGet);
+ // resourceDetails =
+ // ResponseParser.parseToObject(importResponse.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceDetails.setVersion(resourceFromGet.getVersion());
+ //
+ // // add artifact
+ // artifactDefinition.setArtifactName(artifactName1);
+ // ArtifactRestUtils.addInformationalArtifactToResource(resourceDetails,
+ // sdncModifierDetails, resourceVersion , artifactDefinition);
+ //
+ // // add artifact
+ // artifactDefinition.setArtifactName(artifactName2);
+ // resourceUtils.add_artifact(resourceDetails, sdncModifierDetails,
+ // resourceVersion , artifactDefinition);
+ //
+ // // add interface
+ // artifactDefinition.setArtifactName(interfaceArtifactName);
+ // ResourceRestUtils.add_interface(resourceDetails, sdncModifierDetails,
+ // resourceVersion , artifactDefinition);
+ //
+ // //construct fields for validation
+ // resourceVersion="1.0";
+ //
+ // ResourceRespJavaObject resourceRespJavaObject =
+ // Convertor.constructFieldsForRespValidation(resourceDetails,
+ // resourceVersion);
+ // ArrayList<String> artifacts = new ArrayList<String>();
+ //
+ // artifacts.add(resourceId+":"+artifactName1);
+ // artifacts.add(resourceId+":"+artifactName2);
+ // resourceRespJavaObject.setArtifacts(artifacts);
+ // ArrayList<String> interfaces = new ArrayList<String>();
+ //
+ // interfaces.add(interfaze);
+ // resourceRespJavaObject.setInterfaces(interfaces);
+ //
+ // // checkIn resource
+ // resourceVersion = resourceDetails.getVersion();
+ // String checkinComment = "good checkin";
+ // String checkinComentJson = "{\"userRemarks\": \""+checkinComment+"\"}";
+ // RestResponse checkInResponse =
+ // LifecycleRestUtils.changeResourceState(resourceDetails,
+ // sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CHECKIN,
+ // checkinComentJson);
+ // assertNotNull("check response object is not null after import resource",
+ // checkInResponse);
+ // assertEquals("Check response code after checkout resource", 200,
+ // checkInResponse.getErrorCode().intValue());
+ //
+ // // req4cert resource
+ // RestResponse request4cert =
+ // LifecycleRestUtils.changeResourceState(resourceDetails,
+ // sdncModifierDetails, resourceVersion,
+ // LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ // assertNotNull("check response object is not null after resource request
+ // for certification", request4cert);
+ // assertEquals("Check response code after checkout resource", 200,
+ // request4cert.getErrorCode().intValue());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ // assertNotNull(resourceFromGet);
+ // resourceDetails =
+ // ResponseParser.parseToObject(request4cert.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceDetails.setVersion(resourceFromGet.getVersion());
+ //
+ // // startCert
+ // RestResponse startCert =
+ // LifecycleRestUtils.changeResourceState(resourceDetails,
+ // sdncModifierDetails, resourceVersion,
+ // LifeCycleStatesEnum.STARTCERTIFICATION);
+ // assertNotNull("check response object is not null after resource request
+ // start certification", startCert);
+ // assertEquals("Check response code after checkout resource", 200,
+ // startCert.getErrorCode().intValue());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse());
+ // assertNotNull(resourceFromGet);
+ // resourceDetails = ResponseParser.parseToObject(startCert.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceDetails.setVersion(resourceFromGet.getVersion());
+ //
+ // // certify
+ // RestResponse certify =
+ // LifecycleRestUtils.changeResourceState(resourceDetails,
+ // sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFY);
+ // assertNotNull("check response object is not null after resource request
+ // certify", certify);
+ // assertEquals("Check response code after certify resource", 200,
+ // certify.getErrorCode().intValue());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(certify.getResponse());
+ // assertNotNull(resourceFromGet);
+ // resourceDetails = ResponseParser.parseToObject(certify.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceDetails.setVersion(resourceFromGet.getVersion());
+ //
+ // // clean audit
+ // DbUtils.cleanAllAudits();
+ //
+ // // change resource details
+ // resourceDetails =
+ // ElementFactory.getDefaultResource("tosca.nodes.importResource4test",
+ // NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ // "jh0003");
+ //
+ // // import new resource while resource already exist in other state
+ // importResponse =
+ // ImportRestUtils.importNewResourceByName("importResource4testUpdateWithoutReqCap",
+ // UserRoleEnum.ADMIN);
+ // assertNotNull("check response object is not null after import resource",
+ // importResponse);
+ // assertNotNull("check error code exists in response after import
+ // resource", importResponse.getErrorCode());
+ // assertEquals("Check response code after import resource", 200,
+ // importResponse.getErrorCode().intValue());
+ // resourceDetails =
+ // ResponseParser.parseToObject(importResponse.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceVersion = resourceDetails.getVersion();
+ // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ // resourceDetails.getUniqueId());
+ // assertEquals("Check response code after get resource", 200,
+ // resourceGetResponse.getErrorCode().intValue());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ // assertNotNull(resourceFromGet);
+ //
+ // // validate response
+ // Resource resourceFromImport =
+ // ResponseParser.convertResourceResponseToJavaObject(importResponse.getResponse());
+ // assertNotNull(resourceFromImport);
+ //
+ // resourceDetails =
+ // ResponseParser.parseToObject(importResponse.getResponse(),
+ // ResourceReqDetails.class);
+ // resourceRespJavaObject =
+ // Convertor.constructFieldsForRespValidation(resourceDetails);
+ // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ //
+ // // validate get response
+ // resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ // resourceRespJavaObject.getUniqueId());
+ // resourceFromGet =
+ // ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ // assertNotNull(resourceFromGet);
+ //
+ // // validate
+ // ResourceValidationUtils.validateModelObjects(resourceFromImport,
+ // resourceFromGet);
+ //
+ // // validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // Convertor.constructFieldsForAuditValidation(resourceDetails,
+ // resourceVersion);
+ // auditAction="ResourceImport";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setPrevVersion(resourceVersion);
+ // expectedResourceAuditJavaObject.setStatus("200");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // expectedResourceAuditJavaObject.setToscaNodeType(resourceFromGet.getToscaResourceName());
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ // }
+
+ @Test
+ public void importNewResource_uuidTest() throws Exception {
+ RestResponse importResponse = importNewResource(UserRoleEnum.ADMIN);
+
+ assertNotNull("check response object is not null after import resource", importResponse);
+ assertNotNull("check error code exists in response after import resource", importResponse.getErrorCode());
+ assertEquals("Check response code after import resource", 201, importResponse.getErrorCode().intValue());
+ String oldUuid = ResponseParser.getValueFromJsonResponse(importResponse.getResponse(), "uuid");
+
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceVersion = resourceDetails.getVersion();
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ Resource resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ // add mandatory artifacts
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // resourceGetResponse);
+ resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertEquals("Check response code after get resource", 200, resourceGetResponse.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(importResponse.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ String newUuid = ResponseParser.getValueFromJsonResponse(checkInResponse.getResponse(), "uuid");
+ assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid));
+
+ // req4cert resource
+ RestResponse request4cert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertNotNull("check response object is not null after resource request for certification", request4cert);
+ assertEquals("Check response code after checkout resource", 200, request4cert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(request4cert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(request4cert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ String newUuid2 = ResponseParser.getValueFromJsonResponse(request4cert.getResponse(), "uuid");
+ assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid2));
+
+ // startCert
+ RestResponse startCert = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertNotNull("check response object is not null after resource request start certification", startCert);
+ assertEquals("Check response code after checkout resource", 200, startCert.getErrorCode().intValue());
+ resourceFromGet = ResponseParser.convertResourceResponseToJavaObject(startCert.getResponse());
+ assertNotNull(resourceFromGet);
+ resourceDetails = ResponseParser.parseToObject(startCert.getResponse(), ResourceReqDetails.class);
+ resourceDetails.setVersion(resourceFromGet.getVersion());
+
+ String newUuid3 = ResponseParser.getValueFromJsonResponse(startCert.getResponse(), "uuid");
+ assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid3));
+
+ RestResponse certify = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "0.1", LifeCycleStatesEnum.CERTIFY);
+ assertNotNull("check response object is not null after import resource", certify);
+ assertEquals("Check response code after checkout resource", 200, certify.getErrorCode().intValue());
+
+ String newUuid4 = ResponseParser.getValueFromJsonResponse(certify.getResponse(), "uuid");
+ assertTrue(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid4));
+
+ RestResponse checkoutResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, "1.0", LifeCycleStatesEnum.CHECKOUT);
+ assertNotNull("check response object is not null after import resource", checkInResponse);
+ assertEquals("Check response code after checkout resource", 200, checkInResponse.getErrorCode().intValue());
+
+ String newUuid5 = ResponseParser.getValueFromJsonResponse(checkoutResponse.getResponse(), "uuid");
+ assertFalse(ResourceValidationUtils.validateUuidAfterChangingStatus(oldUuid, newUuid5));
+ }
+
+ @Test
+ public void importNewResource_propertiesMapInternalUrlCredential() throws Exception {
+ String folderName = "validateProporties_typeMap_valueUrlCredential";
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class);
+
+ List<PropertyDefinition> properties = resource.getProperties();
+ assertEquals("check properties size", 3, properties.size());
+
+ PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test")).findFirst().get();
+ String defaultValue = propertyDefinition.getDefaultValue();
+
+ Map mapValue = gson.fromJson(defaultValue, Map.class);
+ assertEquals("check Map value size", 2, mapValue.size());
+ checkMapValues(mapValue, "key", 1, null);
+ checkMapValues(mapValue, "key", 2, null);
+
+ System.err.println("import Resource " + "<" + folderName + ">" + "response: " + importResponse.getErrorCode());
+
+ }
+
+ @Test
+ public void importNewResource_propertiesListInternalUrlCredential() throws Exception {
+ String folderName = "validateProporties_typeList_valueUrlCredential";
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class);
+
+ List<PropertyDefinition> properties = resource.getProperties();
+ assertEquals("check properties size", 3, properties.size());
+
+ PropertyDefinition propertyDefinition = properties.stream().filter(p -> p.getName().equals("validation_test")).findFirst().get();
+ String defaultValue = propertyDefinition.getDefaultValue();
+
+ List listValue = gson.fromJson(defaultValue, List.class);
+ assertEquals("check List value size", 2, listValue.size());
+ checkListValues(listValue.get(0), 1, SPECIAL_CHARACTERS);
+ checkListValues(listValue.get(1), 2, SPECIAL_CHARACTERS);
+
+ // Verify attributes
+ List<AttributeDefinition> attributes = resource.getAttributes();
+
+ assertEquals("check properties size", 2, attributes.size());
+
+ // Verify attribute from type map
+ AttributeDefinition attributeMapDefinition = attributes.stream().filter(p -> p.getName().equals("validation_test_map")).findFirst().get();
+ String defaultMapValue = attributeMapDefinition.getDefaultValue();
+ Map attributeMapValue = gson.fromJson(defaultMapValue, Map.class);
+ assertEquals("check Map value size", 2, attributeMapValue.size());
+ checkMapValues(attributeMapValue, "key", 1, SPECIAL_CHARACTERS);
+ checkMapValues(attributeMapValue, "key", 2, SPECIAL_CHARACTERS);
+
+ // Verify attribute from type list
+ AttributeDefinition attributeListDefinition = attributes.stream().filter(p -> p.getName().equals("validation_test_list")).findFirst().get();
+ String defaultListValue = attributeListDefinition.getDefaultValue();
+
+ List attributeListValue = gson.fromJson(defaultListValue, List.class);
+ assertEquals("check List value size", 2, attributeListValue.size());
+ checkListValues(attributeListValue.get(0), 1, SPECIAL_CHARACTERS);
+ checkListValues(attributeListValue.get(1), 2, SPECIAL_CHARACTERS);
+
+ System.err.println("import Resource " + "<" + folderName + ">" + "response: " + importResponse.getErrorCode());
+
+ }
+
+ private void checkListValues(Object object, int index, String suffix) {
+
+ Map map = (Map) object;
+ assertEquals("check Map protocol value", "protocol" + index + (suffix == null ? "" : suffix), map.get("protocol"));
+ assertEquals("check Map token value", "token" + index, map.get("token"));
+ }
+
+ // @Test
+ public void importNewResource_validateProporties_typeTestDataType() throws Exception {
+ String folderName = "validateProporties_typeTestDataType";
+ RestResponse importResponse = ImportRestUtils.importNewResourceByName(folderName, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(importResponse.getResponse(), Resource.class);
+
+ }
+
+ private void checkMapValues(Map mapValue, String key, int index, String suffix) {
+
+ Map map1 = (Map) mapValue.get(key + index);
+ assertEquals("check Map protocol value", "protocol" + index + (suffix == null ? "" : suffix), map1.get("protocol"));
+ assertEquals("check Map token value", "token" + index, map1.get("token"));
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java
new file mode 100644
index 0000000000..3d7c81abae
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaCapabilitiesWithProperties.java
@@ -0,0 +1,416 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+/**
+ * US US730518 Story [BE] - TOSCA capabilities with properties - import "As a
+ * resource designer, I would like to add my VFC capabilities with properties."
+ *
+ * @author ns019t
+ *
+ */
+public class ImportToscaCapabilitiesWithProperties extends ComponentBaseTest {
+ @Rule
+ public static TestName name = new TestName();
+
+ Gson gson = new Gson();
+
+ /**
+ * public Constructor ImportToscaCapabilitiesWithProperties
+ */
+ public ImportToscaCapabilitiesWithProperties() {
+ super(name, ImportToscaCapabilitiesWithProperties.class.getName());
+ }
+
+ /**
+ * String constants
+ */
+ public static String propertyForTestName = "propertyfortest";
+ public static String rootPath = System.getProperty("user.dir");
+ public static String scalable = "tosca.capabilities.Scalable";
+ public static String container = "tosca.capabilities.Container";
+ public static String minInstances = "min_instances";
+ public static String userDefinedNodeYaml = "mycompute.yml";
+
+ /**
+ * Capability Type - capability type on the graph should already have
+ * properties modeled on it. please verify. The import of the capability
+ * types should support adding those properties. when importing, validate
+ * name uniqueness between the capability's properties see capability
+ * tosca.capabilities.Container
+ *
+ * Acceptance Criteria: validate capability type properties (for example,
+ * compute have capability Container -> the properties of this capability
+ * should be in the Json response)
+ *
+ * @throws IOException
+ */
+ @Test
+ public void validateCapabilityTypePropertiesSucceed() throws IOException {
+ User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse createResourceRes = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), "Compute",
+ "1.0");
+ BaseRestUtils.checkSuccess(createResourceRes);
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(createResourceRes.getResponse());
+ Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
+ assertEquals(capabilities.size(), 6);
+
+ CapabilityDefinition capability = capabilities.get(scalable).get(0);
+ List<ComponentInstanceProperty> properties = capability.getProperties();
+ assertEquals(properties.size(), 3);
+ assertTrue(!properties.stream().filter(p -> p.getName().equalsIgnoreCase(propertyForTestName)).findAny()
+ .isPresent());
+
+ ComponentInstanceProperty originalProperty = properties.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(minInstances)).findAny().get();
+ assertEquals(originalProperty.getType(), "integer");
+ assertEquals(originalProperty.getDefaultValue(), "1");
+
+ capability = capabilities.get(container).get(0);
+ properties = capability.getProperties();
+ assertEquals(properties.size(), 4);
+ }
+
+ /**
+ * Capability Definition on VFC / CP / VL - properties can also be defined
+ * on the capability when the capability is declared. (property definition
+ * with default value) If the property name (case insensitive) already
+ * defined on the capability type, it overrides the capability from the
+ * capability type Import of VFC / CP /VL should support adding properties
+ * to the capability. when importing, validate name uniqueness between the
+ * capability's properties
+ *
+ * Acceptance Criteria: import node type with capability definition on it.
+ * use the attached "myCompute"
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importNodeTypeWithCapabilityWithPropertiesFromYmlSucceed() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails,
+ resourceDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
+ assertEquals(capabilities.size(), 6);
+
+ CapabilityDefinition capability = capabilities.get(scalable).get(0);
+ List<ComponentInstanceProperty> properties = capability.getProperties();
+ assertEquals(properties.size(), 4);
+
+ ComponentInstanceProperty newProperty = properties.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(propertyForTestName)).findAny().get();
+ assertEquals(newProperty.getType(), "string");
+ assertEquals(newProperty.getDescription(), "test");
+ assertEquals(newProperty.getDefaultValue(), "success");
+
+ ComponentInstanceProperty overriddenProperty = properties.stream()
+ .filter(p -> p.getName().equalsIgnoreCase(minInstances)).collect(Collectors.toList()).get(0);
+ assertEquals(overriddenProperty.getType(), "integer");
+ assertEquals(overriddenProperty.getDefaultValue(), "3");
+
+ }
+
+ /**
+ * importNodeTypeWithCapabilityWithPropertiesFromYmlFailed
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importNodeTypeWithCapabilityWithPropertiesFromYmlFailed() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ RestResponse createResource = importUserDefinedNodeType("mycompute_failed.yml", sdncModifierDetails,
+ resourceDetails);
+ BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS);
+ }
+
+ /**
+ * Capability Assignment (on node_template / resource instance) - should
+ * support assignment of the property (property value). On the resource
+ * instance level, value can be assigned to either properties that are
+ * defined on the capability type or on the capability definition. When
+ * importing a VF - the node_template can have capability's property value.
+ * It should be imported and saved on the graph Acceptance Criteria: import
+ * a VF that assign values to property of capability that was defined on the
+ * capability type
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesSucceed() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "vf_with_cap_prop_override_cap_type_prop.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ List<ImmutablePair<String, String>> propertyNamesValues = new ArrayList<>();
+ propertyNamesValues.add(new ImmutablePair<String, String>("num_cpus", "2"));
+ propertyNamesValues.add(new ImmutablePair<String, String>("mem_size", "2000 MB"));
+ checkResource(createResource, 8, container, "DBMS", propertyNamesValues);
+
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+ resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop.csar");
+ resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ checkResource(createResource, 8, container, "DBMS", propertyNamesValues);
+ }
+
+ /**
+ * importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesFailed
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importResourceWithCapabilityWithPropertiesOverridingCapTypePropertiesFailed() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String payloadName = "vf_with_cap_prop_override_cap_type_prop_failed.csar";
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ Path path = Paths
+ .get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop_failed.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.INVALID_PROPERTY);
+
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+ resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop_failed.csar");
+ resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+ BaseRestUtils.checkErrorMessageResponse(createResource, ActionStatus.INVALID_PROPERTY);
+
+ }
+
+ /**
+ * Capability Assignment (on node_template / resource instance) - should
+ * support assignment of the property (property value). On the resource
+ * instance level, value can be assigned to either properties that are
+ * defined on the capability type or on the capability definition. When
+ * importing a VF - the node_template can have capability's property value.
+ * It should be imported and saved on the graph Acceptance Criteria: import
+ * a VF that assign values to property of capability that was defined on the
+ * capability definition (on the node type)
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesSucceed() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails,
+ resourceDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource userDefinedNodeType = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(),
+ Resource.class);
+
+ String payloadName = "vf_with_cap_prop_override_cap_type_prop1.csar";
+ resourceDetails = ElementFactory.getDefaultImportResource();
+ Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ List<ImmutablePair<String, String>> propertyNamesValues = new ArrayList<>();
+ propertyNamesValues.add(new ImmutablePair<String, String>("num_cpus", "2"));
+ propertyNamesValues.add(new ImmutablePair<String, String>("mem_size", "2000 MB"));
+ checkResource(createResource, 8, container, "DBMS", propertyNamesValues);
+
+ List<ImmutablePair<String, String>> propertyNamesValues1 = new ArrayList<>();
+ propertyNamesValues1.add(new ImmutablePair<String, String>(propertyForTestName, "success_again"));
+ propertyNamesValues1.add(new ImmutablePair<String, String>(minInstances, "4"));
+ checkResource(createResource, 8, scalable, userDefinedNodeType.getName(), propertyNamesValues1);
+
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+ resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop1.csar");
+ resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ checkResource(createResource, 8, container, "DBMS", propertyNamesValues);
+ checkResource(createResource, 8, scalable, userDefinedNodeType.getName(), propertyNamesValues1);
+
+ }
+
+ /**
+ * importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesFailed
+ *
+ * @throws Exception
+ */
+ @Test
+ public void importResourceWithCapabilityWithPropertiesOverridingNodeTypeCapPropertiesFailed() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ RestResponse createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails,
+ resourceDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+
+ String payloadName = "vf_with_cap_prop_override_cap_type_prop1_failed.csar";
+ resourceDetails = ElementFactory.getDefaultImportResource();
+ Path path = Paths
+ .get(rootPath + "/src/test/resources/CI/csars/vf_with_cap_prop_override_cap_type_prop1_failed.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
+ propertyForTestName);
+
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+ resourceDetails2.setCsarUUID("vf_with_cap_prop_override_cap_type_prop1_failed.csar");
+ resourceDetails2.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+ BaseRestUtils.checkErrorResponse(createResource, ActionStatus.PROPERTY_NAME_ALREADY_EXISTS,
+ propertyForTestName);
+ }
+
+ private RestResponse importUserDefinedNodeType(String payloadName, User sdncModifierDetails,
+ ImportReqDetails resourceDetails) throws Exception {
+
+ Path path = Paths.get(rootPath + "/src/test/resources/CI/csars/" + payloadName);
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VFC.name());
+ return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ }
+
+ // TODO Tal: Since Cashing change partial resource returned that causes null
+ // pointer exception
+ // commented out till fixing
+ private void checkResource(RestResponse createResource, int capNum, String capType, String riName,
+ List<ImmutablePair<String, String>> propertyNamesValues) {
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ Map<String, List<CapabilityDefinition>> capabilities = resource.getCapabilities();
+ // TODO Tal: Since Cashing change partial resource returned that causes
+ // null pointer exception
+ /* assertEquals(capabilities.size(), capNum); */
+ /*
+ * List<CapabilityDefinition> capabilitesContainer =
+ * capabilities.get(capType);
+ */
+
+ ComponentInstance resourceRI = resource.getComponentInstances().stream()
+ .filter(ri -> ri.getComponentName().equals(riName)).collect(Collectors.toList()).get(0);
+ // TODO Tal: Since Cashing change partial resource returned that causes
+ // null pointer exception
+ /*
+ * CapabilityDefinition capabilityFromContainer =
+ * capabilitesContainer.stream()
+ * .filter(cap->cap.getOwnerId().equals(resourceRI.getUniqueId())).
+ * collect(Collectors.toList()).get(0);
+ */
+
+ CapabilityDefinition capabilityFromRI = resourceRI.getCapabilities().get(capType).get(0);
+ for (ImmutablePair<String, String> propValuePair : propertyNamesValues) {
+ // TODO Tal: Since Cashing change partial resource returned that
+ // causes null pointer exception
+ /*
+ * Map<String, ComponentInstanceProperty> propertiesFromContainer =
+ * capabilityFromContainer.getProperties()
+ * .stream().filter(p->p.getName().equalsIgnoreCase(propValuePair.
+ * getLeft())) .collect(Collectors.toMap(p->p.getName(), p->p));
+ */
+
+ List<ComponentInstanceProperty> propertiesFromRI = capabilityFromRI.getProperties().stream()
+ .filter(p -> p.getName().equalsIgnoreCase(propValuePair.getLeft())).collect(Collectors.toList());
+ // TODO Tal: Since Cashing change partial resource returned that
+ // causes null pointer exception
+ /*
+ * for(ComponentInstanceProperty riProp : propertiesFromRI){
+ * assertTrue(propertiesFromContainer.containsKey(riProp.getName()))
+ * ; ComponentInstanceProperty containerProp =
+ * propertiesFromContainer.get(riProp.getName());
+ * assertEquals(riProp.getValue(), containerProp.getValue());
+ * if(riProp.getName().equals(propValuePair.getLeft()))
+ * assertEquals(riProp.getValue(), propValuePair.getRight());
+ *
+ * }
+ */
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
new file mode 100644
index 0000000000..b78bf3de36
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportToscaResourceTest.java
@@ -0,0 +1,2404 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.http.client.ClientProtocolException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.AttributeDefinition;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.ImportUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ToscaNodeTypeInfo;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+/**
+ *
+ * @author Andrey + Pavel + Shay
+ *
+ */
+
+public class ImportToscaResourceTest extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(ImportToscaResourceTest.class.getName());
+ protected Utils utils = new Utils();
+
+ public ImportToscaResourceTest() {
+ super(name, ImportToscaResourceTest.class.getName());
+ }
+
+ public ImportReqDetails importReqDetails;
+ protected static User sdncUserDetails;
+ protected static User testerUser;
+ protected String testResourcesPath;
+ protected ResourceReqDetails resourceDetails;
+ private HashSet<String> capabilitySources;
+ private int actualNumOfReqOrCap;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ @BeforeMethod
+ public void before() throws Exception {
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ resourceDetails = ElementFactory.getDefaultResource();
+ String sourceDir = config.getResourceConfigDir();
+ final String workDir = "importToscaResourceByCreateUrl";
+ testResourcesPath = sourceDir + File.separator + workDir;
+ capabilitySources = new HashSet<String>();
+ actualNumOfReqOrCap = 0;
+ }
+
+ @DataProvider
+ private static final Object[][] getYmlWithInValidListProperties() throws IOException, Exception {
+ return new Object[][] { { "ListPropertyFalure02.yml", "[false,\"truee\"]", "boolean" }, { "ListPropertyFalure03.yml", "[false,3]", "boolean" }, { "ListPropertyFalure04.yml", "[false,3.56]", "boolean" },
+ { "ListPropertyFalure05.yml", "[10000,3.56]", "integer" }, { "ListPropertyFalure06.yml", "[10000,\"aaaa\"]", "integer" }, { "ListPropertyFalure07.yml", "[10000,true]", "integer" },
+ { "ListPropertyFalure08.yml", "[10.5,true]", "float" }, { "ListPropertyFalure09.yml", "[10.5,\"asdc\"]", "float" }, // type
+ // float
+ { "ListPropertyFalure11.yml", "[10.5,\"500.0@\"]", "float" }, // property
+ // list
+ // float
+ // type
+ // contain
+ // @
+ // in
+ // default
+ // value
+ { "ListPropertyFalure12.yml", "[10000,\"3#\"]", "integer" }, // property
+ // list
+ // integer
+ // type
+ // contain
+ // #
+ // in
+ // default
+ // value
+ { "ListPropertyFalure13.yml", "[false,\"true%\"]", "boolean" }, // property
+ // list
+ // boolean
+ // type
+ // contain
+ // %
+ // in
+ // default
+ // value
+ { "ListPropertyFalure14.yml", "[false,\"falsee\",true]", "boolean" }, { "ListPropertyFalure15.yml", "[10.5,\"10.6x\",20.5,30.5]", "float" } // float
+ // with
+ // value
+ // 10.6x
+ // instead
+ // 10.6f
+
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] getYmlWithInValidMapProperties() throws IOException, Exception {
+ return new Object[][] { { "MapPropertyFalure02.yml", "[false,\"truee\"]", "boolean" }, { "MapPropertyFalure03.yml", "[false,3]", "boolean" }, { "MapPropertyFalure04.yml", "[false,3.56]", "boolean" },
+ { "MapPropertyFalure05.yml", "[10000,3.56]", "integer" }, { "MapPropertyFalure06.yml", "[10000,\"aaaa\"]", "integer" }, { "MapPropertyFalure07.yml", "[10000,true]", "integer" }, { "MapPropertyFalure08.yml", "[10.5,true]", "float" },
+ { "MapPropertyFalure09.yml", "[10.5,\"asdc\"]", "float" }, // type
+ // float
+ { "MapPropertyFalure11.yml", "[10.5,\"500.0@\"]", "float" }, // property
+ // list
+ // float
+ // type
+ // contain
+ // @
+ // in
+ // default
+ // value
+ { "MapPropertyFalure12.yml", "[10000,\"3#\"]", "integer" }, // property
+ // list
+ // integer
+ // type
+ // contain
+ // #
+ // in
+ // default
+ // value
+ { "MapPropertyFalure13.yml", "[false,\"true%\"]", "boolean" }, // property
+ // list
+ // boolean
+ // type
+ // contain
+ // %
+ // in
+ // default
+ // value
+ { "MapPropertyFalure14.yml", "[false,\"falsee\",true]", "boolean" }, { "MapPropertyFalure15.yml", "[10.5,\"10.6x\",20.5,30.5]", "float" } // float
+ // with
+ // value
+ // 10.6x
+ // instead
+ // 10.6f
+
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] getYmlWithInValidOccurrences() throws IOException, Exception {
+ return new Object[][] { { "occurencyFalure01.yml" }, // requirements [2
+ // , 0]
+ { "occurencyFalure02.yml" }, // requirements [-1, 2]
+ { "occurencyFalure03.yml" }, // requirements [1 ,-2]
+ { "occurencyFalure05.yml" }, // requirements MAX occurrences not
+ // exist [ 1 , ]
+ { "occurencyFalure06.yml" }, // requirements [ 0 , 0 ]
+ { "occurencyFalure08.yml" }, // requirements [ 1.0 , 2.0 ]
+ { "occurencyFalure09.yml" }, // requirements [ "1" , "2" ]
+ { "occurencyFalure10.yml" }, // requirements [ ]
+ { "occurencyFalure11.yml" }, // requirements [ UNBOUNDED ,
+ // UNBOUNDED ]
+ { "occurencyFalure31.yml" }, // capability [ 2, 1]
+ { "occurencyFalure32.yml" }, // capability [-1, 2]
+ { "occurencyFalure33.yml" }, // capability [1, -2]
+ { "occurencyFalure35.yml" }, // capability MAX occurrences not
+ // exist [ 1 , ]
+ { "occurencyFalure36.yml" }, // capability [ 0 , 0 ]
+ { "occurencyFalure38.yml" }, // capability [ 1.0 , 2.0 ]
+ { "occurencyFalure39.yml" }, // capability [ "1" , "2" ]
+ { "occurencyFalure40.yml" }, // capability [ ]
+ { "occurencyFalure41.yml" } // capability [ UNBOUNDED ,
+ // UNBOUNDED ]
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] getInvalidYmlWithOccurrences() throws IOException, Exception {
+ return new Object[][] { { "occurencyFalure04.yml" }, // requirements MIN
+ // occurrences
+ // not exist [ ,
+ // 1]
+ { "occurencyFalure07.yml" }, // requirements [ @ , 1 ]
+ { "occurencyFalure34.yml" }, // capability MIN occurrences not
+ // exist [ , 1]
+ { "occurencyFalure37.yml" } // capability [ 0 , # ]
+
+ };
+ }
+
+ // US656928
+ protected final String importMapPropertySuccess = "importMapPropertySuccessFlow.yml";
+ protected final String importAttributeSuccess = "importAttributeSuccessFlow.yml";
+ protected final String importSuccessFile = "myCompute.yml";
+ protected final String derivedFromMyCompute = "derivedFromMyCompute.yml";
+ protected final String importSuccessVFFile = "myComputeVF.yml";
+ protected final String importNoDerivedFromFile = "myComputeDerivedFromNotExists.yml";
+ protected final String importInvalidDefinitionVersionFile = "myComputeIncorrectDefenitionVersionValue.yml";
+ protected final String importIncorrectNameSpaceFormatFile = "myComputeIncorrectNameSpaceFormat.yml";
+ protected final String importNoDefenitionVersionFile = "myComputeNoDefenitionVersion.yml";
+ protected final String importNodeTypesTwiceFile = "myComputeWithNodeTypesTwice.yml";
+ protected final String importTopologyTemplateFile = "myComputeWithTopologyTemplate.yml";
+ protected final String importNoContentFile = "noContent.yml";
+ protected final String importWithOccurrences = "myComputeOccurencySuccess.yml";
+ protected final String importListPropertyBadDefault = "importListPropertyBadDefault.yml";
+ protected final String importListPropertyGoodDefault = "importListPropertyGoodDefault.yml";
+ protected final String importListPropertySuccess = "importListPropertySuccessFlow.yml";
+ // US631462
+ protected final String importDuplicateRequirements = "importDuplicateRequirements.yml";
+ protected final String importDuplicateCapability = "importDuplicateCapability.yml";
+ protected final String importCapabilityNameExistsOnParent = "importCapabilityNameExistsOnParent.yml";
+ protected final String importRequirementNameExistsOnParent = "importRequirementNameExistsOnParent.yml";
+ protected final String importToscaResourceReqCapDerivedFromParent = "derivedFromWebAppDerivedReqCap.yml";
+ protected final String missingCapInReqDef = "missingCapInReqDefinition.yml";
+ protected final String missingCapInCapDef = "missingCapInCapDefinition.yml";
+
+ // US558432 - Support for Capability/Requirement "occurences" Import
+ @Test(dataProvider = "getYmlWithInValidOccurrences")
+ public void importToscaResourceWithOccurrencesFailuresFlow01(String ymlFileWithInvalidCapReqOccurrences) throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFileWithInvalidCapReqOccurrences);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_OCCURRENCES.name(), new ArrayList<String>(), importResourceResponse.getResponse());
+ }
+
+ @Test(dataProvider = "getInvalidYmlWithOccurrences")
+ public void importToscaResourceWithOccurrencesFailuresFlow02(String ymlFileWithInvalidCapReqOccurrences) throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFileWithInvalidCapReqOccurrences);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_YAML_FILE.name(), new ArrayList<String>(), importResourceResponse.getResponse());
+ }
+
+ @Test
+ public void importToscaResource() throws Exception {
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ AssertJUnit.assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ AssertJUnit.assertTrue("validate toscaResourceName field", resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName()));
+ AssertJUnit.assertTrue("validate resourceType field", resourceJavaObject.getResourceType().equals(ResourceTypeEnum.VFC));
+ // find derived from resource details
+ // Validate resource details after import-create resource including
+ // capabilities, interfaces from derived_from resource
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceWithOccurrencesSuccessFlow() throws Exception {
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importWithOccurrences);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ AssertJUnit.assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ AssertJUnit.assertTrue("validate toscaResourceName field", resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName()));
+ AssertJUnit.assertTrue("validate resourceType field", resourceJavaObject.getResourceType().equals(ResourceTypeEnum.VFC));
+ String requirementsType = "tosca.capabilities.Attachment";
+ String capabilitType = "tosca.capabilities.Endpoint.Admin";
+ // Verify Occurrences of requirements and capabilities in resource
+ verifyRequirementsOccurrences(resourceJavaObject, requirementsType);
+ verifyCapabilitiesOccurrences(resourceJavaObject, capabilitType);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ // ------------------------------Success---------------------------------
+
+ @Test(enabled = false)
+ public void importToscaResourceVFResType() throws Exception {
+
+ String resourceType = ResourceTypeEnum.VF.toString();
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessVFFile);
+ // importReqDetails.setResourceType(resourceType);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ assertTrue("validate toscaResourceName field", resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName()));
+ assertTrue("validate resourceType field, expected - " + resourceType + ", actual - " + resourceJavaObject.getResourceType(), resourceJavaObject.getResourceType().toString().equals(resourceType));
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ // ------------------------------Failure---------------------------------
+
+ @Test
+ public void importToscaResourceDerivedFromNotExist() throws Exception {
+
+ String fileName = importNoDerivedFromFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ // List<String> derivedFrom = new ArrayList<String>() ;
+ // derivedFrom.add("hh");
+ // importReqDetails.setDerivedFrom(derivedFrom);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.PARENT_RESOURCE_NOT_FOUND.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PARENT_RESOURCE_NOT_FOUND.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceIncorrectDefinitionVersion() throws Exception {
+
+ String fileName = importInvalidDefinitionVersionFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_TOSCA_TEMPLATE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceIncorrectSpaceNameFormat() throws Exception {
+
+ String fileName = importIncorrectNameSpaceFormatFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_NAMESPACE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_NAMESPACE.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceNoDefinitionVersion() throws Exception {
+
+ String fileName = importNoDefenitionVersionFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_TOSCA_TEMPLATE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceNoContent() throws Exception {
+
+ String fileName = importNoContentFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_PAYLOAD.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_PAYLOAD.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceWithTopologyTemplate() throws Exception {
+
+ String fileName = importTopologyTemplateFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_RESOURCE_TOSCA_TEMPLATE.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceWithNodeTypesTwice() throws Exception {
+
+ String fileName = importNodeTypesTwiceFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_SINGLE_RESOURCE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_SINGLE_RESOURCE.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ // failed case - uniqueness of toscaResourceName - RESOURCE_ALREADY_EXISTS
+ @Test
+ public void importToscaResourceTwice() throws Exception {
+ String fileName = importSuccessFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ RestResponse checkInresponse = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKIN);
+ assertTrue("checkIn resource request returned status:" + checkInresponse.getErrorCode(), checkInresponse.getErrorCode() == 200);
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+
+ // import the same tosca resource with different resourceName
+ DbUtils.cleanAllAudits();
+
+ importReqDetails.setName("kuku");
+ List<String> tags = new ArrayList<String>();
+ tags.add(importReqDetails.getName());
+ importReqDetails.setTags(tags);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_ALREADY_EXISTS.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name(), variables, importResourceResponse.getResponse());
+
+ expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(importReqDetails.getToscaResourceName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+
+ }
+
+ @Test
+ public void importToscaResourceWithTheSameNameAsCreatedResourceBefore() throws Exception {
+
+ // create resource
+ String fileName = importSuccessFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName(importReqDetails.getName());
+
+ RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ int status = response.getErrorCode();
+ assertEquals("create request returned status:" + status, 201, status);
+ assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId());
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ // assertNull("validate toscaResourceName field",
+ // resourceJavaObject.getToscaResourceName());
+
+ // import the same tosca resource
+ DbUtils.cleanAllAudits();
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESOURCE_ALREADY_EXISTS.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+
+ }
+
+ @Test
+ public void importToscaResourceInvalidChecksum() throws Exception {
+ String fileName = importSuccessFile;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), "invalidMd5Sum");
+
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, headersMap);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ assertNotNull("check response object is not null after import tosca resource", importResourceResponse);
+ assertNotNull("check error code exists in response after import tosca resource", importResourceResponse.getErrorCode());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_RESOURCE_CHECKSUM.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_RESOURCE_CHECKSUM.name(), variables, importResourceResponse.getResponse());
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceInvalidResType() throws Exception {
+
+ String resourceType = "invalidResourceType";
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessFile);
+ importReqDetails.setResourceType(resourceType);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+ assertNotNull("check response object is not null after import resouce", importResourceResponse);
+ assertNotNull("check error code exists in response after import resource", importResourceResponse.getErrorCode());
+ assertEquals("Check response code after import resource", errorInfo.getCode(), importResourceResponse.getErrorCode());
+
+ List<String> variables = new ArrayList<>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, importResourceResponse.getResponse());
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void derivedTemplateImportedSecondResourceAsFirstImportedNodeType() throws Exception {
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importSuccessFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+ assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ assertTrue("validate toscaResourceName field", resourceJavaObject.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName()));
+ assertTrue("validate resourceType field, expected - " + importReqDetails.getResourceType() + ", actual - " + resourceJavaObject.getResourceType(), resourceJavaObject.getResourceType().toString().equals(importReqDetails.getResourceType()));
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+
+ RestResponse certifyResource = LifecycleRestUtils.certifyResource(importReqDetails);
+ assertTrue("certify resource request returned status:" + certifyResource.getErrorCode(), certifyResource.getErrorCode() == 200);
+
+ // import second resource template derived from first resource
+ DbUtils.cleanAllAudits();
+ importReqDetails.setName("kuku");
+ List<String> tags = new ArrayList<String>();
+ tags.add(importReqDetails.getName());
+ importReqDetails.setTags(tags);
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, derivedFromMyCompute);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+ parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ Resource resourceJavaObject2 = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ assertTrue("validate toscaResourceName field", resourceJavaObject2.getToscaResourceName().equals(parseToscaNodeYaml.getNodeName()));
+ assertTrue("validate resourceType field, expected - " + importReqDetails.getResourceType() + ", actual - " + resourceJavaObject2.getResourceType(), resourceJavaObject2.getResourceType().toString().equals(importReqDetails.getResourceType()));
+
+ // Validate audit message
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject2 = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject2.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject2.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject2.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject2.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject2, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+
+ }
+
+ @Test
+ public void importToscaResourceListPropertyGoodDefault() throws Exception {
+
+ String fileName = importListPropertyGoodDefault;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ assertTrue("response code is not 201, returned :" + importResourceResponse.getErrorCode(), importResourceResponse.getErrorCode() == 201);
+
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ assertTrue("Properties size : " + resourceJavaObject.getProperties().size(), resourceJavaObject.getProperties().size() == 1);
+ assertTrue("Property type : " + resourceJavaObject.getProperties().get(0).getType(), resourceJavaObject.getProperties().get(0).getType().equals(ToscaPropertyType.LIST.getType()));
+ assertTrue("actual Default values : " + resourceJavaObject.getProperties().get(0).getDefaultValue() + " , expected : " + "[false, true]", resourceJavaObject.getProperties().get(0).getDefaultValue().equals("[\"false\",\"true\"]"));
+
+ }
+
+ @Test
+ public void importToscaResourceListPropertyBadDefault() throws Exception {
+
+ String fileName = importListPropertyBadDefault;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name());
+ assertEquals("Check response code after tosca resource import", errorInfo.getCode(), importResourceResponse.getErrorCode());
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("my_prop");
+ variables.add("list");
+ variables.add("boolean");
+ variables.add("[12,true]");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, importResourceResponse.getResponse());
+
+ }
+
+ // Benny US580744 - Add support for TOSCA "list" type - import
+
+ @Test
+ public void importToscaResourceListPropertySuccessFlow() throws Exception {
+ String fileName = importListPropertySuccess;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ ResourceRestUtils.checkCreateResponse(importResourceResponse);
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ // Verify Properties List in resource
+ verifyResourcePropertiesList(resourceJavaObject);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ // DE198534
+ @Test(dataProvider = "getYmlWithInValidListProperties") // invalid default
+ // values
+ public void importToscaResourceListPropertyFailureFlows(String ymlFileWithInvalidPropertyDefualtValues, String defualtValues, String enterySchemaType) throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFileWithInvalidPropertyDefualtValues);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("my_property");
+ variables.add("list");
+ variables.add(enterySchemaType);
+ variables.add(defualtValues);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, importResourceResponse.getResponse());
+ }
+
+ // BUG DE198650
+ @Test
+ public void importToscaResourceListPropertyNonSupportEntrySchemaType() throws Exception {
+ String ymlFile = "ListPropertyFalure01.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("booolean"); // property entry_schema data type
+ variables.add("my_boolean");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables, importResourceResponse.getResponse());
+ }
+
+ // BUG DE198676
+ @Test // (enabled=false)
+ public void importToscaResourceListPropertyNonSupportedPropertyType() throws Exception { // Not
+ // "list"
+ // type
+ String ymlFile = "ListPropertyFalure16.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("koko"); // property data type (koko instead list)
+ variables.add("my_boolean");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, importResourceResponse.getResponse());
+ }
+
+ /// US656928 - [BE] - Add support for TOSCA "map" type - Phase 1 import
+ @Test
+ public void importToscaResourceMapPropertySuccessFlow() throws Exception {
+ String fileName = importMapPropertySuccess;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ ResourceRestUtils.checkCreateResponse(importResourceResponse);
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+ // Verify Properties MAP in resource
+ verifyResourcePropertiesMap(resourceJavaObject);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test(dataProvider = "getYmlWithInValidMapProperties") // invalid default
+ // values
+ public void importToscaResourceMapPropertyFailureFlows(String ymlFileWithInvalidPropertyDefualtValues, String defualtValues, String enterySchemaType) throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFileWithInvalidPropertyDefualtValues);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("my_property");
+ variables.add("map");
+ variables.add(enterySchemaType);
+ variables.add(defualtValues);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables, importResourceResponse.getResponse());
+ }
+
+ @Test
+ public void importToscaResourceMaptPropertyNonSupportedPropertyType() throws Exception { // Not
+ // "Map"
+ // type
+ String ymlFile = "MapPropertyFalure16.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, ymlFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("koko"); // property data type (koko instead list)
+ variables.add("my_boolean");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables, importResourceResponse.getResponse());
+ }
+
+ @Test
+ public void importToscaResourceMissingCapabilityInReqDefinition() throws Exception {
+
+ String fileName = missingCapInReqDef;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_CAPABILITY_TYPE.name());
+ String missingCapName = "org.openecomp.capabilities.networkInterfaceNotFound";
+ BaseRestUtils.checkErrorResponse(importResourceResponse, ActionStatus.MISSING_CAPABILITY_TYPE, missingCapName);
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, Arrays.asList(missingCapName));
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.vSCP-03-16");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceMissingCapabilityInCapDefinition() throws Exception {
+
+ String fileName = missingCapInCapDef;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ logger.debug("import tosca resource response: {}", importResourceResponse.getResponseMessage());
+
+ // Validate audit message
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_CAPABILITY_TYPE.name());
+ String missingCapName = "org.openecomp.capabilities.networkInterfaceNotFound";
+ BaseRestUtils.checkErrorResponse(importResourceResponse, ActionStatus.MISSING_CAPABILITY_TYPE, missingCapName);
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, Arrays.asList(missingCapName));
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.vSCP-03-16");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceDuplicateRequirements() throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importDuplicateRequirements);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("requirement");
+ variables.add("local_storage");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name(), variables, importResourceResponse.getResponse());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceDuplicateCapabilities() throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importDuplicateCapability);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("capability");
+ variables.add("scalable");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name(), variables, importResourceResponse.getResponse());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceRequirementNameExistsOnParent() throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importRequirementNameExistsOnParent);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("requirement");
+ variables.add("local_storage");
+ variables.add("Compute");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), variables, importResourceResponse.getResponse());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceCapabilityNameExistsOnParent() throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importCapabilityNameExistsOnParent);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertTrue(importResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("capability");
+ variables.add("binding");
+ variables.add("Compute");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), variables, importResourceResponse.getResponse());
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgFailure(errorInfo, variables);
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ @Test
+ public void importToscaResourceReqCapDerivedFromParent() throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, importToscaResourceReqCapDerivedFromParent);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ BaseRestUtils.checkCreateResponse(importResourceResponse);
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType("org.openecomp.resource.MyWebApp");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ /************************ Shay ************************/
+
+ @Test
+ public void caseRequirementInsensitiveTest() throws Exception {
+ String fileName = "CaseInsensitiveReqTest_1.yml";
+ int expectedNumOfRequirements = 2;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+ importReqDetails.setRequirements(testResourcesPath, fileName, sdncUserDetails, null);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String fileName2 = "CaseInsensitiveReqTest_2.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName2);
+ importReqDetails.setName("secondImportedResource");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, null);
+ requirements = importReqDetails.getRequirements();
+ requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ checkImportedAssetAssociated(importReqDetails);
+
+ }
+
+ private void checkImportedAssetAssociated(ImportReqDetails importDetails) throws IOException, Exception {
+ RestResponse importResourceResponse;
+ ImportReqDetails importReqDetails2 = ElementFactory.getDefaultImportResource();
+ importReqDetails2 = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails2, testResourcesPath, "BindingAsset.yml");
+ importReqDetails2.setName("bindingAsset");
+ importReqDetails2.setTags(Arrays.asList(importReqDetails2.getName()));
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails2, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ ResourceReqDetails vf = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncUserDetails.getUserId(), ResourceTypeEnum.VF.toString());
+ RestResponse createResourceResponse = ResourceRestUtils.createResource(vf, sdncUserDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceResponse);
+
+ LifecycleRestUtils.changeResourceState(importDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ LifecycleRestUtils.changeResourceState(importReqDetails2, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ RestResponse response = ResourceRestUtils.createResourceInstance(importDetails, sdncUserDetails, vf.getUniqueId());
+ ResourceRestUtils.checkCreateResponse(response);
+ ComponentInstance riCap = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
+
+ response = ResourceRestUtils.createResourceInstance(importReqDetails2, sdncUserDetails, vf.getUniqueId());
+ ResourceRestUtils.checkCreateResponse(response);
+ ComponentInstance riReq = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
+
+ RestResponse getResourceBeforeAssociate = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncUserDetails, vf);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class);
+
+ String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.network.Bindable").get(0).getUniqueId();
+ String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.network.Bindable").get(0).getUniqueId();
+
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(riReq.getUniqueId());
+ requirementDef.setToNode(riCap.getUniqueId());
+
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(riReq.getUniqueId());
+ pair.setCapabilityOwnerId(riCap.getUniqueId());
+ pair.setRequirement("VirtualBinding");
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("tosca.capabilities.network.Bindable");
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capbilityUid);
+ pair.setRequirementUid(requirementUid);
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncUserDetails, vf.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ }
+
+ @Test
+ public void caseCapabilitiesInsensitiveTest() throws Exception {
+ String fileName = "CaseInsensitiveCapTest_1.yml";
+ int expectedNumOfCapabilities = 6;
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setCapabilities(testResourcesPath, fileName, sdncUserDetails, null);
+ Map<String, Object> capabilities = importReqDetails.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String fileName2 = "CaseInsensitiveCapTest_2.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName2);
+ importReqDetails.setName("secondImportedResource");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setCapabilities(testResourcesPath, fileName2, sdncUserDetails, null);
+ capabilities = importReqDetails.getCapabilities();
+ capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+
+ }
+
+ @Test
+ public void fatherAndChildHaveDifferentRequirementsTest() throws Exception {
+ String fileName = "DifferentReqFromCompute.yml";
+ int expectedNumOfRequirements = 3;
+
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, fileName, sdncUserDetails, "Compute");
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ checkImportedAssetAssociated(importReqDetails);
+ }
+
+ @Test
+ public void fatherHasNoRequirementsTest() throws Exception {
+ String fatherFileName = "CPHasNoReqCap.yml";
+ String childFileName = "DerivedFromCPWithOwnReq.yml";
+ int expectedNumOfRequirements = 3;
+
+ importReqDetails.setName("father");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String derivedFromResourceName = importReqDetails.getName();
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromResourceName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ }
+
+ @Test
+ public void childHasSameReqNameAndTypeLikeFatherTest() throws Exception {
+ String childFileName = "SameReqAsCompute.yml";
+ int expectedNumOfRequirements = 2;
+
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, null);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+ }
+
+ @Test
+ public void childHasSameCapNameAndTypeLikeFatherTest() throws Exception {
+ String childFileName = "SameCapAsCompute.yml";
+ int expectedNumOfCapabilities = 6;
+
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, "Compute");
+ Map<String, Object> capabilities = importReqDetails.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+ }
+
+ @Test
+ public void childGetsAllRequirementsOfFatherAndGrandfatherTest() throws Exception {
+ int expectedNumOfRequirements = 4;
+
+ String fatherFileName = "DifferentReqFromCompute.yml";
+ importReqDetails.setName("father");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String derivedFromName = importReqDetails.getName();
+ String childFileName = "DifferentReqCapFromCompute1.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ }
+
+ @Test
+ public void childOverridesGrandfatherRequirementsTest() throws Exception {
+ int expectedNumOfRequirements = 3;
+
+ String fatherFileName = "DifferentReqFromCompute.yml";
+ importReqDetails.setName("father");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String derivedFromName = importReqDetails.getName();
+ String childFileName = "SameReqAsCompute_DerivedFromMyCompute1.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+ }
+
+ @Test
+ public void childAndGrandfatherHaveDifferenetReqiurementTypeTest() throws Exception {
+ int expectedNumOfRequirements = 3;
+ int expectedNumOfCapabilities = 6;
+
+ String fatherName = "father";
+ String fatherFileName = "DifferentReqFromCompute.yml";
+ importReqDetails.setName(fatherName);
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String fatherUniqueId = importReqDetails.getUniqueId();
+ ImportReqDetails importReqDetailsFather = importReqDetails;
+
+ String childFileName = "importRequirementNameExistsOnParent_DerivedFromMyCompute1.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("requirement");
+ variables.add("local_storage");
+ variables.add(fatherName);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), variables, importResourceResponse.getResponse());
+
+ importReqDetails.setUniqueId(fatherUniqueId);
+
+ importReqDetailsFather.setRequirements(testResourcesPath, fatherFileName, sdncUserDetails, "Compute");
+ Map<String, Object> requirements = importReqDetailsFather.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Compute");
+ Map<String, Object> capabilities = importReqDetailsFather.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+ }
+
+ @Test
+ public void childHasNoReqCapTest() throws Exception {
+ int expectedNumOfRequirements = 3;
+ int expectedNumOfCapabilities = 6;
+
+ String fatherFileName = "DifferentReqFromCompute.yml";
+ importReqDetails.setName("father");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String derivedFromName = importReqDetails.getName();
+ String childFileName = "CPHasNoReqCap_DerivedFromMyCompute1.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> capabilities = importReqDetails.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+ }
+
+ @Test
+ public void fatherAndChildGetReqCapFromGrandfatherTest() throws Exception {
+ int expectedNumOfRequirements = 2;
+ int expectedNumOfCapabilities = 6;
+
+ String fatherFileName = "MyFatherCompute_NoReqCap.yml";
+ importReqDetails.setName("father");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String derivedFromName = importReqDetails.getName();
+ String childFileName = "myChildCompute_NoReqCap.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> capabilities = importReqDetails.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+ }
+
+ @Test
+ public void reverseInheritanceTest() throws Exception {
+ int expectedNumOfRequirements = 2;
+ int expectedNumOfCapabilities = 2;
+
+ String fatherName = "father";
+ String fatherFileName = "myFatherWebApp_derviedFromDocker.yml";
+ importReqDetails.setName(fatherName);
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String fatherUniqueId = importReqDetails.getUniqueId();
+ ImportReqDetails importReqDetailsFather = importReqDetails;
+ String childFileName = "myChildWebApp_DerivedFromContainer.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("requirement");
+ variables.add("host");
+ variables.add(fatherName);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED.name(), variables, importResourceResponse.getResponse());
+
+ importReqDetails.setUniqueId(fatherUniqueId);
+ importReqDetailsFather.setRequirements(testResourcesPath, fatherFileName, sdncUserDetails, "Root");
+ Map<String, Object> requirements = importReqDetailsFather.getRequirements();
+ Map<String, Object> requirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetailsFather, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), requirementsFromResponse.keySet().size());
+ importReqDetailsFather.compareRequirementsOrCapabilities(requirements, requirementsFromResponse);
+
+ importReqDetailsFather.setCapabilities(testResourcesPath, fatherFileName, sdncUserDetails, "Root");
+ Map<String, Object> capabilities = importReqDetailsFather.getCapabilities();
+ Map<String, Object> capabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetailsFather, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), capabilitiesFromResponse.keySet().size());
+ importReqDetailsFather.compareRequirementsOrCapabilities(capabilities, capabilitiesFromResponse);
+ }
+
+ // DE202329
+ @Test(enabled = false)
+ public void requirementWithMissingTypeTest() throws Exception {
+ String fatherName = "father";
+ String fatherFileName = "DerivedFromWebApplication_HasNoReqType.yml";
+ importReqDetails.setName(fatherName);
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_INVALID_CONTENT, importResourceResponse.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("diff");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_CAPABILITY_TYPE.name(), variables, importResourceResponse.getResponse());
+
+ }
+
+ @Test
+ public void TwinBrothersHaveSameReqCapTest() throws Exception {
+ int expectedNumOfRequirements = 4;
+ int expectedNumOfCapabilities = 7;
+
+ String derivedFromName = "father";
+ String fatherFileName = "DifferentReqFromCompute.yml";
+ importReqDetails.setName(derivedFromName);
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fatherFileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ RestResponse changeResourceState1 = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState1.getErrorCode().intValue());
+ RestResponse changeResourceState2 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState2.getErrorCode().intValue());
+ RestResponse changeResourceState3 = LifecycleRestUtils.changeResourceState(importReqDetails, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState3.getErrorCode().intValue());
+
+ String childFileName = "DifferentReqCapFromCompute1.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("child");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, childFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ Map<String, Object> childRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ Map<String, Object> childCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities - 1);
+
+ String twinFileName = "DifferentReqCapFromCompute2.yml";
+ importReqDetails = ElementFactory.getDefaultImportResource();
+ importReqDetails.setName("twin");
+ importReqDetails.setTags(Arrays.asList(importReqDetails.getName()));
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, twinFileName);
+ importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+
+ importReqDetails.setRequirements(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> requirements = importReqDetails.getRequirements();
+ Map<String, Object> twinRequirementsFromResponse = parseReqOrCapFromResponse("requirements", importReqDetails, expectedNumOfRequirements);
+ assertEquals(requirements.keySet().size(), twinRequirementsFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(requirements, twinRequirementsFromResponse);
+
+ importReqDetails.setCapabilities(testResourcesPath, importReqDetails.getPayloadName(), sdncUserDetails, derivedFromName);
+ Map<String, Object> capabilities = importReqDetails.getCapabilities();
+ Map<String, Object> twinCapabilitiesFromResponse = parseReqOrCapFromResponse("capabilities", importReqDetails, expectedNumOfCapabilities);
+ assertEquals(capabilities.keySet().size(), twinCapabilitiesFromResponse.keySet().size());
+ importReqDetails.compareRequirementsOrCapabilities(capabilities, twinCapabilitiesFromResponse);
+
+ assertEquals(childRequirementsFromResponse.keySet().size(), twinRequirementsFromResponse.keySet().size());
+ assertEquals(childCapabilitiesFromResponse.keySet().size(), twinCapabilitiesFromResponse.keySet().size());
+ }
+
+ /*
+ * invariantUUID - US672129
+ */
+
+ private void checkInvariantUuidIsImmutableInDifferentAction(ImportReqDetails importReqDetails) throws Exception {
+ // create resource
+ importReqDetails.setName("import");
+ String invariantUuidDefinedByUser = "abcd1234";
+ RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, invariantUuidDefinedByUser);
+ String invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse);
+ assertFalse(checkInvariantUuidEqual(invariantUuidDefinedByUser, importResourceResponse));
+
+ // get resource
+ RestResponse getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, getResource));
+
+ // checkin resource
+ RestResponse changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // checkout resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // checkin resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // checkout resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // checkin resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // certification request
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // start certification
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // certify
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.CERTIFY);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+ String certifiedUniqueId = importReqDetails.getUniqueId();
+
+ // update resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKOUT);
+ ResourceReqDetails updatedResourceReqDetails = new ResourceReqDetails(importReqDetails, importReqDetails.getVersion());
+ updatedResourceReqDetails.setDescription("updatedDescription");
+ updatedResourceReqDetails.setVendorRelease("1.2.3.4");
+ RestResponse updateResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceReqDetails, sdncUserDetails, importReqDetails.getUniqueId());
+ assertEquals(STATUS_CODE_SUCCESS, updateResponse.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, updateResponse));
+
+ // certification request
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // checkout resource
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // certification request
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // start certification
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // cancel certification
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.CANCELCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // start certification
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // failure
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, testerUser, LifeCycleStatesEnum.FAILCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // upload artifact
+ changeResourceState = LifecycleRestUtils.changeResourceState(importReqDetails, sdncUserDetails, LifeCycleStatesEnum.CHECKOUT);
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact();
+ ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, sdncUserDetails, importReqDetails.getUniqueId());
+ assertEquals(STATUS_CODE_SUCCESS, changeResourceState.getErrorCode().intValue());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, changeResourceState));
+
+ // create instance
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.toString());
+ ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ importReqDetails.setUniqueId(certifiedUniqueId);
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(importReqDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails, resourceDetails.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals(STATUS_CODE_CREATED, createResourceInstanceResponse.getErrorCode().intValue());
+ getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId());
+ assertTrue(checkInvariantUuidEqual(invariantUUIDcreation, getResource));
+ }
+
+ private boolean checkInvariantUuidEqual(String expectedInvariantUuid, RestResponse response) {
+ String invariantUUIDFromResponse = ResponseParser.getInvariantUuid(response);
+ return expectedInvariantUuid.equals(invariantUUIDFromResponse);
+ }
+
+ @Test
+ public void checkCPHasImmutableInvariantUuidTest() throws Exception {
+ String filename = "FatherHasNoReqCap.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, filename);
+ checkResourceHasImmutableInvariantUuidTest(importReqDetails);
+ }
+
+ @Test
+ public void checkVFCHasImmutableInvariantUuidTest() throws Exception {
+ String filename = "computeCap11.yml";
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, filename);
+ checkResourceHasImmutableInvariantUuidTest(importReqDetails);
+ }
+
+ public void checkResourceHasImmutableInvariantUuidTest(ImportReqDetails importReqDetails) throws Exception {
+ // invariantUuid is null
+ importReqDetails.setName("first");
+ RestResponse importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, null);
+ String invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse);
+ assertNotNull(invariantUUIDcreation);
+
+ ResourceRestUtils.deleteResource(importReqDetails.getUniqueId(), sdncUserDetails.getUserId());
+
+ // invariantUuid is empty
+ importReqDetails.setName("second");
+ String invariantUuidDefinedByUser = "";
+ importResourceResponse = importResourceWithRequestedInvariantUuid(importReqDetails, invariantUuidDefinedByUser);
+ invariantUUIDcreation = ResponseParser.getInvariantUuid(importResourceResponse);
+ assertNotNull(invariantUUIDcreation);
+
+ ResourceRestUtils.deleteResource(importReqDetails.getUniqueId(), sdncUserDetails.getUserId());
+
+ checkInvariantUuidIsImmutableInDifferentAction(importReqDetails);
+ }
+
+ private static RestResponse importResourceWithRequestedInvariantUuid(ImportReqDetails importDetails, String invariantUuid) throws Exception {
+ importDetails.setInvariantUUID(invariantUuid);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importDetails, sdncUserDetails, null);
+ assertEquals(STATUS_CODE_CREATED, importResourceResponse.getErrorCode().intValue());
+ return importResourceResponse;
+ }
+
+ private Map<String, Object> parseReqOrCapFromResponse(String parsedFieldName, ImportReqDetails importReqDetails, int expectedNumOfReqCap) throws ClientProtocolException, IOException {
+ RestResponse getResource = ResourceRestUtils.getResource(importReqDetails.getUniqueId());
+ assertTrue(getResource.getErrorCode().equals(STATUS_CODE_SUCCESS));
+ Map<String, Object> parsedFieldFromResponseToMap = ResponseParser.getJsonValueAsMap(getResource, parsedFieldName);
+ Iterator<String> iterator = parsedFieldFromResponseToMap.keySet().iterator();
+ actualNumOfReqOrCap = 0;
+ while (iterator.hasNext()) {
+ String next = iterator.next();
+ List<Object> object = (List<Object>) parsedFieldFromResponseToMap.get(next);
+ actualNumOfReqOrCap += object.size();
+ }
+ assertEquals(expectedNumOfReqCap, actualNumOfReqOrCap);
+ return parsedFieldFromResponseToMap;
+ }
+
+ // ---------------------------------
+
+ private void verifyResourcePropertiesList(Resource resourceJavaObject) { // use
+ // importListPropertySuccessFlow.yml
+ boolean isPropertyAppear = false;
+ List<PropertyDefinition> propertiesList = resourceJavaObject.getProperties();
+ for (PropertyDefinition pro : propertiesList) {
+ switch (pro.getName()) {
+ case "my_boolean":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[false,true]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "my_boolean_array":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "duplicate_boolean_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false,true]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_values_Insensitive":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false,true]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "my_integers":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0,1000,-1000,50]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "my_integers_array":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[10,-1000,0]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "duplicate_integers_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[10,10,-1000,0]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "my_string":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"$?^@ecomp$!#%()_-~@+*^...;;/w#\",\"uc\"]"));
+ // assertTrue("Check Property default values ",
+ // pro.getDefaultValue().equals("[\"asdc\",\"@=~!@#$%^&*()_+=?><:-w\",\"uc\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "my_string_array":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"AAA\",\"~$~#bbb%^*_-\",\"qwe\",\"1.3\",\"500\",\"true\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "duplicate_string_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"asdc\",\"uc\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_null_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"uc\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_space_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"asdc\",\"uc\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_array_null_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[\"aaa\",\"bbb\",\"500\"]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "my_float":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,1000.000001,-3.0]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "my_float_array":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0.01,-5.0,2.1]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "duplicate_float_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[0.0,0.0,4.555555]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_no_default_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "integer_no_default_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "string_no_default_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_no_default_values":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "integer_null_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[1000,2000]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_null_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[true,false]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "float_null_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,-3.0]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_space_value":
+ assertTrue("Check Property Type ", pro.getType().equals("list"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("[6,-3.0]"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+
+ }
+ assertTrue(isPropertyAppear);
+ isPropertyAppear = false;
+ }
+
+ }
+
+ private void verifyRequirementsOccurrences(Resource resourceJavaObject, String requirementsType) {
+ boolean isRequirementAppear = false;
+ // List<RequirementDefinition> requerments =
+ // resourceJavaObject.getRequirements().get("tosca.capabilities.Attachment");
+ List<RequirementDefinition> requerments = resourceJavaObject.getRequirements().get(requirementsType);
+
+ for (RequirementDefinition req : requerments) {
+ switch (req.getName()) {
+ case "local_storage100":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("UNBOUNDED"));
+ isRequirementAppear = true;
+ break;
+ case "local_storage200":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("1"));
+ isRequirementAppear = true;
+ break;
+ case "local_storage300":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("10"));
+ isRequirementAppear = true;
+ break;
+ case "local_storage400":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("10000000"));
+ isRequirementAppear = true;
+ break;
+ case "local_storage500":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("2"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("3"));
+ isRequirementAppear = true;
+ break;
+ case "local_storageNoOccurrences600":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals("1"));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals("1"));
+ isRequirementAppear = true;
+ break;
+ }
+ assertTrue(isRequirementAppear);
+ isRequirementAppear = false;
+ }
+
+ }
+
+ private void verifyCapabilitiesOccurrences(Resource resourceJavaObject, String capabilitType) {
+ boolean isCapabilityAppear = false;
+ // List<CapabilityDefinition> capabilities =
+ // resourceJavaObject.getCapabilities().get("tosca.capabilities.Endpoint.Admin");
+ List<CapabilityDefinition> capabilities = resourceJavaObject.getCapabilities().get(capabilitType);
+
+ for (CapabilityDefinition cap : capabilities) {
+ switch (cap.getName()) {
+ case "endpointNoOccurrence":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("UNBOUNDED"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint200":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("2"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint300":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("1"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint400":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("10"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint500":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("10000000"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint600":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("1"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("UNBOUNDED"));
+ isCapabilityAppear = true;
+ break;
+ case "endpoint700":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals("2"));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals("4"));
+ isCapabilityAppear = true;
+ break;
+
+ }
+ assertTrue(isCapabilityAppear);
+ isCapabilityAppear = false;
+ }
+
+ }
+
+ private void verifyResourcePropertiesMap(Resource resourceJavaObject) { // use
+ // importMapPropertySuccessFlow.yml
+ boolean isPropertyAppear = false;
+ List<PropertyDefinition> propertiesList = resourceJavaObject.getProperties();
+ for (PropertyDefinition pro : propertiesList) {
+ switch (pro.getName()) {
+ case "string_prop01":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop02":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop03":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"val1\",\"keyB\":\"val2\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop04":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"10\",\"keyB\":\"true\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop05":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":\"Big\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop06":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"aaaA\",\"keyB\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop07":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop08":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"\",\"keyB\":\"abcd\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop09":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\" \",\"keyB\":\"abcd\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop10":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\" aaaa\",\"keyB\":\" bbbb\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop11":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"aaaa \",\"keyB\":\"bbbb \"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop12":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\" aaaa \",\"keyB\":\" bbbb ccccc \"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop13":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"aaaa\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop14":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\" aaaa \"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop15":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop16":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop17":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop18":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop19":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"AbcD\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop20":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":\"aaaa\",\"keya\":\"aaaa\",\"Keya\":\"Aaaa\",\"KEYA\":\"nnnn\"}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop21":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "string_prop22":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("string"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop01":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":1,\"keyB\":1000}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop02":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop03":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":800,\"keyB\":-600}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop04":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":-600}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop05":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":0}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop06":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":0}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop07":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":100}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop08":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":200}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop09":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":100,\"keyB\":200}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop10":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":2222}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop11":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop12":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "integer_prop13":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":200}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("integer"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop01":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop02":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop03":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop04":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop05":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false,\"keyC\":false}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop06":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":true,\"keyC\":false}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop07":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop08":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":true,\"keyB\":false}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "boolean_prop09":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":false,\"keyB\":true}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("boolean"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop01":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":1.2,\"keyB\":3.56,\"keyC\":33}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop02":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":0.0,\"keyB\":0.0,\"keyC\":0}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop03":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop04":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":1.2,\"keyB\":3.56,\"keyC\":33}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop05":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":33,\"keyB\":1.2,\"keyC\":3.607,\"keyD\":0}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop06":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":33,\"keyB\":1.2,\"keyC\":3.607}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop07":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":null,\"keyB\":null,\"keyC\":null,\"keyD\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop08":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertEquals("Check Property default values ", pro.getDefaultValue(), null);
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop09":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":0.01,\"keyB\":null}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop10":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":0.00020}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ case "float_prop11":
+ assertTrue("Check Property Type ", pro.getType().equals("map"));
+ assertTrue("Check Property default values ", pro.getDefaultValue().equals("{\"keyA\":3.56,\"keyB\":33}"));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType().equals("float"));
+ isPropertyAppear = true;
+ break;
+ }
+ assertTrue(isPropertyAppear);
+ isPropertyAppear = false;
+ }
+
+ }
+
+ @Test
+ public void importToscaResourceAttributeSuccessFlow() throws Exception {
+
+ String fileName = importAttributeSuccess;
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, sdncUserDetails, null);
+ ResourceRestUtils.checkCreateResponse(importResourceResponse);
+ Resource resourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ ToscaNodeTypeInfo parseToscaNodeYaml = utils.parseToscaNodeYaml(Decoder.decode(importReqDetails.getPayloadData()));
+
+ HashMap<String, AttributeDefinition> attr = new HashMap<>();
+
+ AttributeDefinition newAttr2 = new AttributeDefinition();
+ newAttr2.setName("networks");
+ newAttr2.setType("map");
+ newAttr2.setDefaultValue("{\"keyA\" : val1 , \"keyB\" : val2}");
+ SchemaDefinition schema = new SchemaDefinition();
+ PropertyDataDefinition prop = new PropertyDataDefinition();
+ prop.setType("string");
+ schema.setProperty(prop);
+ newAttr2.setSchema(schema);
+ attr.put("networks", newAttr2);
+
+ AttributeDefinition newAttr1 = new AttributeDefinition();
+ newAttr1.setName("public_address");
+ newAttr1.setType("string");
+ attr.put("public_address", newAttr1);
+
+ AttributeDefinition newAttr3 = new AttributeDefinition();
+ newAttr3.setName("ports");
+ newAttr3.setDescription("this is my description");
+ attr.put("ports", newAttr3);
+
+ AttributeDefinition newAttr = new AttributeDefinition();
+ newAttr.setDefaultValue("myDefault");
+ newAttr.setName("private_address");
+ newAttr.setStatus("supported");
+ newAttr.setType("string");
+ attr.put("private_address", newAttr);
+
+ // verify Resource Attributes
+ validateResourceAttribute(resourceJavaObject, attr);
+
+ // TO DO
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ElementFactory.getDefaultImportResourceAuditMsgSuccess();
+ expectedResourceAuditJavaObject.setResourceName(importReqDetails.getName());
+ expectedResourceAuditJavaObject.setModifierName(sdncUserDetails.getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ expectedResourceAuditJavaObject.setToscaNodeType(parseToscaNodeYaml.getNodeName());
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, AuditingActionEnum.IMPORT_RESOURCE.getName(), null, false);
+ }
+
+ private void validateResourceAttribute(Resource resource, Map<String, AttributeDefinition> attr) {
+ List<AttributeDefinition> resList = resource.getAttributes();
+ int size = resList.size();
+ String attributeName;
+ for (int i = 0; i < size; i++) {
+ attributeName = resList.get(i).getName();
+ assertEquals(attr.get(attributeName).getDefaultValue(), resList.get(i).getDefaultValue());
+ assertEquals(attr.get(attributeName).getName(), resList.get(i).getName());
+ assertEquals(attr.get(attributeName).getDescription(), resList.get(i).getDescription());
+ assertEquals(attr.get(attributeName).getStatus(), resList.get(i).getStatus());
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java
new file mode 100644
index 0000000000..9e8b94e5a8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportUpdateResourseCsarTest.java
@@ -0,0 +1,282 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.imports;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.commons.codec.binary.Base64;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ImportUpdateResourseCsarTest extends ComponentBaseTest {
+ @Rule
+ public static TestName name = new TestName();
+
+ Gson gson = new Gson();
+ public static String userDefinedNodeYaml = "mycompute2.yml";
+ public static String rootPath = System.getProperty("user.dir");
+ public static String csarFolderPath = "/src/test/resources/CI/csars/";
+
+ public ImportUpdateResourseCsarTest() {
+ super(name, ImportUpdateResourseCsarTest.class.getName());
+ }
+
+ @Test
+ public void createUpdateImportResourceFromCsarTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ RestResponse updateResource = null;
+ RestResponse createResource = null;
+ Resource resource = null;
+ String payloadName = "orig2G.csar";
+ String rootPath = System.getProperty("user.dir");
+ Path path = Paths.get(rootPath + csarFolderPath + "orig2G.csar");
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("orig2G.csar");
+ resourceDetails.setCsarVersion("1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ // create new resource from Csar
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ // update scar with new artifacts
+ path = Paths.get(rootPath + csarFolderPath + "orig2G_update.csar");
+ data = Files.readAllBytes(path);
+ payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setDescription("update");
+ resourceDetails.setCsarVersion("2");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ }
+
+ @Test
+ public void createUpdateImportResourceFromCsarWithArtifactsGroupNamingTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes;
+ ResourceReqDetails resourceDetails;
+ RestResponse updateResource;
+ RestResponse createResource;
+ Resource resource;
+
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "VF_RI2_G4_withArtifacts_group_naming_a.csar", "VF_RI2_G4_withArtifacts_group_naming.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("VF_RI2_G4_withArtifacts_group_naming.csar");
+ resourceDetails.setCsarVersion("1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ // create new resource from Csar
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ List<GroupDefinition> groups = resource.getGroups();
+ assertTrue(groups != null && groups.size() == 6);
+ assertTrue(groups.stream()
+ .filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)
+ && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(g.getName()).matches())
+ .count() == 0);
+ // update scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "VF_RI2_G4_withArtifacts_group_naming_delete_update.csar", "VF_RI2_G4_withArtifacts_group_naming.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ resourceDetails.setCsarVersion("2");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ groups = resource.getGroups();
+ assertTrue(groups != null && groups.size() == 5);
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "VF_RI2_G4_withArtifacts_group_naming_a.csar", "VF_RI2_G4_withArtifacts_group_naming.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ resourceDetails.setCsarVersion("3");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ groups = resource.getGroups();
+ assertTrue(groups != null && groups.size() == 6);
+ assertTrue(groups.stream()
+ .filter(g -> g.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)
+ && !Pattern.compile(Constants.MODULE_NEW_NAME_PATTERN).matcher(g.getName()).matches())
+ .count() == 0);
+ }
+
+ @Test
+ public void createUpdateDeleteAllRequiredArtifactsTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes;
+ ResourceReqDetails resourceDetails;
+ RestResponse updateResource;
+ RestResponse createResource;
+ Resource resource;
+ String artifactName = "heatnested7";
+
+ ImportReqDetails resourceDetails0 = ElementFactory.getDefaultImportResource();
+ createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, resourceDetails0);
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("orig2GV001.csar");
+ resourceDetails.setCsarVersion("1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ // create new resource from Csar
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 2);
+ List<GroupDefinition> groups = resource.getGroups();
+ // update scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "orig2GV006-remove-all-nested-artifacts.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ resourceDetails.setCsarVersion("2");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 0);
+ groups = resource.getGroups();
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ // First create from orig2GV006-remove-all-nested-artifacts.csar (without
+ // requiredArtifact)
+ // Submit for testing
+ // Login as tester -> Certification
+ // Login as designer
+ // then update to orig2GV008-change-nested-oam-fileContent.csar (with
+ // requiredArtifact)
+ // Expected: requiredArtifact: ["hot-nimbus-psm_v1.0.yaml",
+ // "hot-nimbus-swift-container_v1.0.yaml"]
+ // Actual: no requiredArtifact
+ @Test
+ public void createUpdateAddRequiredArtifactsTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse copyRes;
+ ResourceReqDetails resourceDetails;
+ RestResponse updateResource;
+ RestResponse createResource;
+ Resource resource;
+ String artifactName = "heatnested7";
+
+ ImportReqDetails resourceDetails0 = ElementFactory.getDefaultImportResource();
+ createResource = importUserDefinedNodeType(userDefinedNodeYaml, sdncModifierDetails, resourceDetails0);
+ BaseRestUtils.checkCreateResponse(createResource);
+ createResource = LifecycleRestUtils.certifyResource(resourceDetails0);
+ BaseRestUtils.checkSuccess(createResource);
+
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "orig2GV006-remove-all-nested-artifacts.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+
+ resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("TEST01");
+ resourceDetails.setCsarUUID("orig2GV001.csar");
+ resourceDetails.setCsarVersion("1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ // create new resource from Csar
+ createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ createResource = LifecycleRestUtils.certifyResource(resourceDetails);
+ BaseRestUtils.checkSuccess(createResource);
+
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 0);
+ List<GroupDefinition> groups = resource.getGroups();
+ // update scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails,
+ "orig2GV008-change-nested-oam-fileContent.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ resourceDetails.setDescription("BLA BLA BLA");
+ resourceDetails.setCsarVersion("2");
+ updateResource = ResourceRestUtils.updateResource(resourceDetails, sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(updateResource);
+ resource = ResponseParser.parseToObjectUsingMapper(updateResource.getResponse(), Resource.class);
+ assertTrue(resource.getDeploymentArtifacts().get(artifactName).getRequiredArtifacts().size() == 2);
+ groups = resource.getGroups();
+ // back original scar
+ copyRes = ImportCsarResourceTest.copyCsarRest(sdncModifierDetails, "orig2GV001_a.csar", "orig2GV001.csar");
+ BaseRestUtils.checkSuccess(copyRes);
+ }
+
+ private RestResponse importUserDefinedNodeType(String payloadName, User sdncModifierDetails,
+ ImportReqDetails resourceDetails) throws Exception {
+
+ Path path = Paths.get(rootPath + csarFolderPath + payloadName);
+ byte[] data = Files.readAllBytes(path);
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(ResourceTypeEnum.VFC.name());
+ return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java
new file mode 100644
index 0000000000..345b81eb3e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/inputs/InputsApiTests.java
@@ -0,0 +1,225 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.inputs;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.InputDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.InputsRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+import fj.data.Either;
+
+/**
+ * CI-Tests for inputs
+ * @author il0695
+ *
+ */
+public class InputsApiTests extends ComponentBaseTest {
+
+ private static String inputCsar1 = "FCGI_with_inputs.csar";
+ private static String inputCsar2 = "LDSA1_with_inputs.csar";
+ private static User sdncDesignerDetails = null;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ /**
+ * Constructor
+ */
+ public InputsApiTests() {
+ super(name, InputsApiTests.class.getName());
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ }
+
+ /**
+ * Create VF with inputs from CSAR file
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testCreateResourceInstanceWithInputsFromCsar() throws Exception {
+ Resource vf = AtomicOperationUtils.importResourceFromCSAR(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, inputCsar1);
+ assertTrue("Success creating VF from CSAR", !vf.getInputs().isEmpty());
+ }
+
+ /**
+ * Create service and add to it VF instance with inputs
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testAddVfInstanceWithInputsToService() throws Exception {
+ createServiceWithVFInstanceWithInputs();
+ }
+
+ /**
+ * General test to check most functionality of inputs
+ * <ul>
+ * <li>Create service with VF instance that has inputs)</li>
+ * <li>Get all inputs of VF instance</li>
+ * <li>Add inputs to service</li>
+ * <li>Get service inputs</li>
+ * <li>Delete service inputs</li>
+ * </ul>
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testInputsMainFunctionality() throws Exception {
+ Service service = createServiceWithVFInstanceWithInputs();
+ int totalInputsBeforeAdd = service.getInputs().size();
+
+ // Get component instances
+ RestResponse getInstancesResponse = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE, service.getUniqueId(), sdncDesignerDetails);
+ BaseValidationUtils.checkSuccess(getInstancesResponse);
+ List<ComponentInstance> serviceInstances = new Gson().fromJson(getInstancesResponse.getResponse(), new TypeToken<ArrayList<ComponentInstance>>(){}.getType());
+
+ // Get all inputs of first instance
+ ComponentInstance vfInstance = serviceInstances.get(0);
+ RestResponse getComponentInstanceInputsResponse = InputsRestUtils.getComponentInstanceInputs(service, vfInstance);
+ BaseValidationUtils.checkSuccess(getComponentInstanceInputsResponse);
+ List<InputDefinition> instanceInputs = new Gson().fromJson(getComponentInstanceInputsResponse.getResponse(), new TypeToken<ArrayList<InputDefinition>>(){}.getType());
+
+ // Take only the 2 first inputs
+ List<InputDefinition> inputsToAdd = instanceInputs.stream().limit(2).collect(Collectors.toList());
+
+ // Build component instances input map to add to server
+ ComponentInstInputsMap buildComponentInstInputsMap = buildComponentInstInputsMap(vfInstance.getUniqueId(), inputsToAdd);
+ RestResponse addInputResponse = InputsRestUtils.addInput(service, buildComponentInstInputsMap, UserRoleEnum.DESIGNER);
+ BaseValidationUtils.checkSuccess(addInputResponse);
+
+ // Get service inputs count
+ RestResponse getComponentInputsResponse = InputsRestUtils.getComponentInputs(service);
+ BaseValidationUtils.checkSuccess(getComponentInputsResponse);
+ List<InputDefinition> serviceInputsAfterAdd = new Gson().fromJson(getComponentInputsResponse.getResponse(), new TypeToken<ArrayList<InputDefinition>>(){}.getType());
+ if (serviceInputsAfterAdd.size()-totalInputsBeforeAdd!=2) {
+ assertTrue("Error adding inputs to service (service should have 2 inputs)", false);
+ }
+
+ // Delete 1 input from service
+ RestResponse deleteInputFromComponentResponse = InputsRestUtils.deleteInputFromComponent(service, serviceInputsAfterAdd.get(0).getUniqueId());
+ BaseValidationUtils.checkSuccess(deleteInputFromComponentResponse);
+
+ // Get service inputs count after delete
+ RestResponse getComponentInputsResponseAfterDelete = InputsRestUtils.getComponentInputs(service);
+ BaseValidationUtils.checkSuccess(getComponentInputsResponseAfterDelete);
+ List<InputDefinition> serviceInputsAfterDelete = new Gson().fromJson(getComponentInputsResponseAfterDelete.getResponse(), new TypeToken<ArrayList<InputDefinition>>(){}.getType());
+ if (serviceInputsAfterDelete.size()-totalInputsBeforeAdd!=1) {
+ assertTrue("Error deleting inputs from service (service should have 1 input)", false);
+ }
+
+ assertTrue("Success testing inputs main functionality", true);
+ }
+
+ /**
+ * Private method to create service with VF instance that has inputs
+ * This is private method to be used by multiple tests
+ *
+ * @return {@link org.openecomp.sdc.be.model}
+ * @throws Exception
+ * @throws IOException
+ */
+ private Service createServiceWithVFInstanceWithInputs() throws Exception, IOException {
+ // Create default service
+ Either<Service, RestResponse> createDefaultServiceEither = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
+ if (createDefaultServiceEither.isRight()){
+ assertTrue("Error creating default service", false);
+ }
+ Service service = createDefaultServiceEither.left().value();
+
+ // Create VF from CSAR file
+ Resource vfWithInputs = AtomicOperationUtils.importResourceFromCSAR(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, inputCsar2);
+
+ // Certify VF
+ Pair<Component, RestResponse> changeComponentState = AtomicOperationUtils.changeComponentState(vfWithInputs, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ assertTrue("response code is BaseRestUtils.STATUS_CODE_SUCCESS, returned :" + changeComponentState.getRight().getErrorCode(), changeComponentState.getRight().getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ // Add VF instance to service
+ Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainerEither = AtomicOperationUtils.addComponentInstanceToComponentContainer(vfWithInputs, service, UserRoleEnum.DESIGNER, true);
+ if (addComponentInstanceToComponentContainerEither.isRight()){
+ assertTrue("Error adding VF to service", false);
+ }
+
+ // Get service response
+ ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+
+ // Get VF instance from service
+ ComponentInstance vfInstance = service.getComponentInstances().get(0);
+ if (vfInstance!=null){
+ assertTrue("Success creating service with VF instance", true);
+ } else {
+ assertTrue("Error creating service with VF instance", false);
+ }
+ return service;
+ }
+
+ /**
+ * Return default ComponentInstInputsMap
+ *
+ * @param addToInput
+ * @param inputs
+ * @return {@link org.openecomp.sdc.be.model.ComponentInstInputsMap}
+ */
+ private ComponentInstInputsMap buildComponentInstInputsMap (String addToInput, List<InputDefinition> inputs) {
+ Map<String, List<InputDefinition>> map = new HashMap<>();
+ map.put(addToInput, inputs);
+ ComponentInstInputsMap componentInstInputsMap = new ComponentInstInputsMap();
+ componentInstInputsMap.setComponentInstanceInputsMap(map);
+ return componentInstInputsMap;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java
new file mode 100644
index 0000000000..e15652dddf
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/lifecycle/LCSbaseTest.java
@@ -0,0 +1,274 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.lifecycle;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+
+import org.apache.log4j.lf5.util.ResourceUtils;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.annotations.BeforeMethod;
+
+/**
+ *
+ * @author al714h
+ *
+ * resourceDetails - create, Add Heat, certify resourceDetails1 - create
+ * resource, LCS - CheckOut serviceDetails - create, add RI from
+ * resourceDetails serviceDetails2 - create, add RI from resourceDetails
+ * serviceDetailsEmpty - create, LCS - CheckOut serviceDetailsEmpty2 -
+ * create, LCS - CheckOut
+ *
+ */
+public abstract class LCSbaseTest extends ComponentBaseTest {
+
+ protected ResourceReqDetails resourceDetails;
+ protected ResourceReqDetails resourceDetails1;
+ protected ServiceReqDetails serviceDetails;
+ protected ServiceReqDetails serviceDetails2;
+ protected ServiceReqDetails serviceDetailsEmpty;
+ protected ServiceReqDetails serviceDetailsEmpty2;
+ protected ComponentInstanceReqDetails componentInstanceReqDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails2;
+ protected User sdncDesignerDetails1;
+ protected User sdncDesignerDetails2;
+ protected static User sdncTesterDeatails1;
+ protected User sdncAdminDetails1;
+ protected ArtifactReqDetails heatArtifactDetails;
+ protected ArtifactReqDetails heatVolArtifactDetails;
+ protected ArtifactReqDetails heatNetArtifactDetails;
+
+ protected ArtifactReqDetails defaultArtifactDetails;
+ protected ResourceUtils resourceUtils;
+ protected ArtifactUtils artifactUtils;
+
+ // protected static ServiceUtils serviceUtils = new ServiceUtils();
+ public LCSbaseTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+
+ initializeMembers();
+
+ createComponents();
+
+ }
+
+ public void initializeMembers() throws IOException, Exception {
+ resourceDetails = ElementFactory.getDefaultResource();
+ // resourceDetails =
+ // ElementFactory.getDefaultResource("myNewResource1234567890",
+ // NormativeTypesEnum.ROOT, ResourceServiceCategoriesEnum.ROUTERS,
+ // UserRoleEnum.DESIGNER.getUserId());
+ resourceDetails1 = ElementFactory.getDefaultResource("secondResource", NormativeTypesEnum.ROOT);
+ serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails2 = ElementFactory.getDefaultService("newTestService2", ServiceCategoriesEnum.MOBILITY, "al1976");
+ serviceDetailsEmpty = ElementFactory.getDefaultService("newEmptyService", ServiceCategoriesEnum.MOBILITY,
+ "al1976");
+ serviceDetailsEmpty2 = ElementFactory.getDefaultService("newEmptyService2", ServiceCategoriesEnum.MOBILITY,
+ "al1976");
+ sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ heatNetArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_NET.getType());
+ heatVolArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT_VOL.getType());
+ componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+ resourceInstanceReqDetails2 = ElementFactory.getDefaultComponentInstance();
+
+ }
+
+ protected void createComponents() throws Exception {
+
+ RestResponse response = ResourceRestUtils.createResource(resourceDetails1, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetails1.getUniqueId());
+
+ response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId());
+
+ response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId());
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1,
+ resourceDetails.getUniqueId());
+ assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ // certified resource
+ response = LCSbaseTest.certifyResource(resourceDetails, sdncDesignerDetails1);
+ assertTrue("certify resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ // add resource instance with HEAT deployment artifact to the service
+ componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncDesignerDetails1,
+ serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201);
+
+ response = ServiceRestUtils.createService(serviceDetails2, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetails2.getUniqueId());
+
+ componentInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(componentInstanceReqDetails, sdncDesignerDetails1,
+ serviceDetails2.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201);
+
+ response = ServiceRestUtils.createService(serviceDetailsEmpty, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetailsEmpty.getUniqueId());
+
+ response = ServiceRestUtils.createService(serviceDetailsEmpty2, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetailsEmpty2.getUniqueId());
+
+ DbUtils.cleanAllAudits();
+
+ }
+
+ public static RestResponse certifyResource(ResourceReqDetails resourceDetails, User user) throws Exception {
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(),
+ LifeCycleStatesEnum.CHECKIN);
+ // if (restResponseResource.getErrorCode() == 200){
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ // }else
+ // return restResponseResource;
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ if (restResponseResource.getErrorCode() == 200) {
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
+ sdncTesterDeatails1.getUserId(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponseResource;
+ if (restResponseResource.getErrorCode() == 200) {
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
+ sdncTesterDeatails1.getUserId(), LifeCycleStatesEnum.CERTIFY);
+ }
+ return restResponseResource;
+ }
+
+ public static RestResponse certifyService(ServiceReqDetails serviceDetails, User user) throws Exception {
+ RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, user,
+ LifeCycleStatesEnum.CHECKIN);
+ // if (restResponseService.getErrorCode() == 200){
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, user,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ // }else
+ // return restResponseService;
+
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ if (restResponseService.getErrorCode() == 200) {
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDeatails1,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponseService;
+ if (restResponseService.getErrorCode() == 200) {
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDeatails1,
+ LifeCycleStatesEnum.CERTIFY);
+ }
+ return restResponseService;
+ }
+
+ protected static RestResponse raiseResourceToTargetVersion(ResourceReqDetails resourceDetails, String targetVersion,
+ User user) throws Exception {
+ return raiseResourceToTargetVersion(resourceDetails, targetVersion, null, user);
+ }
+
+ protected static RestResponse raiseResourceToTargetVersion(ResourceReqDetails resourceDetails, String targetVersion,
+ RestResponse prevResponse, User user) throws Exception {
+
+ String[] splitParts = targetVersion.split("\\.");
+
+ int version = Integer.parseInt(splitParts[1]);
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+
+ if (prevResponse != null) {
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(prevResponse.getResponse());
+ if (resourceRespJavaObject.getLifecycleState().equals(LifecycleStateEnum.CERTIFIED)) {
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
+ user.getUserId(), LifeCycleStatesEnum.CHECKOUT);
+ }
+ }
+
+ RestResponse restResponseResource = null;
+ for (int i = 0; i < (version - 1); i++) {
+
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, null,
+ LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ if (restResponseResource.getErrorCode() == 200) {
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user.getUserId(),
+ LifeCycleStatesEnum.CHECKOUT);
+ if (restResponseResource.getErrorCode() == 200) {
+
+ } else
+ break;
+
+ } else
+ break;
+
+ }
+
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, null,
+ LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+ assertEquals("Check response code ", 200, restResponseResource.getErrorCode().intValue());
+ return restResponseResource;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java
new file mode 100644
index 0000000000..6a4fa3ba55
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ChangeServiceInstanceVersionTest.java
@@ -0,0 +1,1478 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ChangeServiceInstanceVersionTest extends ComponentInstanceBaseTest {
+
+ protected ArtifactReqDetails heatArtifactDetails;
+ public String firstVfInstanceUniqueId;
+ public String firstVfInstanceName;
+ public String secondVfInstanceUniqueId;
+ public String secoundVfInstanceName;
+ public String serviceInstanceToReplaceUniqueId;
+ public String expectedServiceName;
+ public String expectedPosX;
+ public String expectedPosY;
+ public String actualServiceInstanceName;
+ public String actualPosX;
+ public String actualPosY;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ChangeServiceInstanceVersionTest() {
+ super(name, ChangeServiceInstanceVersionTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+ firstVfInstanceName = null;
+ secoundVfInstanceName = null;
+ firstVfInstanceUniqueId = null;
+ secondVfInstanceUniqueId = null;
+ serviceInstanceToReplaceUniqueId = null;
+ expectedServiceName = null;
+ expectedPosX = null;
+ expectedPosY = null;
+ actualServiceInstanceName = null;
+ actualPosX = null;
+ actualPosY = null;
+ init();
+ createComponents();
+ }
+
+ private void createComponents() throws Exception {
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ createAtomicResource(resourceDetailsVFC_01);
+ changeResourceStateToCertified(resourceDetailsVFC_01);
+ createAtomicResource(resourceDetailsCP_01);
+ changeResourceStateToCertified(resourceDetailsCP_01);
+ createAtomicResource(resourceDetailsVL_01);
+ changeResourceStateToCertified(resourceDetailsVL_01);
+ createAtomicResource(resourceDetailsVFC_02);
+ changeResourceStateToCertified(resourceDetailsVFC_02);
+ createAtomicResource(resourceDetailsCP_02);
+ changeResourceStateToCertified(resourceDetailsCP_02);
+ createAtomicResource(resourceDetailsVL_02);
+ changeResourceStateToCertified(resourceDetailsVL_02);
+ createVF(resourceDetailsVF_02);
+ createVF(resourceDetailsVF_01);
+ // create check-In services
+ createService(serviceDetails_01);
+ createService(serviceDetails_02);
+ createService(serviceDetails_03);
+ createProduct(productDetails_01);
+ createProduct(productDetails_02);
+
+ // add resourceDetailsCP_01 ,resourceDetailsVFC_01 and
+ // resourceDetailsCP_01 to resourceDetailsVF_01 and certify
+ // resourceDetailsVF_01
+ certifyVf(resourceDetailsVF_01, resourceDetailsVFC_02, resourceDetailsCP_01);
+ // add resourceDetailsCP_02 ,resourceDetailsVFC_02 and
+ // resourceDetailsVL_02 to resourceDetailsVF_02 and certify
+ // resourceDetailsVF_02
+ certifyVf(resourceDetailsVF_02, resourceDetailsVFC_02, resourceDetailsCP_02);
+ RestResponse createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails); // serviceDetails_01 has certified
+ // resourceDetailsVF_01
+ firstVfInstanceName = ResponseParser.getNameFromResponse(createVFInstanceResponse);
+ createVFInstanceResponse = createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02,
+ sdncDesignerDetails); // serviceDetails_01 has certified
+ // resourceDetailsVF_02
+ secoundVfInstanceName = ResponseParser.getUniqueIdFromResponse(createVFInstanceResponse);
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByPm() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByAdmin() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // service [0.2] state to CERTIFICATIONREQUEST
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT,
+ true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ @Test
+ public void changeServiceInstanceToOlderVersion() throws Exception {
+ // Get VF Instance UniquId [Service version 0.1]
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ ComponentInstance actualComponentInstance = service.getComponentInstances().get(0);
+ firstVfInstanceUniqueId = actualComponentInstance.getUniqueId();
+ String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse);
+
+ // Checkout service [0.2]
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01,
+ sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // Adding service instance (serviceDetails_01 V0.2) to product without
+ // saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to Older version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT,
+ true);
+ // RestResponse changeServiceInstanceVersionResponse =
+ // changeServiceInstanceVersion(productDetails_01.getUniqueId(),
+ // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid,
+ // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ // DE190201
+ @Test
+ public void changeServiceInstanceVersionToCertifiedVersion() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ /*
+ * String serviceNewUniqueUid =
+ * ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ * serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ */
+ // get the new VF instance uniqueId after checkout service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ // RestResponse changeServiceInstanceVersionResponse =
+ // changeServiceInstanceVersion(productDetails_01.getUniqueId(),
+ // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid,
+ // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ // DE191927
+ @Test(enabled = false)
+ public void changeServiceInstanceVersionThenReCheckInProduct() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ /////////////////////
+ productOldUniqueId = productDetails_01.getUniqueId();
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ /////////////////////////////////////////////
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ @Test
+ public void changeServiceInstanceToHisVersion() throws Exception {
+ // Get VF Instance UniquId [Service version 0.1]
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ String serviceOlderVersionUniquId = ResponseParser.getUniqueIdFromResponse(getServiceResponse);
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceOlderVersionUniquId, sdncPmDetails1, ComponentTypeEnum.PRODUCT,
+ true);
+ // RestResponse changeServiceInstanceVersionResponse =
+ // changeServiceInstanceVersion(productDetails_01.getUniqueId(),
+ // serviceInstanceToReplaceUniqueId , serviceNewUniqueUid,
+ // sdncPmDetails1, ComponentTypeEnum.PRODUCT , true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByAdminNotByProductOwner() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncAdminDetails, ComponentTypeEnum.PRODUCT,
+ true);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByPmNotByProductOwner() throws Exception {
+ // Adding service instance (serviceDetails_01) to product AND --->
+ // saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // change uniqueId after product check-out in expected Req&Cap
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId);
+ // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1
+ // instead sdncPmDetails1)
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(
+ productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails2,
+ ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByTester() throws Exception {
+ // Adding service instance (serviceDetails_01) to product AND --->
+ // saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // change uniqueId after product check-out in expected Req&Cap
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // CHANGE Service Instance VERSION BY NON PRODUCT OWNER (sdncPmDetails1
+ // instead sdncPmDetails1)
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(
+ productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid,
+ sdncTesterDetails, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceVersionProductIsNotCheckOut() throws Exception {
+ // Adding service instance (serviceDetails_01) to product AND --->
+ // saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // CHANGE Service Instance VERSION for Non checkedOut product
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productOldUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ // DE191727
+ @Test(enabled = false)
+ public void changeServiceInstanceVersionServiceIsInCheckOutState() throws Exception {
+ // Adding service instance (serviceDetails_01) to product AND --->
+ // saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceToReplaceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // change uniqueId after product check-out in expected Req&Cap
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // CHANGE Service Instance VERSION to service in checkOut state
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(
+ productDetails_01.getUniqueId(), serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1,
+ ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(serviceNewUniqueUid);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+
+ }
+
+ @Test
+ public void changeServiceInstanceVersionServiceInstanceDoesNotExist() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // change service instance to newer version
+ String serviceUniqueUidNotExist = "1234567890";
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceUniqueUidNotExist, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(serviceUniqueUidNotExist);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ // DE189392
+ @Test(enabled = false)
+ public void changeServiceInstanceNonExistingProduct() throws Exception {
+ // Adding service instance (serviceDetails_01) to product saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // change service instance to newer version - Non existing Product
+ String productNewUniqueIdNotExist = "1234567890";
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueIdNotExist,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(productNewUniqueIdNotExist);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceVersionToNonExisitingServiceVersion() throws Exception {
+ // Adding service instance (serviceDetails_01) to product saving Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ updateNewComponentInstanceId(createServiceInstanceResp, productNewUniqueId);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // change service instance to Non-existing version
+ String serviceUniqueUidNotExist = "1234567890";
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceUniqueUidNotExist, sdncPmDetails1, ComponentTypeEnum.PRODUCT,
+ true);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(serviceUniqueUidNotExist);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceComponentTypeIsNotProduct() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version for NON-Component Type =
+ // Product (e.g. service)
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.SERVICE, true);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceComponentTypeNotSupported() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version for NON-Component Type =
+ // Product (e.g. service)
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1,
+ ComponentTypeEnum.SERVICE_INSTANCE, true);
+ assertEquals("Check response code ", STATUS_CODE_UNSUPPORTED_ERROR,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("null");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales,
+ changeServiceInstanceVersionResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void SeveralServiceInstanceFromSameServiceVersionChangeVersionOnlyForOneServiceInstance() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstanceDuringSetup(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ serviceDetails_01.setUniqueId(serviceNewUniqueUid);
+ // get the new VF instance uniqueId after checkout service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01.getUniqueId(), sdncPmDetails1);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ List<ComponentInstance> serviceComponentInstances = service.getComponentInstances();
+ for (ComponentInstance component : serviceComponentInstances) {
+ if (component.getName().equals(firstVfInstanceName)) {
+ firstVfInstanceUniqueId = component.getUniqueId();
+ }
+ }
+ assertTrue(firstVfInstanceUniqueId != null);
+ // delete resource instance (resourceDetailsVF_01) from Service
+ RestResponse deleteVfFromServiceResponse = deleteVFInstanceDuringSetup(firstVfInstanceUniqueId,
+ serviceDetails_01, sdncDesignerDetails);
+ assertTrue(deleteVfFromServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Add different VF instance (resourceDetailsVF_02) to Service
+ RestResponse restResponse = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(restResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get service instance new uniqueId , name and position after checkout
+ // product
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, sdncPmDetails1, ComponentTypeEnum.PRODUCT, true);
+ ProductRestUtils.checkSuccess(changeServiceInstanceVersionResponse);
+ actualServiceInstanceName = ResponseParser.getNameFromResponse(changeServiceInstanceVersionResponse);
+ actualPosX = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posX");
+ actualPosY = ResponseParser.getValueFromJsonResponse(changeServiceInstanceVersionResponse.getResponse(),
+ "posY");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(changeServiceInstanceVersionResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Verify that Service instance name and position didn't change after
+ // changing service instance version
+ assertTrue(actualServiceInstanceName.equals(expectedServiceName));
+ assertTrue(actualPosX.equals(expectedPosX));
+ assertTrue(actualPosY.equals(expectedPosY));
+ }
+
+ @Test
+ public void changeServiceInstanceVersionByNonAsdcUser() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ nonAsdcUser.setUserId("bt760h");
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void changeServiceInstanceVersionEmptyUserId() throws Exception {
+ // Adding service instance (serviceDetails_01) to product without saving
+ // Req&Cap
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Adding service instance (serviceDetails_02) to product AND ---> Save
+ // Req&Cap
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // check-in product
+ RestResponse changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productOldUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Checkout service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ String serviceNewUniqueUid = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ // Check-In service [0.2]
+ changeStatusResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeStatusResponse);
+ // check-out product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(changeStatusResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ nonAsdcUser.setUserId("");
+ // change service instance to newer version
+ RestResponse changeServiceInstanceVersionResponse = changeServiceInstanceVersion(productNewUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceNewUniqueUid, nonAsdcUser, ComponentTypeEnum.PRODUCT, true);
+ assertEquals("Check response code ", STATUS_CODE_MISSING_INFORMATION,
+ changeServiceInstanceVersionResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
+ changeServiceInstanceVersionResponse.getResponse());
+ // Check-in product
+ changeStatusResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeStatusResponse);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ ////////////////////////////////////
+ private void updateNewComponentInstanceId(RestResponse createServiceInstanceResp, String productNewUniqueId)
+ throws Exception {
+ String firstServiceInstanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "normalizedName");
+ RestResponse getProductResponse = ProductRestUtils.getProduct(productNewUniqueId, sdncPmDetails1.getUserId());
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductResponse.getResponse(), Product.class);
+ List<ComponentInstance> componentInstances = product.getComponentInstances();
+ for (ComponentInstance component : componentInstances) {
+ if (component.getNormalizedName().equals(firstServiceInstanceNormalizedName)) {
+ serviceInstanceToReplaceUniqueId = component.getUniqueId();
+ expectedServiceName = component.getName();
+ expectedPosX = component.getPosX();
+ expectedPosY = component.getPosY();
+ }
+ }
+ assertTrue(serviceInstanceToReplaceUniqueId != null);
+ }
+
+ private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponse;
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponse.getErrorCode() == 200) {
+ String newVersion = ResponseParser.getVersionFromResponse(restResponse);
+ resourceDetails.setVersion(newVersion);
+ resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId());
+ resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(),
+ "uniqueId");
+ resourceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponse;
+ }
+
+ private void certifyVf(ResourceReqDetails resource, ResourceReqDetails computeResource,
+ ResourceReqDetails cpResource) throws Exception {
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, cpResource,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, computeResource,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails,
+ sdncDesignerDetails, resource.getUniqueId());
+ ResourceRestUtils.checkSuccess(response);
+
+ String capOwnerId = toCompInstId;
+ User user = sdncDesignerDetails;
+ ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE;
+
+ fulfillCpRequirement(resource, fromCompInstId, toCompInstId, capOwnerId, user, containerCompType);
+
+ RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource);
+ ResourceRestUtils.checkSuccess(changeResourceStateToCertified);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java
new file mode 100644
index 0000000000..7891f4a46b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductBaseTest.java
@@ -0,0 +1,195 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.PRODUCT_COMPONENT_TYPE;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.BeforeMethod;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+public abstract class ProductBaseTest extends ComponentBaseTest {
+ User productStrategistUser1;
+ User productStrategistUser2;
+ User productStrategistUser3;
+ User productManager1;
+ User productManager2;
+ User adminUser;
+ User designerUser;
+
+ // Category1->Subcategory1->Grouping1
+ protected List<CategoryDefinition> defaultCategories;
+
+ protected static String auditAction;
+ protected static ComponentOperationEnum operation;
+
+ public ProductBaseTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ @BeforeMethod
+ public void beforeProductTest() throws IOException, Exception {
+ productStrategistUser1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+ productStrategistUser2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2);
+ productStrategistUser3 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3);
+ productManager1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ productManager2 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2);
+ adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ createDefaultChain();
+ }
+
+ private void createDefaultChain() throws Exception {
+ CategoryDefinition productCategoryDefinition = ElementFactory.getDefaultCategory();
+ SubCategoryDefinition productSubCategoryDefinition = ElementFactory.getDefaultSubCategory();
+ GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup();
+ productCategoryDefinition.addSubCategory(productSubCategoryDefinition);
+ productSubCategoryDefinition.addGrouping(productGroupingDefinition);
+ List<CategoryDefinition> definitionsList = new ArrayList<>();
+ definitionsList.add(productCategoryDefinition);
+ defaultCategories = createCategoriesChain(definitionsList);
+ }
+
+ private List<CategoryDefinition> createCategoriesChain(List<CategoryDefinition> categoryDefinitions) throws Exception {
+ for (CategoryDefinition categoryDefinition : categoryDefinitions) {
+ RestResponse createCategory = CategoryRestUtils.createCategory(categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ int status = createCategory.getErrorCode().intValue();
+ if (status == BaseRestUtils.STATUS_CODE_CREATED) {
+ String categoryId = ResponseParser.getUniqueIdFromResponse(createCategory);
+ categoryDefinition.setUniqueId(categoryId);
+ }
+ List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
+ for (SubCategoryDefinition subCategoryDefinition : subcategories) {
+ RestResponse createSubCategory = CategoryRestUtils.createSubCategory(subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ status = createSubCategory.getErrorCode().intValue();
+ if (status == BaseRestUtils.STATUS_CODE_CREATED) {
+ String subCategoryId = ResponseParser.getUniqueIdFromResponse(createSubCategory);
+ subCategoryDefinition.setUniqueId(subCategoryId);
+ }
+ List<GroupingDefinition> groupings = subCategoryDefinition.getGroupings();
+ for (GroupingDefinition groupingDefinition : groupings) {
+ RestResponse createGroupingRest = CategoryRestUtils.createGrouping(groupingDefinition, subCategoryDefinition, categoryDefinition, productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ status = createGroupingRest.getErrorCode().intValue();
+ if (status == BaseRestUtils.STATUS_CODE_CREATED) {
+ String groupingId = ResponseParser.getUniqueIdFromResponse(createGroupingRest);
+ groupingDefinition.setUniqueId(groupingId);
+ }
+ }
+ }
+ }
+ RestResponse allCategories = CategoryRestUtils.getAllCategories(productStrategistUser1, PRODUCT_COMPONENT_TYPE);
+ Gson gson = new Gson();
+ List<CategoryDefinition> res = gson.fromJson(allCategories.getResponse(), new TypeToken<List<CategoryDefinition>>() {
+ }.getType());
+ return res;
+ }
+
+ // Category1->Subcategory1->[Grouping1, Grouping11]
+ protected List<CategoryDefinition> addSecondGroupingToDefaultCategory() throws Exception {
+ GroupingDefinition productGroupingDefinition = ElementFactory.getDefaultGroup();
+ productGroupingDefinition.setName("Grouping11");
+ defaultCategories.get(0).getSubcategories().get(0).addGrouping(productGroupingDefinition);
+ return createCategoriesChain(defaultCategories);
+ }
+
+ // Category1->[Subcategory1->[Grouping1,
+ // Grouping11],Subcategory2->[Grouping12]]
+ protected List<CategoryDefinition> addSubcategoryAndGroupingToDefaultCategory() throws Exception {
+ GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup();
+ groupingDefinition1.setName("Grouping11");
+ defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition1);
+
+ SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory();
+ subCategory2.setName("Subcategory2");
+ GroupingDefinition groupingDefinition2 = ElementFactory.getDefaultGroup();
+ groupingDefinition2.setName("Grouping12");
+ subCategory2.addGrouping(groupingDefinition2);
+ defaultCategories.get(0).addSubCategory(subCategory2);
+ return createCategoriesChain(defaultCategories);
+ }
+
+ // [Category1->[Subcategory1->[Grouping1,
+ // Grouping11],Subcategory2->[Grouping12]],
+ // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]],
+ // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11,
+ // Grouping22]]]
+ protected List<CategoryDefinition> addManyGroupingsDiffCategories() throws Exception {
+ CategoryDefinition category2 = ElementFactory.getDefaultCategory();
+ category2.setName("Category2");
+ CategoryDefinition category3 = ElementFactory.getDefaultCategory();
+ category3.setName("Category3");
+ SubCategoryDefinition subCategory1 = ElementFactory.getDefaultSubCategory();
+ subCategory1.setName("Subcategory1");
+ SubCategoryDefinition subCategory2 = ElementFactory.getDefaultSubCategory();
+ subCategory2.setName("Subcategory2");
+ SubCategoryDefinition subCategory1_2 = ElementFactory.getDefaultSubCategory();
+ subCategory1_2.setName("Subcategory1");
+ SubCategoryDefinition subCategory2_2 = ElementFactory.getDefaultSubCategory();
+ subCategory2_2.setName("Subcategory2");
+ SubCategoryDefinition subCategory1_3 = ElementFactory.getDefaultSubCategory();
+ subCategory1_3.setName("Subcategory1");
+ SubCategoryDefinition subCategory2_3 = ElementFactory.getDefaultSubCategory();
+ subCategory2_3.setName("Subcategory2");
+
+ GroupingDefinition groupingDefinition1 = ElementFactory.getDefaultGroup();
+ groupingDefinition1.setName("Grouping1");
+ GroupingDefinition groupingDefinition11 = ElementFactory.getDefaultGroup();
+ groupingDefinition11.setName("Grouping11");
+ GroupingDefinition groupingDefinition12 = ElementFactory.getDefaultGroup();
+ groupingDefinition12.setName("Grouping12");
+ GroupingDefinition groupingDefinition22 = ElementFactory.getDefaultGroup();
+ groupingDefinition22.setName("Grouping22");
+
+ defaultCategories.get(0).getSubcategories().get(0).addGrouping(groupingDefinition11);
+ subCategory2.addGrouping(groupingDefinition12);
+ defaultCategories.get(0).addSubCategory(subCategory2);
+
+ defaultCategories.add(category2);
+ defaultCategories.add(category3);
+ category2.addSubCategory(subCategory1_2);
+ category2.addSubCategory(subCategory2_2);
+ subCategory1_2.addGrouping(groupingDefinition1);
+ subCategory2_2.addGrouping(groupingDefinition1);
+ category3.addSubCategory(subCategory1_3);
+ category3.addSubCategory(subCategory2_3);
+ subCategory1_3.addGrouping(groupingDefinition11);
+ subCategory2_3.addGrouping(groupingDefinition11);
+ subCategory2_3.addGrouping(groupingDefinition22);
+ return createCategoriesChain(defaultCategories);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java
new file mode 100644
index 0000000000..1820315841
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckinTest.java
@@ -0,0 +1,199 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+public class ProductCheckinTest extends ProductLifecycleTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ProductCheckinTest() {
+ super(name, ProductCheckinTest.class.getName());
+ }
+
+ @BeforeClass
+ public static void staticInit() {
+ auditAction = CHECKIN_ACTION;
+ operation = ComponentOperationEnum.CHANGE_STATE_CHECKIN;
+ }
+
+ @Test
+ public void checkInProductByCreator() throws Exception {
+
+ String checkinComment = "good checkin";
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN, checkinComment);
+ assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue());
+ Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(),
+ Product.class);
+
+ expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation);
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct,
+ auditAction, productManager1, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID());
+ expectedProductAudit.setCOMMENT(checkinComment);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT);
+ }
+
+ @Test
+ public void checkInProductByPM() throws Exception {
+
+ String checkinComment = "good checkin";
+ RestResponse response = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN, checkinComment);
+ assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue());
+
+ User checkoutUser = productManager2;
+ response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue());
+ expectedProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class);
+
+ DbUtils.cleanAllAudits();
+ checkinComment = "good checkin no 2";
+ response = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKIN,
+ checkinComment);
+ assertEquals("Check response code after checkin resource", 200, response.getErrorCode().intValue());
+
+ Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(response.getResponse(), Product.class);
+
+ expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ expectedProduct.setVersion("0.2");
+ expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId());
+ expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName());
+
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation);
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct,
+ auditAction, checkoutUser, ActionStatus.OK, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID());
+ expectedProductAudit.setCOMMENT(checkinComment);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT);
+ }
+
+ @Test
+ public void checkInProductByAdmin() throws Exception {
+
+ String checkinComment = "good checkin";
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, adminUser,
+ LifeCycleStatesEnum.CHECKIN, checkinComment);
+ assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue());
+ Product checkedInProduct = ResponseParser.parseToObjectUsingMapper(checkInResponse.getResponse(),
+ Product.class);
+
+ expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ expectedProduct.setLastUpdaterUserId(adminUser.getUserId());
+ expectedProduct.setLastUpdaterFullName(adminUser.getFullName());
+
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedInProduct, operation);
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedInProduct,
+ auditAction, adminUser, ActionStatus.OK, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, checkedInProduct.getUUID());
+ expectedProductAudit.setCOMMENT(checkinComment);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction, AuditJsonKeysEnum.COMMENT);
+ }
+
+ @Test
+ public void checkInProductByPMNotOwner() throws Exception {
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 403, checkInResponse.getErrorCode().intValue());
+ String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(),
+ productManager1.getLastName(), productManager1.getUserId() };
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productManager2, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.1", "0.1",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ expectedProduct.getUUID(), auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ @Test
+ public void checkInProductByPsRoleNotAllowed() throws Exception {
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productStrategistUser1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue());
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ expectedProduct.getUUID());
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ @Test
+ public void checkInProductNotExist() throws Exception {
+ String notExisitingUuid = "1234";
+ expectedProduct.setUniqueId(notExisitingUuid);
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 404, checkInResponse.getErrorCode().intValue());
+ String[] auditParameters = new String[] { "", "product" };
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING,
+ Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters);
+ expectedProductAudit.setCURR_STATE(Constants.EMPTY_STRING);
+ expectedProductAudit.setRESOURCE_NAME(notExisitingUuid);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ @Test
+ public void checkInProductAlreadyCheckedIn() throws Exception {
+ RestResponse checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 200, checkInResponse.getErrorCode().intValue());
+ DbUtils.cleanAllAudits();
+ checkInResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager2,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 409, checkInResponse.getErrorCode().intValue());
+ String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(),
+ productManager1.getLastName(), productManager1.getUserId() };
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productManager2, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ expectedProduct.getUUID(), auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java
new file mode 100644
index 0000000000..ec1f7ad38d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCheckoutTest.java
@@ -0,0 +1,146 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.FileNotFoundException;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+public class ProductCheckoutTest extends ProductLifecycleTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ @BeforeClass
+ public static void staticInit() {
+ auditAction = CHECKOUT_ACTION;
+ operation = ComponentOperationEnum.CHANGE_STATE_CHECKOUT;
+ }
+
+ public ProductCheckoutTest() {
+ super(name, ProductCheckoutTest.class.getName());
+ }
+
+ @Test
+ public void checkOutProductByPmNotInContacts() throws Exception {
+ checkOutProductSuccess(productManager2);
+ }
+
+ @Test
+ public void checkOutProductByPmInContacts() throws Exception {
+ checkOutProductSuccess(productManager1);
+ }
+
+ @Test
+ public void checkOutProductByAdmin() throws Exception {
+ checkOutProductSuccess(adminUser);
+ }
+
+ @Test
+ public void checkOutProductByPs() throws Exception {
+ // Changed in 1604 patch - now it's restricted
+ checkOutProductRestricted(productStrategistUser3);
+ // checkOutProductSuccess(productStrategistUser3);
+ }
+
+ @Test
+ public void checkOutProductByDesignerRoleNotAllowed() throws Exception {
+ checkOutProductRestricted(designerUser);
+ }
+
+ @Test
+ public void checkOutProductAlreadyCheckedOut() throws Exception {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue());
+ Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ DbUtils.cleanAllAudits();
+
+ lcsResponse = LifecycleRestUtils.changeProductState(checkedOutProduct, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkin resource", 403, lcsResponse.getErrorCode().intValue());
+ String[] auditParameters = new String[] { checkedOutProduct.getName(), "product", productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() };
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, productManager2, ActionStatus.COMPONENT_IN_CHECKOUT_STATE, "0.2", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID(), auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ private void checkOutProductSuccess(User checkoutUser) throws Exception, FileNotFoundException {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue());
+
+ // 0.1 is not highest now
+ RestResponse prevVersionProductResp = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productStrategistUser1.getUserId());
+ Product prevVersionProduct = ResponseParser.parseToObjectUsingMapper(prevVersionProductResp.getResponse(), Product.class);
+ Boolean falseParam = false;
+ assertEquals(falseParam, prevVersionProduct.isHighestVersion());
+
+ Product checkedOutProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ expectedProduct.setVersion("0.2");
+ expectedProduct.setLastUpdaterUserId(checkoutUser.getUserId());
+ expectedProduct.setLastUpdaterFullName(checkoutUser.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, checkedOutProduct, operation);
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(checkedOutProduct, auditAction, checkoutUser, ActionStatus.OK, "0.1", "0.2", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, checkedOutProduct.getUUID());
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ private void checkOutProductRestricted(User checkoutUser) throws Exception, FileNotFoundException {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin resource", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkin resource", 409, lcsResponse.getErrorCode().intValue());
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct, auditAction, checkoutUser, ActionStatus.RESTRICTED_OPERATION, "0.1", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, expectedProduct.getUUID());
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java
new file mode 100644
index 0000000000..ec3d9b75a5
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductComponentInstanceCRUDTest.java
@@ -0,0 +1,1437 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_MISSING_INFORMATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS_DELETE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_UNSUPPORTED_ERROR;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ProductComponentInstanceCRUDTest extends ComponentInstanceBaseTest {
+
+ protected ArtifactReqDetails heatArtifactDetails;
+ @Rule
+ public static TestName name = new TestName();
+
+ public ProductComponentInstanceCRUDTest() {
+ super(name, ProductComponentInstanceCRUDTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+ init();
+ createComponents();
+ }
+
+ private void createComponents() throws Exception {
+
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ createAtomicResource(resourceDetailsVFC_01);
+ changeResourceStateToCertified(resourceDetailsVFC_01);
+ createAtomicResource(resourceDetailsCP_01);
+ changeResourceStateToCertified(resourceDetailsCP_01);
+ createAtomicResource(resourceDetailsVL_01);
+ changeResourceStateToCertified(resourceDetailsVL_01);
+ createAtomicResource(resourceDetailsVFC_02);
+ changeResourceStateToCertified(resourceDetailsVFC_02);
+ createAtomicResource(resourceDetailsCP_02);
+ changeResourceStateToCertified(resourceDetailsCP_02);
+ createAtomicResource(resourceDetailsVL_02);
+ changeResourceStateToCertified(resourceDetailsVL_02);
+ createVF(resourceDetailsVF_02);
+ createVF(resourceDetailsVF_01);
+ // create check-In services
+ createService(serviceDetails_01);
+ createService(serviceDetails_02);
+ createService(serviceDetails_03);
+ createProduct(productDetails_01);
+ createProduct(productDetails_02);
+
+ // addresourceDetailsCP_02 ,resourceDetailsVFC_02 and
+ // resourceDetailsVL_02 to resourceDetailsVF_02 check-in VF
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02,
+ resourceDetailsVFC_02, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsCP_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVL_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ // addresourceDetailsCP_01 ,resourceDetailsVFC_01 and
+ // resourceDetailsVL_01 to resourceDetailsVF_01 and certify
+ // resourceDetailsVF_01
+ certifyVf(resourceDetailsVF_01);
+ createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); // serviceDetails_01
+ // has
+ // certified
+ // VF
+ createVFInstanceDuringSetup(serviceDetails_02, resourceDetailsVF_02, sdncDesignerDetails); // serviceDetails_02
+ // has
+ // check-in
+ // VF
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ }
+
+ // pass
+ @Test
+ public void createServiceInstanceTest() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ // DE189427
+ @Test(enabled = false)
+ public void createServiceInstanceFromCheckedOutState() throws Exception {
+ // can't create instance of checked-out component
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceInToAnotherServiceInstance() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String uniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
+ sdncPmDetails1, uniqueIdFromResponse, ComponentTypeEnum.PRODUCT);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_NOT_FOUND);
+ }
+
+ @Test
+ public void createSeveralServiceInstanceFromSameServices() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void createSeveralServiceInstanceFromDifferentServices() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void createCertifiedServiceInstance() throws Exception {
+ changeServiceStateToCertified(serviceDetails_01);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceByPm() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceWithoutVf() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_02, serviceDetails_03,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_02, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceByNonProductOwner() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails2);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceByNonAsdcUser() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ ;
+ nonExistingSdncUser.setUserId("bt1234");
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonExistingSdncUser);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceToNotCheckOutProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ // pass
+ @Test
+ public void createServiceInstanceNameIsEmpty() throws Exception {
+ String expectedServiceInstanceName = serviceDetails_01.getName() + " 1";
+ String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1";
+ serviceDetails_01.setName("");
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
+ "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(expectedServiceInstanceName, actualComponentInstance.getName());
+ assertEquals((expectedServiceInstancenormalizedName).toLowerCase(),
+ actualComponentInstance.getNormalizedName());
+ }
+
+ // pass
+ @Test
+ public void createServiceInstanceNameIsNull() throws Exception {
+ String expectedServiceInstanceName = serviceDetails_01.getName() + " 1";
+ String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "1";
+ serviceDetails_01.setName(null);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
+ "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
+ assertEquals("check Resource Instance normalizedName ", (expectedServiceInstancenormalizedName).toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", expectedServiceInstanceName, instanceName);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(expectedServiceInstanceName, actualComponentInstance.getName());
+ assertEquals((expectedServiceInstancenormalizedName).toLowerCase(),
+ actualComponentInstance.getNormalizedName());
+ }
+
+ @Test(enabled = false)
+ public void createServiceInstanceToNonExistingProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
+ sdncPmDetails1, "blabla", ComponentTypeEnum.PRODUCT);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ createServiceInstanceResp.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("blabla");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceToNonSupportedComponentType() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
+ sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.RESOURCE_INSTANCE);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("null");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales,
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ // pass
+ @Test
+ public void createServiceInstancePositionIsEmpty() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ serviceInstanceReqDetails.setPosX("");
+ serviceInstanceReqDetails.setPosY("");
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstancePositionIsNull() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ serviceInstanceReqDetails.setPosX(null);
+ serviceInstanceReqDetails.setPosY(null);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createServiceInstanceResp.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.PRODUCT);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceByDesigner() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncDesignerDetails);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void createServiceInstanceUserIdIsEmpty() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ nonSdncDetails.setUserId("");
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, nonSdncDetails);
+ assertTrue(createServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
+ createServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ //// Update Service instance
+
+ @Test
+ public void updateServiceInstanceNameByPm() throws Exception {
+ // Check-in Product by PM and Check-out by PM
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create service instance by PM
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "abcD";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", newName, instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(newName, actualComponentInstance.getName());
+ assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ @Test
+ public void updateServiceInstanceNewNameAndLocation() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "updaatedName100";
+ serviceInstanceReqDetails.setPosX("100");
+ serviceInstanceReqDetails.setPosY("100");
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
+ assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
+ assertEquals(newName, actualComponentInstance.getName());
+ assertEquals(newName.toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ @Test(enabled = false)
+ public void updateServiceInstanceNameRemoveSpacesFromBiginningAndEnd() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = " Abcd ";
+ String expectedNewName = " Abcd ";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (expectedNewName).toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", expectedNewName, instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(expectedNewName, actualComponentInstance.getName());
+ assertEquals((expectedNewName).toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ // pass
+ @Test
+ public void updateServiceInstanceNameAllowedCharacters() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "qwer-TYUIOP_asd_0987654321.Abcd";
+ String ExpectedNormalizName = "qwertyuiopasd0987654321abcd";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", ExpectedNormalizName, instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", newName, instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(newName, actualComponentInstance.getName());
+ assertEquals(ExpectedNormalizName, actualComponentInstance.getNormalizedName());
+
+ }
+
+ @Test
+ public void updateInstanceNameInvalidCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "Abcd1";
+ String updateName;
+ for (int i = 0; i < invalidChars.length; i++) {
+ updateName = newName + invalidChars[i];
+ serviceInstanceReqDetails.setName(updateName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(),
+ ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("Service Instance");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), varibales,
+ updateServiceInstanceResponse.getResponse());
+ }
+ }
+
+ // pass
+ @Test
+ public void updateInstanceNameMaxLength() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (newName).toLowerCase(), instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", newName, instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(newName, actualComponentInstance.getName());
+ assertEquals((newName).toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ @Test
+ public void updateInstanceNameExceedMaxLength() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String expectedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(), "name");
+ String expectedNormalizedName = ResponseParser.getValueFromJsonResponse(createServiceInstanceResp.getResponse(),
+ "normalizedName");
+ String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("Service Instance");
+ varibales.add("50");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), varibales,
+ updateServiceInstanceResponse.getResponse());
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(expectedName, actualComponentInstance.getName());
+ assertEquals(expectedNormalizedName, actualComponentInstance.getNormalizedName());
+ }
+
+ @Test
+ public void updateServiceInstanceNameEmpty() throws Exception {
+ // see US534663 In case a PS/PM removes the current service instance
+ // name then BE has to generate again the "default" service instance
+ // name
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(instanceName, actualComponentInstance.getName());
+ assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName());
+ }
+
+ // pass
+ @Test
+ public void updateServiceInstanceNameNull() throws Exception {
+ // see US534663 In case a PS/PM removes the current service instance
+ // name then BE has to generate again the "default" service instance
+ // name
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = null;
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + "2").toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance normalizedName ", (serviceDetails_01.getName() + " 2"), instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(instanceName, actualComponentInstance.getName());
+ assertEquals(instanceNormalizedName, actualComponentInstance.getNormalizedName());
+ }
+
+ @Test
+ public void updateServiceInstanceCheckedByOtherUser() throws Exception {
+ // see US534663 In case a PS/PM removes the current service instance
+ // name then BE has to generate again the "default" service instance
+ // name
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "blabla";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails2, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updateServiceInstanceResponse.getResponse());
+ }
+
+ @Test
+ public void updateServiceInstance_UserIdIsNonAsdcUser() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "blabla";
+ serviceInstanceReqDetails.setName(newName);
+ User nonSdncUserDetails = new User();
+ nonSdncUserDetails.setUserId("bt4567");
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, nonSdncUserDetails, productDetails_01.getUniqueId(),
+ ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updateServiceInstanceResponse.getResponse());
+ }
+
+ @Test
+ public void updateServiceInstanceNameToAlreadyExisting() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String ServiceName1 = ResponseParser.getNameFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(serviceInstanceReqDetails,
+ sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // Update service instance2 name to service instance1
+ serviceInstanceReqDetails.setName(ServiceName1);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("Service Instance");
+ varibales.add(ServiceName1);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales,
+ updateServiceInstanceResponse.getResponse());
+ }
+
+ @Test
+ public void updateServiceInstanceForNonExistingProduct() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "blabla";
+ serviceInstanceReqDetails.setName(newName);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, "blablabla", ComponentTypeEnum.PRODUCT);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
+ updateServiceInstanceResponse.getResponse());
+
+ }
+
+ @Test
+ public void updateNonExistingServiceInstance() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String newName = "blabla";
+ serviceInstanceReqDetails.setName(newName);
+ serviceInstanceReqDetails.setUniqueId("11111111");
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(newName);
+ varibales.add("service instance");
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ updateServiceInstanceResponse.getErrorCode().intValue());
+ // need to change ActionStatus.RESOURCE_INSTANCE_NOT_FOUND.name() to
+ // ActionStatus.SERVICE_INSTANCE_NOT_FOUND.name()
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND.name(), varibales,
+ updateServiceInstanceResponse.getResponse());
+ }
+
+ @Test
+ public void updateServiceInstanceLocation() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ serviceInstanceReqDetails.setPosX("50");
+ serviceInstanceReqDetails.setPosY("100");
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
+ assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
+ }
+
+ @Test
+ public void updateServiceInstanceToNonExistingLocation() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ String nameFromResponse = ResponseParser.getNameFromResponse(createServiceInstanceResp);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ serviceInstanceReqDetails.setPosX("-50");
+ serviceInstanceReqDetails.setPosY("-100");
+ serviceInstanceReqDetails.setName(nameFromResponse);
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
+ assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
+ assertEquals(nameFromResponse, actualComponentInstance.getName());
+ }
+
+ @Test
+ public void updateServiceInstanceLocationNameIsEmpty() throws Exception {
+ String expectedServiceInstanceName = serviceDetails_01.getName() + " 2";
+ String expectedServiceInstancenormalizedName = serviceDetails_01.getName() + "2";
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ serviceInstanceReqDetails.setPosX("100");
+ serviceInstanceReqDetails.setPosY("200");
+ serviceInstanceReqDetails.setName("");
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String nameFromResponse = ResponseParser.getNameFromResponse(updateServiceInstanceResponse);
+ String postX = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posX");
+ String postY = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "posY");
+ assertEquals(nameFromResponse, expectedServiceInstanceName);
+ assertEquals(postX, "100");
+ assertEquals(postY, "200");
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(serviceInstanceReqDetails.getPosX(), actualComponentInstance.getPosX());
+ assertEquals(serviceInstanceReqDetails.getPosY(), actualComponentInstance.getPosY());
+ assertEquals(nameFromResponse, actualComponentInstance.getName());
+ assertEquals(expectedServiceInstancenormalizedName.toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ // pass
+ @Test
+ public void updateServiceInstanceNameToProductName() throws Exception {
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_01);
+ RestResponse createServiceInstanceResp = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // ComponentInstance componentInstance =
+ // ResponseParser.parseToObjectUsingMapper(createServiceInstanceResp.getResponse(),
+ // ComponentInstance.class);
+ // addCompInstReqCapToExpected(componentInstance,
+ // ComponentTypeEnum.PRODUCT);
+ serviceInstanceReqDetails.setName(productDetails_01.getName());
+ RestResponse updateServiceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ResourceRestUtils.checkSuccess(updateServiceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateServiceInstanceResponse.getResponse(),
+ "name");
+ assertEquals("check Resource Instance normalizedName ", (serviceInstanceReqDetails.getName()).toLowerCase(),
+ instanceNormalizedName);
+ assertEquals("check Resource Instance Name ", serviceInstanceReqDetails.getName(), instanceName);
+ // get product and verify that service instanceName is correct
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ assertEquals(serviceInstanceReqDetails.getName(), actualComponentInstance.getName());
+ assertEquals((serviceInstanceReqDetails.getName()).toLowerCase(), actualComponentInstance.getNormalizedName());
+ }
+
+ //// Delete Service Instance
+
+ @Test
+ public void deleteAllServiceInstanceFromProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 0, 0);
+ }
+
+ @Test
+ public void deleteServiceWhileServiceInstanceExistInProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ // Delete service while service instance of it exist in product
+ RestResponse deleteServiceResponse = ServiceRestUtils.deleteServiceById(serviceDetails_01.getUniqueId(),
+ sdncDesignerDetails.getUserId());
+ assertTrue(deleteServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ // Get product and verify that service instance still exists
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ // ComponentInstance actualComponentInstance =
+ // actualProduct.getComponentInstances().get(0);
+ // assertTrue(serviceInstanceUniqueIdFromResponse ==
+ // actualComponentInstance.getUniqueId());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ // pass
+ @Test
+ public void deleteServiceInstanceByPm() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceByPmCreatedByPm() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceByPmWhichIsCheckedOutByAnotherPm() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails2);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ // DE190189
+ @Test
+ public void deleteServiceInstanceByPmCreatedByPs() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ String productOldUniqueId = productDetails_01.getUniqueId();
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get product and get service instance new uniquId
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPmDetails1.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ String serviceInstanceUniqueId = actualComponentInstance.getUniqueId();
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 0, 0);
+ }
+
+ // DE190189
+ @Test
+ public void deleteServiceInstanceByAdminCreatedByPs() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ String productOldUniqueId = productDetails_01.getUniqueId();
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ String productNewUniqueId = ResponseParser.getUniqueIdFromResponse(restResponse);
+ updateExpectedReqCapAfterChangeLifecycleState(productOldUniqueId, productNewUniqueId);
+ // get product and get service instance new uniquId
+ RestResponse getActualProductResponse = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncAdminDetails.getUserId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getActualProductResponse.getResponse(),
+ Product.class);
+ ComponentInstance actualComponentInstance = actualProduct.getComponentInstances().get(0);
+ String serviceInstanceUniqueId = actualComponentInstance.getUniqueId();
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncAdminDetails);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 0, 0);
+ }
+
+ @Test
+ public void createAndDeleteServiceInstanceByAdmin() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncAdminDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // productDetails_01.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncAdminDetails);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncAdminDetails);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncAdminDetails);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceFromNonCheckOutProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ RestResponse restResponse = LifecycleRestUtils.changeProductState(productDetails_01, sdncPmDetails1,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceByDesigner() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncDesignerDetails);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceByTester() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncTesterDetails);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceByPsWhichIsCheckedOutByAnotherPs() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPsDetails2);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ // pass
+ @Test
+ public void deleteServiceInstanceByNonAsdcUser() throws Exception {
+ User nonExistingSdncUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ ;
+ nonExistingSdncUser.setUserId("bt1234");
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ nonExistingSdncUser);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceFromNonExistingProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
+ "1234567890", serviceInstanceUniqueId, ComponentTypeEnum.PRODUCT);
+ assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
+ deleteResourceInstanceResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteNonExistingServiceInstanceFromProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ // String serviceInstanceUniqueId =
+ // ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
+ productDetails_01.getUniqueId(), "1234567890123456unExistingServiceInstance",
+ ComponentTypeEnum.PRODUCT);
+ assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("1234567890123456unExistingServiceInstance");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PRODUCT_NOT_FOUND.name(), varibales,
+ deleteResourceInstanceResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceFromNonSupportedComponentType() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
+ productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.RESOURCE_INSTANCE);
+ assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_UNSUPPORTED_ERROR);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("null");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.UNSUPPORTED_ERROR.name(), varibales,
+ deleteResourceInstanceResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceComponentTypeIsNotProduct() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncPmDetails1,
+ productDetails_01.getUniqueId(), serviceInstanceUniqueId, ComponentTypeEnum.SERVICE);
+ assertTrue(deleteResourceInstanceResponse.getErrorCode() == STATUS_CODE_NOT_FOUND);
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), varibales,
+ deleteResourceInstanceResponse.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteServiceInstanceUserIdIsEmpty() throws Exception {
+ User nonSdncDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ nonSdncDetails.setUserId("");
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ nonSdncDetails);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_MISSING_INFORMATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(),
+ deleteServiceInstanceResp.getResponse());
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ @Test
+ public void deleteCertifiedServiceInstance() throws Exception {
+ changeServiceStateToCertified(serviceDetails_01);
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(serviceInstanceUniqueId, productDetails_01,
+ sdncPmDetails1);
+ assertTrue(deleteServiceInstanceResp.getErrorCode() == STATUS_CODE_SUCCESS_DELETE);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ }
+
+ ////////////////////////////////////
+
+ private void certifyVf(ResourceReqDetails resource) throws Exception {
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ // Fixing Vl/Cp req/cap
+ ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE;
+ User user = sdncDesignerDetails;
+ fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType);
+ consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType);
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails,
+ sdncDesignerDetails, resource.getUniqueId());
+ ResourceRestUtils.checkSuccess(response);
+ RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource);
+ ResourceRestUtils.checkSuccess(changeResourceStateToCertified);
+ }
+
+ private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponse;
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponse.getErrorCode() == 200) {
+ String newVersion = ResponseParser.getVersionFromResponse(restResponse);
+ resourceDetails.setVersion(newVersion);
+ resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId());
+ resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(),
+ "uniqueId");
+ resourceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponse;
+ }
+
+ private RestResponse changeServiceStateToCertified(ServiceReqDetails serviceDetails) throws Exception {
+ /*
+ * RestResponse restResponse =
+ * LifecycleRestUtils.changeServiceState(serviceDetails,
+ * sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ * ResourceRestUtils.checkSuccess(restResponse);
+ */
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponse;
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponse.getErrorCode() == 200) {
+ serviceDetails.setVersion("1.0");
+ serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ serviceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId());
+ serviceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(),
+ "uniqueId");
+ serviceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponse;
+ }
+
+ @Test
+ public void deleteServiceInstanceTest() throws Exception {
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+
+ createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_02, sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 2, 0);
+ String compInstId2 = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+
+ RestResponse deleteServiceInstanceResp = deleteServiceInstance(compInstId, productDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 1, 0);
+
+ deleteServiceInstanceResp = deleteServiceInstance(compInstId2, productDetails_01, sdncPmDetails1);
+ ResourceRestUtils.checkDeleteResponse(deleteServiceInstanceResp);
+ getComponentAndValidateRIs(productDetails_01, 0, 0);
+ }
+
+ @Test
+ public void returnedServiceInstanceTypeAttributeTest() throws Exception {
+ String expectedServiceType = ComponentTypeEnum.SERVICE.getValue().toUpperCase();
+
+ RestResponse createServiceInstanceResp = createServiceInstance(productDetails_01, serviceDetails_01,
+ sdncPmDetails1);
+ ResourceRestUtils.checkCreateResponse(createServiceInstanceResp);
+ String serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(createServiceInstanceResp);
+ ComponentInstanceRestUtils.checkComponentInstanceType(createServiceInstanceResp, expectedServiceType);
+
+ RestResponse getProductResp = ProductRestUtils.getProduct(productDetails_01.getUniqueId(),
+ sdncPsDetails1.getUserId());
+ ProductRestUtils.checkSuccess(getProductResp);
+ Product productObject = ResponseParser.parseToObjectUsingMapper(getProductResp.getResponse(), Product.class);
+ List<ComponentInstance> productComponentInstances = productObject.getComponentInstances();
+ for (ComponentInstance comp : productComponentInstances) {
+ String actualOriginType = comp.getOriginType().getValue().toUpperCase();
+ assertTrue(expectedServiceType.equals(actualOriginType));
+ }
+
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails_02);
+ serviceInstanceReqDetails.setUniqueId(serviceUniqueIdFromResponse);
+ serviceInstanceReqDetails.setComponentUid(serviceDetails_01.getUniqueId());
+ RestResponse updateResourceInstance = ComponentInstanceRestUtils.updateComponentInstance(
+ serviceInstanceReqDetails, sdncPmDetails1, productDetails_01.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ ComponentInstanceRestUtils.checkSuccess(updateResourceInstance);
+ ComponentInstanceRestUtils.checkComponentInstanceType(updateResourceInstance, expectedServiceType);
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java
new file mode 100644
index 0000000000..d2c2dfe77f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCreateWithValidationsTest.java
@@ -0,0 +1,1710 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.Arrays;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.Test;
+
+public class ProductCreateWithValidationsTest extends ProductBaseTest {
+ @Rule
+ public static TestName name = new TestName();
+
+ public static String INITIAL_PRODUCT_VERSION = "0.1";
+ public static String CREATE_AUDIT_ACTION = "Create";
+ public String normalizedName;
+
+ public ProductCreateWithValidationsTest() {
+ super(name, ProductCreateWithValidationsTest.class.getName());
+ }
+
+ @Test
+ public void createProductSuccessValidation() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNotByPmUser() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productStrategistUser1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION,
+ productStrategistUser1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productStrategistUser1, ActionStatus.RESTRICTED_OPERATION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNotByAsdcUser() throws Exception {
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ nonAsdcUser.setUserId("bt750k");
+ nonAsdcUser.setFirstName(null);
+ nonAsdcUser.setLastName(null);
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION,
+ nonAsdcUser);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.RESTRICTED_OPERATION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductUserIdIsEmpty() throws Exception {
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ nonAsdcUser.setUserId("");
+ nonAsdcUser.setFirstName(null);
+ nonAsdcUser.setLastName(null);
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, nonAsdcUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION,
+ nonAsdcUser);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, nonAsdcUser, ActionStatus.MISSING_INFORMATION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationLessThanMinCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Pro");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING, "Product", "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationMaxLength() throws Exception {
+ // Max length = 25
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Qwertyuiop1234567890asdfA");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationExceedMaxLength() throws Exception {
+ // Max length = 25
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Qwertyuiop1234567890asdfAa");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING, "Product", "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationEmptyName() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product",
+ "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameAlreadyExist() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ // productReqDetails.setName("ProDuct1");
+ DbUtils.deleteFromEsDbByPattern("_all");
+ createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS,
+ createProduct.getErrorCode().intValue());
+ productReqDetails.setVersion("0.1");
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_NAME_ALREADY_EXIST,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product",
+ productReqDetails.getName());
+ constructFieldsForAuditValidation.setCURR_VERSION("0.1");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ constructFieldsForAuditValidation.setCURR_STATE("NOT_CERTIFIED_CHECKOUT");
+ constructFieldsForAuditValidation.setSERVICE_INSTANCE_ID(null);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationNameIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product",
+ "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ // DE193857
+ @Test(enabled = false)
+ public void createProductNameValidationAllowedCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Ac_2@3:4& m=n+b-u.j-u'g#b"); // Bug @:&=+'#
+ normalizedName = "ac234mnbujugb";
+ String expectedProductName = "Ac_2@3:4& M=n+b-u.j-u'g#b";
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ productReqDetails.setName(expectedProductName);
+ productReqDetails.setName("Ac_2@3:4& M=n+b-u.j-u'g#b");
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setNormalizedName(normalizedName);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ // DE193857
+ @Test(enabled = false)
+ public void createProductNameValidationREmoveExtraNonAlphanumericChars() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Ac____222----333......asd");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setName("Ac_222-333.asd");
+ normalizedName = "ac222333asd";
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationNotAllowedCharacters() throws Exception {
+ ExpectedProductAudit constructFieldsForAuditValidation;
+ char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|',
+ '\\', ',', '$' };
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("abc" + invalidChars[i]);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "",
+ productManager1);
+ constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product",
+ "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+ }
+
+ @Test
+ public void createProductFullNameContainSpecialCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|',
+ '\\', ',', '$' };
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ for (int i = 0; i < invalidChars.length; i++) {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ productReqDetails.setFullName("abc" + invalidChars[i]);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED,
+ createProduct.getErrorCode().intValue());
+ RestResponse deleteProduct = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS,
+ deleteProduct.getErrorCode().intValue());
+ }
+ }
+
+ @Test(enabled = false)
+ public void createProductNameValidationRemoveSpaceFromBeginning() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName(" Qwertyuiop1234567890asdfA");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim()));
+ normalizedName = productReqDetails.getName().trim().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test(enabled = false)
+ public void createProductNameValidationRemoveSpaceFromTheEnd() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Qwertyuiop1234567890asdfA ");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim()));
+ normalizedName = productReqDetails.getName().trim().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationStartWithNumber() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("1Qwert");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim()));
+ normalizedName = productReqDetails.getName().trim().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationStartWithNonAlphaNumeric() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("_Qwert");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName().trim()));
+ normalizedName = productReqDetails.getName().trim().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING, "Product", "abbreviated");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductNameValidationFirstLetterOfKeyWordsCapitalized() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ // productReqDetails.setTags(Arrays.asList("abba"));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ // productReqDetails.setName("Abba");
+ /*
+ * String actualNormalizedNameFromResponse =
+ * ResponseParser.getValueFromJsonResponse(createProduct.getResponse(),
+ * "normalizedName");
+ * assertTrue(actualNormalizedNameFromResponse.equals(normalizedName));
+ */
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameValidationIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setFullName("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameValidationIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setFullName("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "full");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameLessThanMinLength() throws Exception {
+ // Min is 4 characters
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setFullName("abc");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING, "Product", "full");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameHasMinLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setFullName("abcd");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameHasMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setFullName(
+ "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameExceedMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setFullName(
+ "Abba1234567890asdfghjk l123zxcvbnm432adfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.123");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1,
+ ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING, "Product", "full");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductFullNameRemoveExtraSpaces() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setFullName("Abbaaa a1");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setFullName("Abbaaa a1");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionValidationIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setDescription("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionValidationIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setDescription(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_DESCRIPTION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionValidCharacters01() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890<b>Bold<</b>");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold&lt;");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionValidCharacters02() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setDescription("~!@#$%^&amp;*()_+&lt;&gt;?qwertyuiopasdfghjklzxcvbnm1234567890#");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionInValidCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription("מה");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_DESCRIPTION,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionRemoveSpacesFromBeginning() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription(" abcd12345");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setDescription("abcd12345");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionRemoveSpacesFromTheEnd() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription("abcd 12345 xcvb ");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setDescription("abcd 12345 xcvb");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription(
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDescriptionExceedMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setDescription(
+ "Abxba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12Abba1234567890asdfghjkl123zxcvbnm432asdfghjkl_-.123Abba1234567890asdfghjkl23zxcvbnm432asdfghjkl_-.12asdfghjklzxcvbnmqwertyui");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "1024");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductTagIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product");
+ productReqDetails.setTags(Arrays.asList(""));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_FIELD_FORMAT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "tag");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ // DE192351
+ @Test
+ public void createProductTagValidationAllowedCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Acde2@3:4& m=n+b-u.j-u'g#b"));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductTagsNameValidationProductNameIsNotInTag() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Qwertyuiop1234567890asdfA");
+ productReqDetails.setTags(Arrays.asList("Abc"));
+ normalizedName = productReqDetails.getName().trim().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductSingleTagMaxLength() throws Exception {
+ // SingleTagMaxLength = 50
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(
+ Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678"));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductSingleTagExceedMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(
+ Arrays.asList(productReqDetails.getName(), "Axbba1234567890asdfghjkl123zxcvbnm432asdfgh12345678"));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "50");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductAllTagsMaxLength() throws Exception {
+ // AllTagsMaxLength = 1024
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(
+ Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345"));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductAllTagsExceedMaxLength() throws Exception {
+ // AllTagsMaxLength = 1024
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(
+ Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456"));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "1024");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductDuplicateTagRemoved() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductContactsIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ productReqDetails.setContacts(Arrays.asList(""));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductContactsInvalidFormat() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ productReqDetails.setContacts(Arrays.asList("bt750345"));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_CONTACT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductConvertContactsToLowerCase() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toUpperCase()));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setContacts(Arrays.asList(productManager1.getUserId().toLowerCase()));
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductContactsDoexNotContainTheProductCreator() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ productReqDetails.setContacts(Arrays.asList(productManager2.getUserId()));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setContacts(Arrays.asList(productManager2.getUserId(), productManager1.getUserId()));
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductContactsNotAllowedAsdcUsers() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ productReqDetails.setContacts(Arrays.asList(designerUser.getUserId()));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING,
+ designerUser.getUserId());
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductContactsNotAsdcUser() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1"); // Bug @:&=+'#
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase();
+ String nonAsdcUser = "bh1234";
+ productReqDetails.setContacts(Arrays.asList(nonAsdcUser));
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PRODUCT_CONTACT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, nonAsdcUser);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.MISSING_PROJECT_CODE,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeIsNotNumeric() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("asdfgh");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeHasnMinCharacters() throws Exception {
+ // Min =5
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("12345");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeHasnMaxCharacters() throws Exception {
+ // Max =10
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("1234567890");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeExceedMaxCharacters() throws Exception {
+ // Max =10
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("12345678901");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductProjectCodeLessThanMinCharacters() throws Exception {
+ // Max =10
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setProjectCode("1234");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_PROJECT_CODE,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconIsEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setIcon("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setIcon(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_MISSING_ICON,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconExceedMaxLength() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setIcon("asdfghjklqwertyuiozxcvbf12");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product", "25");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconAllowedCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setIcon("a--s-fghjk_q__r1234567890");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIconInValidCharacters() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ String icon = "asdfg";
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+ RestResponse createProduct;
+ for (int i = 0; i < invalidChars.length; i++) {
+ productReqDetails.setIcon(icon + invalidChars[i]);
+ createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "",
+ productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.COMPONENT_INVALID_ICON,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, "Product");
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+ }
+
+ @Test
+ public void createProductIsActiveisEmpty() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setActive("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setActive("false");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIsActiveisNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setActive("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ productReqDetails.setActive("false");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIsActiveisFalse() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setActive("false");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIsActiveisHasInvalidValue() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setActive("xfalse");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT,
+ createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "", productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT,
+ Constants.EMPTY_STRING, Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ constructFieldsForAuditValidation.setRESOURCE_NAME("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test
+ public void createProductIsActiveisTrue() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Product1");
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ productReqDetails.setActive("true");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ //////////////////////////////////////////////
+ // DE192424
+ @Test
+ public void createProductNameValidationNormalizationNameWithSpaces() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setName("Abba Emma");
+ // productReqDetails.setName("abba emma");
+ // productReqDetails.setTags(Arrays.asList("abba emma"));
+ normalizedName = productReqDetails.getName().toLowerCase().replaceAll("\\s+", "");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ String actualNormalizedNameFromResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(),
+ "normalizedName");
+ assertTrue(actualNormalizedNameFromResponse.equals(normalizedName));
+ // productReqDetails.setName("Abba Emma");
+ String productUuid = ResponseParser.getUuidFromResponse(createProduct);
+ compareExpectedAndActualProducts(productReqDetails, createProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProductRes);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(
+ expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING,
+ "0.1", null, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, productUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ private void compareExpectedAndActualProducts(ProductReqDetails productReqDetails, RestResponse createProduct)
+ throws JSONException {
+ String productName = ResponseParser.getNameFromResponse(createProduct);
+ assertTrue(productReqDetails.getName().equals(productName));
+ String productIcon = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "icon");
+ assertTrue(productReqDetails.getIcon().equals(productIcon));
+ String productFullName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "fullName");
+ assertTrue(productReqDetails.getFullName().equals(productFullName));
+ String productProjectCode = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "projectCode");
+ assertTrue(productReqDetails.getProjectCode().equals(productProjectCode));
+ String productIsActive = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "isActive");
+ String expectedIsActive = (productReqDetails.getActive() != null ? productReqDetails.getActive() : "false");
+ assertTrue(productIsActive.equals(expectedIsActive));
+ String productdescription = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "description");
+ assertTrue(productReqDetails.getDescription().equals(productdescription));
+ String productNormalizedName = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(),
+ "normalizedName");
+ assertTrue(normalizedName.equals(productNormalizedName));
+ String productContacts = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "contacts");
+ JSONArray reciviedContacts = new JSONArray(productContacts);
+ String actualContact = null;
+ for (int i = 0; i < reciviedContacts.length(); i++) {
+ actualContact = reciviedContacts.getString(i);
+ assertEquals(productReqDetails.getContacts().get(i), actualContact);
+ }
+ String productTags = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "tags");
+ JSONArray reciviedTages = new JSONArray(productTags);
+ String actualTag = null;
+ for (int i = 0; i < reciviedTages.length(); i++) {
+ actualTag = reciviedTages.getString(i);
+ assertEquals(productReqDetails.getTags().get(i), actualTag);
+ }
+ }
+
+ // END
+ ///////////////////////////////////////////////////////
+ @Test
+ public void createProductSuccessFlow() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED,
+ createProduct.getErrorCode().intValue());
+
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS,
+ getProductRes.getErrorCode().intValue());
+
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(false));
+ }
+
+ @Test
+ public void createProductSetIsActive() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setActive("true");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED,
+ createProduct.getErrorCode().intValue());
+
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(),
+ productManager1.getUserId());
+ assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS,
+ getProductRes.getErrorCode().intValue());
+
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct,
+ ComponentOperationEnum.GET_COMPONENT);
+ assertEquals(actualProduct.getIsActive(), new Boolean(true));
+ }
+
+ @Test
+ public void createProductNoIcon() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setIcon(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA,
+ createProduct.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createProductNoProjectCode() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ productReqDetails.setProjectCode(null);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_DATA,
+ createProduct.getErrorCode().intValue());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java
new file mode 100644
index 0000000000..f234708b7a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductCrudTest.java
@@ -0,0 +1,2197 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public class ProductCrudTest extends ProductBaseTest {
+ private static Logger log = LoggerFactory.getLogger(ProductCrudTest.class.getName());
+ @Rule
+ public static TestName name = new TestName();
+
+ public static String INITIAL_PRODUCT_VERSION = "0.1";
+ public static String CREATE_AUDIT_ACTION = "Create";
+ public static String UPDATE_AUDIT_ACTION = "Update";
+ public static String COMPONENT_TYPE = "Product";
+
+ private ProductReqDetails productReqDetails;
+ private RestResponse createProduct;
+ private Product product;
+
+ public ProductCrudTest() {
+ super(name, ProductCrudTest.class.getName());
+ }
+
+ @Test // (enabled=false)
+ public void createAndGetAll() throws Exception {
+ createProductAndGet(UserRoleEnum.DESIGNER);
+ }
+
+ private void createProductAndGet(UserRoleEnum user) throws Exception, IOException {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+
+ RestResponse catalog = CatalogRestUtils.getCatalog(user.getUserId());
+ assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, catalog.getErrorCode().intValue());
+
+ try {
+ JsonElement jElement = new JsonParser().parse(catalog.getResponse());
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonArray products = (JsonArray) jObject.get("products");
+ assertEquals("Check product array size", 1, products.size());
+ Iterator<JsonElement> iter = products.iterator();
+ while (iter.hasNext()) {
+ JsonElement next = iter.next();
+ Product product = ResponseParser.parseToObjectUsingMapper(next.toString(), Product.class);
+ assertNotNull(product);
+ assertEquals("Check product name", productReqDetails.getName(), product.getName());
+ // Map<String, String> allVersions = product.getAllVersions();
+ // assertEquals("Check product name", 1, allVersions.size());
+ }
+
+ } catch (Exception e) {
+ log.debug("exception", e);
+ }
+ }
+
+ @Test
+ public void getAllNoProcduts() throws Exception {
+
+ RestResponse catalog = CatalogRestUtils.getCatalog();
+ assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_SUCCESS, catalog.getErrorCode().intValue());
+
+ try {
+ JsonElement jElement = new JsonParser().parse(catalog.getResponse());
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonArray products = (JsonArray) jObject.get("products");
+ assertEquals("Check product array size", 0, products.size());
+ } catch (Exception e) {
+ log.debug("exception", e);
+ }
+
+ }
+
+ @Test
+ public void getAllNoAttHeader() throws Exception {
+ String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ List<String> headersToRemove = new ArrayList<String>();
+ headersToRemove.add(HttpHeaderEnum.USER_ID.getValue());
+
+ RestResponse catalog = CatalogRestUtils.sendGetAndRemoveHeaders(url, null, headersToRemove);
+ assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, catalog.getErrorCode().intValue());
+
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(), catalog.getResponse());
+ }
+
+ @Test
+ public void getAllWrongUser() throws Exception {
+ RestResponse catalog = CatalogRestUtils.getCatalog("kj8976");
+ assertEquals("Check response code after get catalog", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, catalog.getErrorCode().intValue());
+
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), catalog.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void getAllWithProductStrategist_User() throws Exception {
+ createProductAndGet(UserRoleEnum.PRODUCT_STRATEGIST1);
+ }
+
+ @Test // (enabled=false)
+ public void getAllWithProductManager_User() throws Exception {
+ createProductAndGet(UserRoleEnum.PRODUCT_MANAGER1);
+ }
+
+ @Test // (enabled=false)
+ public void createProductNoCategories() throws Exception {
+ createProductWithCategories(null);
+ }
+
+ @Test // (enabled=false)
+ public void createProductOneGrouping() throws Exception {
+ // Category1->[Subcategory1->[Grouping1]]
+ createProductWithCategories(defaultCategories);
+ }
+
+ @Test // (enabled=false)
+ public void createProductTwoGroupingsSameSubCategory() throws Exception {
+ // Category1->Subcategory1->[Grouping1, Grouping11]
+ List<CategoryDefinition> addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory();
+ createProductWithCategories(addSecondGroupingToDefaultCategory);
+ }
+
+ @Test // (enabled=false)
+ public void createProductTwoSubsDifferentGroupings() throws Exception {
+ // Category1->[Subcategory1->[Grouping1,
+ // Grouping11],Subcategory2->[Grouping12]]
+ List<CategoryDefinition> addSubcategoryAndGroupingToDefaultCategory = addSubcategoryAndGroupingToDefaultCategory();
+ createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory);
+ }
+
+ @Test // (enabled=false)
+ public void createManyGroupingsDiffCategories() throws Exception {
+ // [Category1->[Subcategory1->[Grouping1,
+ // Grouping11],Subcategory2->[Grouping12]],
+ // Category2->[Subcategory1->[Grouping1],Subcategory2->[Grouping1]],
+ // Category3->[Subcategory1->[Grouping11],Subcategory2->[Grouping11,
+ // Grouping22]]]
+ List<CategoryDefinition> addSubcategoryAndGroupingToDefaultCategory = addManyGroupingsDiffCategories();
+ createProductWithCategories(addSubcategoryAndGroupingToDefaultCategory);
+ }
+
+ @Test // (enabled=false)
+ public void createProductEmptyUserId() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ User emptyUser = new User();
+ emptyUser.setUserId("");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, emptyUser);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, emptyUser);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, emptyUser, ActionStatus.MISSING_INFORMATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null,
+ null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test // (enabled=false)
+ public void createProductNonExistingUserId() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ User notExistingUser = new User();
+ notExistingUser.setUserId("jj6444");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, notExistingUser);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, notExistingUser);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, notExistingUser, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING,
+ null, null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test // (enabled=false)
+ public void createProductInvalidJson() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct_Invalid_Json(productManager1.getUserId());
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, productManager1);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.INVALID_CONTENT, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null,
+ null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setRESOURCE_NAME("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test // (enabled=false)
+ public void createProductAdminRoleNotAllowed() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, wrongRole);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null,
+ null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test // (enabled=false)
+ public void createProductProductStrategistRoleNotAllowed() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ User wrongRole = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST3);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, wrongRole);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, createProduct.getErrorCode().intValue());
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, wrongRole);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, wrongRole, ActionStatus.RESTRICTED_OPERATION, Constants.EMPTY_STRING, Constants.EMPTY_STRING, null,
+ null, Constants.EMPTY_STRING);
+ constructFieldsForAuditValidation.setCURR_VERSION("");
+ constructFieldsForAuditValidation.setCURR_STATE("");
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ @Test // (enabled=false)
+ public void getProductSuccessFlow() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue());
+
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.GET_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void getNonExistedProduct() throws Exception {
+
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after getting created Product", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue());
+
+ Product product = ResponseParser.parseToObjectUsingMapper(getProductRes.getResponse(), Product.class);
+ assertEquals("Assert on product icon", "Product1", product.getName());
+
+ RestResponse deleteProductRes = ProductRestUtils.deleteProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code for deletign Product", BaseRestUtils.STATUS_CODE_SUCCESS, deleteProductRes.getErrorCode().intValue());
+
+ RestResponse getProductAfterDeleteRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after getting deleted Product", BaseRestUtils.STATUS_CODE_NOT_FOUND, getProductAfterDeleteRes.getErrorCode().intValue());
+ }
+
+ @Test // (enabled=false)
+ public void getProductMissingHeader() throws Exception {
+
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+
+ productManager1.setUserId(null);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after getting created Producuct with userId extracted from header", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, getProductRes.getErrorCode().intValue());
+
+ }
+
+ @Test // (enabled=false)
+ public void getProductNonExistingUser() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+
+ productManager1.setUserId("bt1111");
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after getting created Producuct with non exsisting user", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, getProductRes.getErrorCode().intValue());
+ }
+
+ @Test // (enabled=false)
+ public void createProductAndGetProductWithDifferentUser() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ User sdncProductStrategistUserAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), sdncProductStrategistUserAdminDetails.getUserId());
+ assertEquals("Check response code after getting created Product different user role", BaseRestUtils.STATUS_CODE_SUCCESS, getProductRes.getErrorCode().intValue());
+ }
+
+ // US594753 - Update Product metadata
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductAllFieldsByPM() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ // Update product
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("NewProductName");
+ List<CategoryDefinition> addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory();
+ productReqDetails.setFullName("New Full name");
+ productReqDetails.setActive("false");
+ productReqDetails.setContacts(Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId().toLowerCase()));
+ productReqDetails.setDescription("New Product Description");
+ productReqDetails.setIcon("asdfghjklqwertyuiozxcvbfv");
+ productReqDetails.setProjectCode("98765");
+ productReqDetails.setCategories(addSecondGroupingToDefaultCategory);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(),
+ // productOldName));
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductByPS() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("New discription");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productStrategistUser1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void updateProductByAdmin() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("New discription");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void updateProductByNonPmUser() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ // Update product name
+ productReqDetails.setDescription("New discription");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, designerUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void updateProductByNonAsdcUser() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ // Update product name
+ productReqDetails.setDescription("New discription");
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ nonAsdcUser.setUserId("bt789k");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void updateProductUserIdIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ // Update product name
+ productReqDetails.setDescription("New discription");
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ nonAsdcUser.setUserId("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, nonAsdcUser);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_MISSING_INFORMATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void updateProductByNonProductOwner() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("New discription");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.GET_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNotInCheckoutState() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ // Update product name
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(), updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(changeProductLifeCycle.getResponse(), "lastUpdateDate");
+ expectedProduct.setLastUpdateDate(Long.parseLong(valueFromJsonResponse));
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("abbreviated");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ // List<String> tags = productReqDetails.getTags();
+ // tags.removeAll(tags);
+ productReqDetails.setTags(new ArrayList<>());
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName(null); // no update will be performed
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2);
+ ProductRestUtils.checkSuccess(updateProduct);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(product.getName().toLowerCase());
+ expectedProduct.setName(product.getName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameLessThanMinLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("ABC"); // no update will be performed
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("abbreviated");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameHasMinLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("NewP");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ productReqDetails.setLastUpdaterUserId(productManager2.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager2.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager2);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ // DE193857 - Normalized Name is not removing special characters
+ @Test(enabled = false)
+ public void updateProductNameMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ // Update product name
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgP");
+ String newNormalizedName = "ac2b3u4kmsknobujuggp";
+ String newName = "Ac_2B3U4k MSKnob-u.j-uGgP";
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setTags(Arrays.asList(newName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(newName);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("Ac_2B3U4k mSKnob-u.j-uGgPx");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("abbreviated");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameAlreadyExist() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product1 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product1, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setName("CiProduct2000");
+ // productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ createProduct = ProductRestUtils.createProduct(productReqDetails, productManager2);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product2 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product2, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product2.getUniqueId());
+ productReqDetails.setUUID(product2.getUUID());
+ productReqDetails.setName(product1.getName());
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager2);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_ALREADY_EXISTS, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add(product1.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager2.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product2.getUniqueId());
+ expectedProduct.setVersion(product2.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // DE193857 - Normalized Name is not removing special characters
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameAllowedCharacters() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ // Update product name
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("A_BU4k m&K=o#b-u.j-uG'g+P"); // Allowed
+ // characters
+ // [a-z,A-Z,0-9]
+ // , ‘ ‘
+ // (space),
+ // ampersand
+ // dash
+ // “-“, plus
+ // "+", period
+ // ".",
+ // apostrophe
+ // "'", hashtag
+ // "#", equal
+ // "=", period
+ // ":", at "@",
+ // and
+ // underscore
+ //
+ String newNormalizedName = "abu4km&kobujuggp";
+ String newName = "A_BU4k M&K=o#b-u.j-uG'g+P";
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setTags(Arrays.asList(newName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(newName);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameRemoveSpaceFromBeginning() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName(" asdfg");
+ String newNormalizedName = "asdfg";
+ String newName = "Asdfg";
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // productReqDetails.setTags(Arrays.asList(newName, productOldName));
+ productReqDetails.setTags(Arrays.asList(newName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(newName);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameRemoveSpaceFromEnd() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("asdfg fc ");
+ String newNormalizedName = "asdfgfc";
+ String newName = "Asdfg Fc";
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // productReqDetails.setTags(Arrays.asList(newName, productOldName));
+ productReqDetails.setTags(Arrays.asList(newName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(newName);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ //// DE193857 - Normalized Name is not removing special characters
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameRemoveExtraNonAlphanumericChars() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("A__k &&==##---u..hG'''+++");
+ String newNormalizedName = "akhg";
+ String newName = "A_k &=#-u.hG'+";
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // productReqDetails.setTags(Arrays.asList(newName, productOldName));
+ productReqDetails.setTags(Arrays.asList(newName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(newName);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // If user update Product Name we need to remove the old product name from
+ // Tags and add the new product name instead - will be handled in new US
+ @Test(enabled = false)
+ public void updateProductNameValidationStartWithNumber() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("1000Ab");
+ String newNormalizedName = productReqDetails.getName().toLowerCase();
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName()));
+ // productReqDetails.setTags(Arrays.asList(productReqDetails.getName(),
+ // productOldName));
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setNormalizedName(newNormalizedName);
+ expectedProduct.setName(productReqDetails.getName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductNameValidationStartWithNonAlphaNumeric() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setName("_1000Ab");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("abbreviated");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_FORMAT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("full");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_ONE_OF_COMPONENT_NAMES.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setNormalizedName(product.getNormalizedName());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setFullName(product.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameHasMinLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("asdc");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setNormalizedName(product.getNormalizedName());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setFullName(productReqDetails.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameHasMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setNormalizedName(product.getNormalizedName());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setFullName(productReqDetails.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNamelessThanMinLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("123");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("full");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjkx");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("full");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ELEMENT_INVALID_NAME_LENGTH.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ // DE193947
+ @Test
+ public void updateProductFullNameWithSpecialCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',', '$', '#', '@', '+' };
+ String fullName = "avbng";
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ for (int i = 0; i < invalidChars.length; i++) {
+ productReqDetails.setFullName(fullName + invalidChars[i]);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, updateProduct.getErrorCode().intValue());
+ }
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameValidCharactersCharacters01() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890<b>Bold<</b>");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setNormalizedName(product.getNormalizedName());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setFullName("qwertyuiopasdfghjklzxcvbnm1234567890Bold&lt;");
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductFullNameRemoveExtraSpaces() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setFullName("Abbaaa a1");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setNormalizedName(product.getNormalizedName());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setFullName("Abbaaa a1");
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test(enabled = false)
+ public void updateProductDescriptionValidCharacters01() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("~!@#$%^&*()_+<>?qwertyuiopasdfghjklzxcvbnm1234567890#");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setDescription("~!@#$%^&amp;*()_+&lt;&gt;?qwertyuiopasdfghjklzxcvbnm1234567890#");
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionValidCharacters02() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890<b>Bold<</b>");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setDescription("qwertyuiopasdfghjklzxcvbnm1234567890Bold&lt;");
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionInValidCharacters() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("מה");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_DESCRIPTION.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionRemoveSpacesFromBeginning() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription(" abcd12345 g");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setDescription("abcd12345 g");
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionRemoveSpacesFromTheEnd() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setDescription("abcd12345 gdf ");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setDescription("abcd12345 gdf");
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ String description = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg";
+ productReqDetails.setDescription(description);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setDescription(description);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductDescriptionExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ String description = "01234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjk aa1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfghjklzxcvbnm1234567890qwertyuiopasdfg";
+ productReqDetails.setDescription(description);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("1024");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductTagIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(""));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ varibales.add("tag");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductTagIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setTags(product.getTags());
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductTagsNameValidationProductNameIsNotInTag() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList("Abc"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name(), new ArrayList<String>(), updateProduct.getResponse());
+ }
+
+ @Test // (enabled=false)
+ public void createProductSingleTagMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345678"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setTags(productReqDetails.getTags());
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductSingleTagExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456788"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("50");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductAllTagsMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setTags(productReqDetails.getTags());
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductAllTagsExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345601", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345602", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345603",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345604", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345605", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345606", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345607",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345608", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh1234569", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345610", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345611",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345612", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345613", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345614", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345615",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345616", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345617", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345618", "Abba1234567890asdfghjkl123zxcvbnm432asdfgh12345619",
+ "Abba1234567890asdfghjkl123zxcvbnm432asdfgh123456"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add("1024");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductTagsDuplicateTagRemoved() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setTags(Arrays.asList(productReqDetails.getName(), "KoKo", "KoKo"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata updated
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setTags(Arrays.asList(productReqDetails.getName(), "KoKo"));
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductContactsIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setContacts(Arrays.asList(""));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductContactsIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setContacts(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductContactsInvalidFormat() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setContacts(Arrays.asList("bt750345"));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductConvertContactsToLowerCase() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setContacts(Arrays.asList(productManager2.getUserId().toUpperCase()));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setContacts(Arrays.asList(productManager2.getUserId().toLowerCase(), productManager1.getUserId()));
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductContactsNotAllowedAsdcUsers() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setContacts(Arrays.asList(productStrategistUser1.getUserId()));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(productStrategistUser1.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductContactsNotAsdcUser() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ String nonAsdcUserUserId = "bt567h";
+ productReqDetails.setContacts(Arrays.asList(nonAsdcUserUserId));
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(nonAsdcUserUserId);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PRODUCT_CONTACT.name(), varibales, updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_PROJECT_CODE.name(), new ArrayList<String>(), updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setProjectCode(product.getProjectCode());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeLessThanMinCharacters() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("9870");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList<String>(), updateProduct.getResponse());
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeHasnMinCharacters() throws Exception { // min
+ // =5
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("98700");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setProjectCode(productReqDetails.getProjectCode());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeHasnMaxCharacters() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("1234567890");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setProjectCode(productReqDetails.getProjectCode());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeExceedMaxCharacters() throws Exception {// Max
+ // =10
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("12345678901");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList<String>(), updateProduct.getResponse());
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setProjectCode(product.getProjectCode());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductProjectCodeIsNotNumeric() throws Exception {
+ // Max =10
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setProjectCode("1234a");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROJECT_CODE.name(), new ArrayList<String>(), updateProduct.getResponse());
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setProjectCode(product.getProjectCode());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIconIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setIcon("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<String>();
+ variables.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables, updateProduct.getResponse());
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIcon(product.getIcon());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIconIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setIcon(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ // Get Product and verify that metadata didn't change
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIcon(product.getIcon());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIconMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setIcon("A_a-1-2--b__BB1234567890A"); // Max length =
+ // 25
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIcon(productReqDetails.getIcon());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIconExceedMaxLength() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setIcon("A_a-1-2--b__BB1234567890A_");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<String>();
+ variables.add(COMPONENT_TYPE);
+ variables.add("25");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT.name(), variables, updateProduct.getResponse());
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIcon(product.getIcon());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIconInValidCharacters() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ String icon = "asdfg"; // Allowed characters [a-zA-Z0-9], dash (‘-‘),
+ // underscore (‘_’).
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/', '|', '\\', ',' };
+ RestResponse updateProduct;
+ for (int i = 0; i < invalidChars.length; i++) {
+ productReqDetails.setIcon(icon + invalidChars[i]);
+ updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ArrayList<String> variables = new ArrayList<String>();
+ variables.add(COMPONENT_TYPE);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), variables, updateProduct.getResponse());
+ }
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIcon(product.getIcon());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIsActiveIsEmpty() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setActive("");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIsActive(false);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIsActiveIsTrue() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setActive("true");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIsActive(true);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIsActiveIsNull() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(defaultCategories);
+ productReqDetails.setActive("true");
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setActive(null);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIsActive(true);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIsActiveIsFalse() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setActive("false");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ expectedProduct.setIsActive(false);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductIsActiveHasInvalidValue() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setActive("eeeee");
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(), updateProduct.getResponse());
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_INVALID_CONTENT, updateProduct.getErrorCode().intValue());
+ RestResponse getProduct = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ ProductRestUtils.checkSuccess(getProduct);
+ Product expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ expectedProduct.setUniqueId(product.getUniqueId());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(getProduct.getResponse(), Product.class);
+ expectedProduct.setVersion(product.getVersion());
+ expectedProduct.setLastUpdaterUserId(productManager1.getUserId());
+ expectedProduct.setLastUpdaterFullName(productManager1.getFullName());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductAssociations() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ List<CategoryDefinition> addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory();
+ productReqDetails.setCategories(addSecondGroupingToDefaultCategory);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setCategories(productReqDetails.getCategories());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductAssociations02() throws Exception {
+ List<CategoryDefinition> addSecondGroupingToDefaultCategory = addSecondGroupingToDefaultCategory(); // Category1->Subcategory1->[Grouping1,
+ // Grouping11]
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(addSecondGroupingToDefaultCategory);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ Product product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ List<CategoryDefinition> defaultCategory = addSubcategoryAndGroupingToDefaultCategory(); // Category1->[Subcategory1->[Grouping1,
+ // Grouping11],Subcategory2->[Grouping12]]
+ productReqDetails.setCategories(defaultCategory);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setCategories(productReqDetails.getCategories());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductRemoveAllAssociations() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ List<CategoryDefinition> defaultCategory = new ArrayList<CategoryDefinition>();
+ productReqDetails.setCategories(defaultCategory);
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setCategories(productReqDetails.getCategories());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ @Test // (enabled=false)
+ public void updateProductAssociationsCategotyIsNull() throws Exception {
+ createProducrByPSAndCheckIn();
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ productReqDetails.setUniqueId(product.getUniqueId());
+ productReqDetails.setUUID(product.getUUID());
+ productReqDetails.setCategories(null);// product categories will not be
+ // updated
+ RestResponse updateProduct = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkSuccess(updateProduct);
+ productReqDetails.setLastUpdaterUserId(productManager1.getUserId());
+ productReqDetails.setLastUpdaterFullName(productManager1.getFullName());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(updateProduct.getResponse(), Product.class);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, "0.2", productManager1);
+ expectedProduct.setUUID(product.getUUID());
+ expectedProduct.setInvariantUUID(product.getInvariantUUID());
+ expectedProduct.setCategories(product.getCategories());
+ expectedProduct.setNormalizedName(productReqDetails.getName().toLowerCase());
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.UPDATE_COMPONENT);
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+
+ private void createProductWithCategories(List<CategoryDefinition> categoryDefinitions) throws Exception {
+ ProductReqDetails productReqDetails = (categoryDefinitions != null ? ElementFactory.getDefaultProduct(categoryDefinitions) : ElementFactory.getDefaultProduct());
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ String actualUuid = ResponseParser.getUuidFromResponse(createProduct);
+ Product expectedProduct = Convertor.constructFieldsForRespValidation(productReqDetails, INITIAL_PRODUCT_VERSION, productManager1);
+ String normalizedNameFomJsonResponse = ResponseParser.getValueFromJsonResponse(createProduct.getResponse(), "normalizedName");
+ expectedProduct.setNormalizedName(normalizedNameFomJsonResponse);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, ComponentOperationEnum.CREATE_COMPONENT);
+ ExpectedProductAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(expectedProduct, CREATE_AUDIT_ACTION, productManager1, ActionStatus.CREATED, Constants.EMPTY_STRING, "0.1", null,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, actualUuid);
+ AuditValidationUtils.validateAuditProduct(constructFieldsForAuditValidation, CREATE_AUDIT_ACTION);
+ }
+
+ private void createProducrByPSAndCheckIn() throws Exception {
+ productReqDetails = ElementFactory.getDefaultProduct(defaultCategories);
+ createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ ProductRestUtils.checkCreateResponse(createProduct);
+ product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ RestResponse changeProductLifeCycle = ProductRestUtils.changeProductLifeCycle(product, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.checkSuccess(changeProductLifeCycle);
+ }
+
+ @Test
+ public void checkInvariantUuidIsImmutable() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!";
+ productReqDetails.setInvariantUUID(invariantUuidDefinedByUser);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ BaseRestUtils.checkStatusCode(createProduct, "create request failed", false, 201);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ Product ProductCreation = ResponseParser.convertProductResponseToJavaObject(createProduct.getResponse());
+ String invariantUUIDcreation = ProductCreation.getInvariantUUID();
+
+ // validate get response
+ RestResponse getProductRes = ProductRestUtils.getProduct(productReqDetails.getUniqueId(), productManager1.getUserId());
+ BaseRestUtils.checkSuccess(getProductRes);
+ Product productGetting = ResponseParser.convertProductResponseToJavaObject(getProductRes.getResponse());
+ String invariantUUIDgetting = productGetting.getInvariantUUID();
+ assertEquals(invariantUUIDcreation, invariantUUIDgetting);
+
+ // Update Product with new invariant UUID
+ RestResponse restResponseUpdate = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ BaseRestUtils.checkSuccess(restResponseUpdate);
+ Product updatedProduct = ResponseParser.convertProductResponseToJavaObject(restResponseUpdate.getResponse());
+ String invariantUUIDupdating = updatedProduct.getInvariantUUID();
+ assertEquals(invariantUUIDcreation, invariantUUIDupdating);
+
+ // Do checkin
+ RestResponse restResponseCheckin = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKIN);
+ BaseRestUtils.checkSuccess(restResponseCheckin);
+ Product checkinProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckin.getResponse());
+ String invariantUUIDcheckin = checkinProduct.getInvariantUUID();
+ String version = checkinProduct.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckin);
+ assertEquals(version, "0.1");
+
+ // Do checkout
+ RestResponse restResponseCheckout = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ BaseRestUtils.checkSuccess(restResponseCheckout);
+ Product checkoutProduct = ResponseParser.convertProductResponseToJavaObject(restResponseCheckout.getResponse());
+ String invariantUUIDcheckout = checkoutProduct.getInvariantUUID();
+ version = checkoutProduct.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckout);
+ assertEquals(version, "0.2");
+
+ }
+
+ // US672129 Benny
+ private void getProductValidateInvariantUuid(String productUniqueId, String invariantUUIDcreation) throws Exception {
+ RestResponse getProduct = ProductRestUtils.getProduct(productUniqueId, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getProduct.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(getProduct));
+ }
+
+ @Test // invariantUUID generated when the component is created and never
+ // changed
+ public void productInvariantUuid() throws Exception {
+ ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct();
+ String invariantUuidDefinedByUser = "12345";
+ productReqDetails.setInvariantUUID(invariantUuidDefinedByUser);
+ RestResponse createProduct = ProductRestUtils.createProduct(productReqDetails, productManager1);
+ assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ // invariantUUID generated when the component is created and never
+ // changed
+ String invariantUUIDcreation = ResponseParser.getInvariantUuid(createProduct);
+ getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation);
+ // Update Product with new invariant UUID
+ RestResponse restResponse = ProductRestUtils.updateProduct(productReqDetails, productManager1);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation);
+ // Checkin
+ restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation);
+ // Checkout
+ restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation);
+
+ // UnDo-CheckOut
+ restResponse = LifecycleRestUtils.changeProductState(productReqDetails, productManager1, LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getProductValidateInvariantUuid(productReqDetails.getUniqueId(), invariantUUIDcreation);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java
new file mode 100644
index 0000000000..aebea697b2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductGetFollowedTest.java
@@ -0,0 +1,164 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ProductGetFollowedTest extends ProductBaseTest {
+
+ protected Product product200;
+ protected Product product400;
+
+ private ProductReqDetails productDetails200;
+ private ProductReqDetails productDetails400;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ProductGetFollowedTest() {
+ super(name, ProductGetFollowedTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+ createProducts();
+ }
+
+ @Test
+ public void followedPageTest() throws Exception { // Actions
+ RestResponse changeLifeCycleResponse;
+ changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+ changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+ // Expected users Followed page
+ ProductValidationUtils.checkUserFollowedPage(productManager1, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400);
+ ProductValidationUtils.checkUserFollowedPage(productManager2, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ @Test
+ public void followedPagePmCheckedOutProductWasCheckInByOtherPm() throws Exception {
+ ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product400, productManager1, LifeCycleStatesEnum.CHECKOUT);
+ RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+
+ ProductValidationUtils.checkUserFollowedPage(productManager1, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ @Test
+ public void followedPagePmCheckInProduct02() throws Exception {
+ ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+
+ ProductValidationUtils.checkUserFollowedPage(productManager1, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400);
+ ProductValidationUtils.checkUserFollowedPage(productManager2, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ @Test
+ public void followedPageAdminCheckoutProductWasCheckedinByPm() throws Exception {
+ ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+ RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+
+ ProductValidationUtils.checkUserFollowedPage(productManager1, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ @Test
+ public void followedPageAdminCheckInProduct() throws Exception {
+ ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKOUT);
+ RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product400, adminUser, LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+
+ ProductValidationUtils.checkUserFollowedPage(productManager1, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager2, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ @Test
+ public void followedPagePmCheckoutProductWasCheckedinByAdmin() throws Exception {
+ ProductRestUtils.changeProductLifeCycle(product200, productManager1, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product400, productManager2, LifeCycleStatesEnum.CHECKIN);
+ ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKOUT);
+ ProductRestUtils.changeProductLifeCycle(product200, adminUser, LifeCycleStatesEnum.CHECKIN);
+ RestResponse changeLifeCycleResponse = ProductRestUtils.changeProductLifeCycle(product200, productManager2, LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(changeLifeCycleResponse);
+
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productManager1, product200);
+ ProductValidationUtils.checkUserFollowedPage(productManager2, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(adminUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(designerUser, product200, product400);
+ ProductValidationUtils.verifyProductsNotExistInUserFollowedPage(productStrategistUser1, product200, product400);
+ }
+
+ private void createProducts() throws Exception {
+ // PM1 (Product manager) create :PR200 (check In State)
+ // PM2 (Product manager) create :PR400 (check In State)
+
+ productDetails200 = ElementFactory.getDefaultProduct("CiProd200", defaultCategories);
+ productDetails400 = ElementFactory.getDefaultProduct("CiProd400", defaultCategories);
+
+ RestResponse createProduct = ProductRestUtils.createProduct(productDetails200, productManager1);
+ ResourceRestUtils.checkCreateResponse(createProduct);
+ product200 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+
+ createProduct = ProductRestUtils.createProduct(productDetails400, productManager2);
+ ResourceRestUtils.checkCreateResponse(createProduct);
+ product400 = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java
new file mode 100644
index 0000000000..8c3409342b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductLifecycleTest.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.BeforeMethod;
+
+public abstract class ProductLifecycleTest extends ProductBaseTest {
+
+ protected static final String CHECKIN_ACTION = "Checkin";
+ protected static final String CHECKOUT_ACTION = "Checkout";
+ protected static final String UNDO_CHECKOUT_ACTION = "UndoCheckout";
+
+ protected Product expectedProduct;
+
+ public ProductLifecycleTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+ ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories);
+ RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productManager1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED, createProduct.getErrorCode().intValue());
+ expectedProduct = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java
new file mode 100644
index 0000000000..479dbb9436
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductTestBase.java
@@ -0,0 +1,148 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+
+import org.apache.log4j.lf5.util.ResourceUtils;
+import org.junit.Before;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+
+public class ProductTestBase extends ProductBaseTest {
+
+ public ProductTestBase(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ protected ResourceReqDetails downloadResourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected User sdncUserDetails;
+ protected ArtifactReqDetails heatArtifactDetails;
+ protected ArtifactReqDetails defaultArtifactDetails;
+ protected ResourceUtils resourceUtils;
+ protected ArtifactUtils artifactUtils;
+ protected Resource resource;
+ protected Service service;
+ protected Product product;
+
+ // protected static ServiceUtils serviceUtils = new ServiceUtils();
+
+ @Before
+ public void before() throws Exception {
+
+ initializeMembers();
+ createComponents();
+
+ }
+
+ public void initializeMembers() throws IOException, Exception {
+
+ downloadResourceDetails = ElementFactory.getDefaultResource();
+ serviceDetails = ElementFactory.getDefaultService();
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+
+ }
+
+ protected void createComponents() throws Exception {
+
+ RestResponse response = ResourceRestUtils.createResource(downloadResourceDetails, sdncUserDetails);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", downloadResourceDetails.getUniqueId());
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncUserDetails,
+ downloadResourceDetails.getUniqueId());
+ assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ // certified resource
+ response = LifecycleRestUtils.certifyResource(downloadResourceDetails);
+ assertTrue("certify resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ response = ResourceRestUtils.getResource(downloadResourceDetails.getUniqueId());
+ assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200);
+ resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+
+ response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId());
+
+ // add resource instance with HEAT deployment artifact to the service
+ resourceInstanceReqDetails.setComponentUid(downloadResourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails,
+ serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201);
+
+ // certified service
+ response = LifecycleRestUtils.certifyService(serviceDetails);
+ assertTrue("certify service request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ response = ServiceRestUtils.getService(serviceDetails, sdncUserDetails);
+ assertTrue("response code is not 200, returned: " + response.getErrorCode(), response.getErrorCode() == 200);
+ service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse());
+
+ DbUtils.cleanAllAudits();
+
+ ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct(defaultCategories);
+ RestResponse createProduct = ProductRestUtils.createProduct(defaultProduct, productStrategistUser1);
+ assertEquals("Check response code after create Product", BaseRestUtils.STATUS_CODE_CREATED,
+ createProduct.getErrorCode().intValue());
+ product = ResponseParser.parseToObjectUsingMapper(createProduct.getResponse(), Product.class);
+
+ // add service instance to product
+ //
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java
new file mode 100644
index 0000000000..412e6fd92d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductToscaYamlGenerationTest.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ProductToscaYamlGenerationTest extends ProductTestBase {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ProductToscaYamlGenerationTest() {
+ super(name, ProductToscaYamlGenerationTest.class.getName());
+ }
+
+ @Test
+ public void productToscaYamlFormat() throws IOException {
+
+ String heatEnvArtifactHeader = (String) Utils.parseYamlConfig("heatEnvArtifactHeader");
+ // System.out.println("heatEnvArtifactHeader = \n" +
+ // heatEnvArtifactHeader);
+
+ String heatEnvArtifactFooter = (String) Utils.parseYamlConfig("heatEnvArtifactFooter");
+ // System.out.println("heatEnvArtifactFooter = \n" +
+ // heatEnvArtifactFooter);
+
+ // temporary commented
+ // RestResponse downloadResourceInstanceHeatArtifact =
+ // ArtifactRestUtils.downloadResourceInstanceArtifact(service.getUniqueId(),
+ // resourceInstanceId, sdncUserDetails,
+ // heatArtifactDefinition.getUniqueId());
+ // assertTrue("expected request returned status:" + 200 + ", actual: " +
+ // downloadResourceInstanceHeatArtifact.getErrorCode(),
+ // downloadResourceInstanceHeatArtifact.getErrorCode()==200);
+
+ // InputStream stream =
+ // getDecodedSteramFromString(downloadResourceInstanceHeatArtifact.getResponse());
+ // System.out.println(Utils.getParamValueFromYamlByKey(stream,
+ // "description", String.class));
+
+ // node_types
+
+ }
+
+ private InputStream getDecodedSteramFromString(String encoded64Payload) throws IOException {
+
+ Gson gson = new Gson();
+ ArtifactUiDownloadData artifactUiDownloadData = gson.fromJson(encoded64Payload, ArtifactUiDownloadData.class);
+ String decodedPayload = Decoder.decode(artifactUiDownloadData.getBase64Contents());
+ return new ByteArrayInputStream(decodedPayload.getBytes());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java
new file mode 100644
index 0000000000..d4bfb62377
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/product/ProductUndoCheckoutTest.java
@@ -0,0 +1,216 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.product;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+
+import java.io.FileNotFoundException;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ProductValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+public class ProductUndoCheckoutTest extends ProductLifecycleTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ @BeforeClass
+ public static void staticInit() {
+ auditAction = UNDO_CHECKOUT_ACTION;
+ operation = ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT;
+ }
+
+ public ProductUndoCheckoutTest() {
+ super(name, ProductUndoCheckoutTest.class.getName());
+ }
+
+ @Test
+ public void undoCheckOutProductByPm() throws Exception {
+ undoCheckOutProductSuccess(productManager1, false);
+ }
+
+ @Test
+ public void undoCheckOutProductByAdmin() throws Exception {
+ undoCheckOutProductSuccess(adminUser, true);
+ }
+
+ @Test
+ public void undoCheckOutAfterCreate() throws Exception {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue());
+
+ // Verify version was removed
+ lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), productManager1.getUserId());
+ assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue());
+
+ Product emptyProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+ assertNull(emptyProduct);
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(emptyProduct,
+ auditAction, productManager1, ActionStatus.OK, "0.1", Constants.EMPTY_STRING,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, null, Constants.EMPTY_STRING);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+
+ }
+
+ @Test
+ public void undoCheckOutNotExist() throws Exception {
+ String notExistId = "1234";
+ expectedProduct.setUniqueId(notExistId);
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undo checkout product", 404, lcsResponse.getErrorCode().intValue());
+ expectedProduct.setName(notExistId);
+ String[] auditParameters = new String[] { Constants.EMPTY_STRING };
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productManager1, ActionStatus.PRODUCT_NOT_FOUND, Constants.EMPTY_STRING,
+ Constants.EMPTY_STRING, null, null, Constants.EMPTY_STRING, auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+
+ }
+
+ @Test
+ public void undoCheckOutNotInCheckout() throws Exception {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undo checkout product", 409, lcsResponse.getErrorCode().intValue());
+
+ String[] auditParameters = new String[] { expectedProduct.getName(), "product", productManager1.getFirstName(),
+ productManager1.getLastName(), productManager1.getUserId() };
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, productManager1, ActionStatus.COMPONENT_ALREADY_CHECKED_IN, "0.1", "0.1",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ expectedProduct.getUUID(), auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+
+ }
+
+ @Test
+ public void undoCheckOutProductByPsRoleNotAllowed() throws Exception {
+ undoCheckOutProductRestricted(productStrategistUser1);
+ }
+
+ @Test
+ public void undoCheckOutProductByPmNotStateOwner() throws Exception {
+ undoCheckOutProductForbidden(productManager2);
+ }
+
+ private void undoCheckOutProductSuccess(User user, boolean isAdmin) throws Exception, FileNotFoundException {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue());
+
+ // Checking undo checkout of admin even if not state owner
+ User checkoutUser = isAdmin ? productManager1 : user;
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, checkoutUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue());
+ Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, user, LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undo checkout product", 200, lcsResponse.getErrorCode().intValue());
+
+ // Verify version was removed
+ lcsResponse = ProductRestUtils.getProduct(productToBeUndone.getUniqueId(), user.getUserId());
+ assertEquals("Check response code after get undone product", 404, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = ProductRestUtils.getProduct(expectedProduct.getUniqueId(), user.getUserId());
+ assertEquals("Check response code after get latest version", 200, lcsResponse.getErrorCode().intValue());
+
+ Product latestProduct = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ expectedProduct.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, latestProduct, operation);
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(latestProduct,
+ auditAction, user, ActionStatus.OK, "0.2", "0.1", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKIN, latestProduct.getUUID());
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ private void undoCheckOutProductRestricted(User undoCheckoutUser) throws Exception, FileNotFoundException {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue());
+ Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser,
+ LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undocheckout product", 409, lcsResponse.getErrorCode().intValue());
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(productToBeUndone,
+ auditAction, undoCheckoutUser, ActionStatus.RESTRICTED_OPERATION, "0.2", "0.2",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ productToBeUndone.getUUID());
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+ private void undoCheckOutProductForbidden(User undoCheckoutUser) throws Exception, FileNotFoundException {
+ RestResponse lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkin product", 200, lcsResponse.getErrorCode().intValue());
+
+ lcsResponse = LifecycleRestUtils.changeProductState(expectedProduct, productManager1,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout product", 200, lcsResponse.getErrorCode().intValue());
+ Product productToBeUndone = ResponseParser.parseToObjectUsingMapper(lcsResponse.getResponse(), Product.class);
+
+ lcsResponse = LifecycleRestUtils.changeProductState(productToBeUndone, undoCheckoutUser,
+ LifeCycleStatesEnum.UNDOCHECKOUT);
+ assertEquals("Check response code after undocheckout product", 403, lcsResponse.getErrorCode().intValue());
+ String[] auditParameters = new String[] { productToBeUndone.getName(), "product",
+ productManager1.getFirstName(), productManager1.getLastName(), productManager1.getUserId() };
+
+ ExpectedProductAudit expectedProductAudit = Convertor.constructFieldsForAuditValidation(expectedProduct,
+ auditAction, undoCheckoutUser, ActionStatus.COMPONENT_CHECKOUT_BY_ANOTHER_USER, "0.2", "0.2",
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ productToBeUndone.getUUID(), auditParameters);
+ AuditValidationUtils.validateAuditProduct(expectedProductAudit, auditAction);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java
new file mode 100644
index 0000000000..303be77f92
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/AdditionalInformationServletTest.java
@@ -0,0 +1,2021 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.property;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.json.simple.parser.JSONParser;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.AdditionalInfoParameterInfo;
+import org.openecomp.sdc.be.model.AdditionalInformationDefinition;
+import org.openecomp.sdc.be.model.PropertyConstraint;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintDeserialiser;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.resource.ResourceApiTest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.reflect.TypeToken;
+
+public class AdditionalInformationServletTest extends ComponentBaseTest {
+
+ protected Type constraintType = new TypeToken<PropertyConstraint>() {
+ }.getType();
+
+ protected Gson gson = new GsonBuilder().registerTypeAdapter(constraintType, new PropertyConstraintDeserialiser()).create();
+
+ @Rule
+ public static TestName name = new TestName();
+
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+ protected JSONParser jsonParser = new JSONParser();
+
+ public AdditionalInformationServletTest() {
+ super(name, AdditionalInformationServletTest.class.getName());
+ }
+
+ // @Before
+ // public void deleteResources() {
+ // //TODO Evg : will be new API added for delete by name and version
+ //
+ // ResourceReqDetails resource = getResource();
+ // User user = getUser();
+ //
+ // try {
+ // String resourceName = resource.getResourceName();
+ // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName,
+ // "0.1");
+ // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName,
+ // "0.2");
+ // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName,
+ // "1.0");
+ // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName,
+ // "1.1");
+ // ResourceRestUtils.deleteResourceByNameAndVersion(user, resourceName +
+ // "aa", "0.1");
+ // resourceUtils.deleteResource_allVersions(resource, user);
+ //
+ // } catch (IOException e) {
+ // assertTrue(false);
+ // }
+ //
+ // try {
+ // ServiceReqDetails serviceDetails = getServiceDetails();
+ //
+ // RestResponse deleteServiceResponse =
+ // serviceUtils.deleteServiceByNameAndVersion(UserUtils.getAdminDetails(),
+ // serviceDetails.getServiceName(), "0.1");
+ //
+ // assertNotNull("check response object is not null after delete
+ // service",deleteServiceResponse);
+ // assertNotNull("check error code exists in response after delete
+ // service",deleteServiceResponse.getErrorCode());
+ // assertTrue("delete service failed status:" +
+ // deleteServiceResponse.getErrorCode(),
+ // deleteServiceResponse.getErrorCode() != 500);
+ //
+ // deleteServiceResponse =
+ // serviceUtils.deleteServiceByNameAndVersion(UserUtils.getAdminDetails(),
+ // serviceDetails.getServiceName(), "1.0");
+ //
+ // assertNotNull("check response object is not null after delete
+ // service",deleteServiceResponse);
+ // assertNotNull("check error code exists in response after delete
+ // service",deleteServiceResponse.getErrorCode());
+ // assertTrue("delete service failed status:" +
+ // deleteServiceResponse.getErrorCode(),
+ // deleteServiceResponse.getErrorCode() != 500);
+ //
+ // serviceUtils.deleteService_allVersions(serviceDetails, user);
+ //
+ // } catch (IOException e) {
+ // assertTrue(false);
+ // }
+ // }
+
+ @Test
+ public void updateResourceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ String updatedKey = "ZZZ ZZZ";
+ String updatedValue = "JJJJ";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ AssertJUnit.assertNotNull("check response object is not null after create property", createProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ fromJson.setKey(updatedKey);
+ fromJson.setValue(updatedValue);
+
+ RestResponse updatedProperty = updateAdditionalInformation(resourceId, fromJson, user, fromJson.getUniqueId());
+ AssertJUnit.assertNotNull("check response object is not null after update additional information", updatedProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after additional information", 200, updatedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(updatedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ AssertJUnit.assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ AssertJUnit.assertEquals("check returned key", "ZZZ ZZZ", updatedJson.getKey());
+ AssertJUnit.assertEquals("check returned value", updatedValue, updatedJson.getValue());
+ AssertJUnit.assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ }
+
+ @Test
+ public void deleteResourceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ AssertJUnit.assertNotNull("check response object is not null after create property", createProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = deleteAdditionalInformation(resourceId, fromJson.getUniqueId(), user);
+ AssertJUnit.assertNotNull("check response object is not null after update additional information", deletedProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ AssertJUnit.assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ AssertJUnit.assertEquals("check returned key", "AAA AAA", updatedJson.getKey());
+ AssertJUnit.assertEquals("check returned value", value, updatedJson.getValue());
+ AssertJUnit.assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ deletedProperty = deleteAdditionalInformation(resourceId, fromJson.getUniqueId(), user);
+ AssertJUnit.assertNotNull("check response object is not null after update additional information", deletedProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after additional information", 409, deletedProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceAdditionalInformationTestDuringLifecycle() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ AssertJUnit.assertNotNull("check response object is not null after create resource", createResourceResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ AssertJUnit.assertNotNull("check response object is not null after create property", createProperty);
+ AssertJUnit.assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ AssertJUnit.assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ AssertJUnit.assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ resource.setUniqueId(resourceId);
+
+ // resourceUtils.addResourceMandatoryArtifacts(user,
+ // createResourceResponse);
+
+ certifyResource(user, resource, null, 1);
+
+ }
+
+ public RestResponse createService() {
+
+ User user = getUser();
+ ServiceReqDetails serviceDetails = getServiceDetails();
+
+ RestResponse createServiceResponse = null;
+ try {
+ createServiceResponse = ServiceRestUtils.createService(serviceDetails, user);
+ AssertJUnit.assertNotNull("check response object is not null after create user", createServiceResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after checkout resource", 201, createServiceResponse.getErrorCode().intValue());
+ } catch (Exception e) {
+ AssertJUnit.assertTrue(false);
+ }
+
+ return createServiceResponse;
+
+ }
+
+ protected User getUser() {
+ String adminFirstName = "Jimmy";
+ String adminLastName = "Hendrix";
+ String adminUserId = "jh0003";
+ return new User(adminFirstName, adminLastName, adminUserId, null, null, null);
+ }
+
+ protected ResourceReqDetails getResource() {
+ String resourceName = "ciResourceforproperty4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "pe0123";
+ String icon = "myICON";
+ ResourceReqDetails resource = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resource.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory());
+ return resource;
+ }
+
+ protected RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws IOException {
+
+ ResourceApiTest rat = new ResourceApiTest();
+ ResourceReqDetails resourceObj = rat.getResourceObj();
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+ RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return createResourceResponse;
+
+ }
+
+ protected RestResponse getResource(User sdncModifierDetails, String resourceUid) throws IOException {
+
+ ResourceApiTest rat = new ResourceApiTest();
+ ResourceReqDetails resourceObj = rat.getResourceObj();
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid);
+ RestResponse createResourceResponse = http.httpSendGet(url, headersMap);
+
+ return createResourceResponse;
+
+ }
+
+ protected RestResponse deleteResource(String resourceName, String resourceVersion, User sdncModifierDetails) throws IOException {
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceName, resourceVersion);
+
+ return deleteResourceResponse;
+
+ }
+
+ protected RestResponse updateAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails, String id) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String body = gson.toJson(additionalInfo);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendPut(url, body, headersMap);
+
+ }
+
+ protected RestResponse updateServiceAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails, String id) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String body = gson.toJson(additionalInfo);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendPut(url, body, headersMap);
+
+ }
+
+ protected RestResponse deleteAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.DELETE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendDelete(url, headersMap);
+
+ }
+
+ protected RestResponse deleteServiceAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.DELETE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendDelete(url, headersMap);
+
+ }
+
+ protected RestResponse getAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ protected RestResponse getServiceAdditionalInformation(String resourceId, String id, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId, id);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ protected RestResponse getResourceAllAdditionalInformation(String resourceId, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ALL_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ protected RestResponse getServiceAllAdditionalInformation(String resourceId, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ALL_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ protected RestResponse createResourceAdditionalInformation(String resourceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String body = gson.toJson(additionalInfo);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_ADDITIONAL_INFORMATION_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ return http.httpSendPost(url, body, headersMap);
+
+ }
+
+ protected RestResponse createServiceAdditionalInformation(String serviceId, AdditionalInfoParameterInfo additionalInfo, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String body = gson.toJson(additionalInfo);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_ADDITIONAL_INFORMATION_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
+ return http.httpSendPost(url, body, headersMap);
+
+ }
+
+ protected ServiceReqDetails getServiceDetails() {
+ String serviceName = "ciNewTestService21";
+ String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add("serviceTag");
+ tags.add(serviceName);
+ String description = "service Description";
+ String vendorName = "Oracle";
+ String vendorRelease = "0.1";
+ String contactId = "al1976";
+ String icon = "myIcon";
+
+ return new ServiceReqDetails(serviceName, category, tags, description, contactId, icon);
+ }
+
+ // TODO Tal: Since Cashing change partial resource returned that causes null
+ // pointer exception in line:
+ // commented out till fixing
+ protected Resource certifyResource(User user, ResourceReqDetails resource, String resourceVersion, int numberOfAI) throws IOException {
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN);
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", checkInResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue());
+
+ Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class);
+ // TODO Tal: Since Cashing change partial resource returned that causes
+ // null pointer exception
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ */
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size());
+ */
+
+ RestResponse req4certResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", req4certResponse);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, req4certResponse.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(), Resource.class);
+ // TODO Tal: Since Cashing change partial resource returned that causes
+ // null pointer exception
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ */
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size());
+ */
+
+ // change modifier
+ user.setUserId(UserRoleEnum.TESTER.getUserId());
+ // start certification
+
+ RestResponse startCertResourceResponse3 = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ AssertJUnit.assertNotNull("check response object is not null after create user", startCertResourceResponse3);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, startCertResourceResponse3.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class);
+ // TODO Tal: Since Cashing change partial resource returned that causes
+ // null pointer exception
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ */
+ /*
+ * AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0). getParameters().size());
+ */
+
+ // certify
+
+ RestResponse certifyResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFY);
+ AssertJUnit.assertNotNull("check response object is not null after create user", certifyResponse);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, certifyResponse.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(), Resource.class);
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ AssertJUnit.assertEquals("check size of additional information", numberOfAI, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ Resource certifyResource = gson.fromJson(certifyResponse.getResponse(), Resource.class);
+ return certifyResource;
+ }
+
+ protected Resource certifyService(User user, ServiceReqDetails service, String resourceVersion) throws Exception {
+ RestResponse checkInResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKIN);
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", checkInResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue());
+
+ Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class);
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ RestResponse req4certResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", req4certResponse);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, req4certResponse.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(), Resource.class);
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ // change modifier
+ user.setUserId(UserRoleEnum.TESTER.getUserId());
+ // start certification
+
+ RestResponse startCertResourceResponse3 = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ AssertJUnit.assertNotNull("check response object is not null after create user", startCertResourceResponse3);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, startCertResourceResponse3.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class);
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ // certify
+
+ RestResponse certifyResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CERTIFY);
+ AssertJUnit.assertNotNull("check response object is not null after create user", certifyResponse);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200, certifyResponse.getErrorCode().intValue());
+
+ resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(), Resource.class);
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ AssertJUnit.assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ Resource certifyResource = gson.fromJson(certifyResponse.getResponse(), Resource.class);
+ return certifyResource;
+ }
+
+ @Test
+ public void createResourceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceAdditionalInfoFormatWithTags() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "<b>Bold<</b>";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertEquals("check returned key", "Bold&amp;lt;", fromJson.getValue());
+
+ }
+
+ @Test
+ public void createServiceAdditionalInfoFormatWithTags() throws Exception {
+ User user = getUser();
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ assertNotNull("check response object is not null after create resource", createServiceResponse);
+ assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "<b>Bold<</b>";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertEquals("check returned key", "Bold&amp;lt;", fromJson.getValue());
+
+ }
+
+ @Test
+ public void createResourceAdditionalInfoFormatWithWhiteSpaces() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = " ";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ key = " ";
+ value = "AAA AAA";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceAdditionalInfoFormatWithWhiteSpaces() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+ ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ assertNotNull("check response object is not null after create resource", createServiceResponse);
+ assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = " ";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ key = " ";
+ value = "AAA AAA";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceAndUpdateAdditionalInfo() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ key = "BBB BBB";
+ value = "BBBB";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "BBB BBB", fromJson.getKey());
+
+ String updatedKey = "AAA AAA";
+ String updatedValue = "JJJJ";
+
+ fromJson.setKey(updatedKey);
+ fromJson.setValue(updatedValue);
+
+ RestResponse updatedProperty = updateAdditionalInformation(resourceId, fromJson, user, fromJson.getUniqueId());
+ assertNotNull("check response object is not null after update additional information", updatedProperty);
+ assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 409, updatedProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceEmptyAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ key = "BBBB";
+ value = "";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceEmptyAdditionalInformationTest() throws Exception {
+
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceAllSpacesAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = " ";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceAllSpacesAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = " ";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceInvalidKeyAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "abc?";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceInvalidKeyAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "abc?";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceAdditionalInformationNullKeyTest() throws Exception {
+
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ String key = null;
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceAdditionalInformationNullKeyTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = null;
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceMaximumInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ for (int i = 0; i < 50; i++) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceLifeCycleAndMaximumInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+ resource.setUniqueId(resourceId);
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ for (int i = 0; i < 49; i++) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+
+ String resourceVersion = "0.1";
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+
+ assertNotNull("check response object is not null after create property", checkInResponse);
+ assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode());
+ assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue());
+
+ resourceVersion = "0.2";
+
+ RestResponse checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null);
+
+ resourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse);
+ resource.setUniqueId(resourceId);
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value);
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value);
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ RestResponse checkUndoOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.UNDOCHECKOUT, null);
+
+ resourceVersion = "0.1";
+
+ checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null);
+ resourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse);
+ resource.setUniqueId(resourceId);
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value);
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value);
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceLifeCycleCertifyAndMaximumInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+ resource.setUniqueId(resourceId);
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ for (int i = 0; i < 49; i++) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+
+ String resourceVersion = "0.1";
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+
+ // resourceUtils.addResourceMandatoryArtifacts(user,
+ // createResourceResponse);
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+
+ assertNotNull("check response object is not null after create property", checkInResponse);
+ assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode());
+ assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue());
+
+ RestResponse changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST, null);
+ changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.STARTCERTIFICATION, null);
+ changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CERTIFY, null);
+
+ assertNotNull("check response object is not null after create property", checkInResponse);
+ assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode());
+ assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue());
+
+ resourceId = ResponseParser.getUniqueIdFromResponse(changeStateResponse);
+ resource.setUniqueId(resourceId);
+
+ resourceVersion = "1.0";
+
+ changeStateResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null);
+ resourceId = ResponseParser.getUniqueIdFromResponse(changeStateResponse);
+ resource.setUniqueId(resourceId);
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value);
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value);
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceCycleAndMaximumInformationTest() throws Exception {
+
+ User user = getUser();
+
+ ServiceReqDetails service = getServiceDetails();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ assertNotNull("check response object is not null after create resource", createServiceResponse);
+ assertNotNull("check error code exists in response after create resource", createServiceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createServiceResponse.getErrorCode().intValue());
+
+ service.setUniqueId(serviceId);
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ for (int i = 0; i < 49; i++) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+
+ String resourceVersion = "0.1";
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+ RestResponse checkInResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKIN, checkinComentJson);
+
+ assertNotNull("check response object is not null after create property", checkInResponse);
+ assertNotNull("check error code exists in response after create property", checkInResponse.getErrorCode());
+ assertEquals("Check response code after create property", 200, checkInResponse.getErrorCode().intValue());
+
+ resourceVersion = "0.2";
+
+ RestResponse checkOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null);
+
+ serviceId = ResponseParser.convertServiceResponseToJavaObject(checkOutResponse.getResponse()).getUniqueId();
+ service.setUniqueId(serviceId);
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value);
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value);
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ RestResponse checkUndoOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.UNDOCHECKOUT, null);
+
+ resourceVersion = "0.1";
+
+ checkOutResponse = LifecycleRestUtils.changeServiceState(service, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT, null);
+ serviceId = ResponseParser.convertServiceResponseToJavaObject(checkOutResponse.getResponse()).getUniqueId();
+ service.setUniqueId(serviceId);
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 50, value);
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + 51, value);
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createServiceMaximumInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ String lastCreatedProperty = null;
+
+ for (int i = 0; i < 50; i++) {
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key + i, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ lastCreatedProperty = fromJson.getUniqueId();
+
+ }
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 409, createProperty.getErrorCode().intValue());
+
+ RestResponse deletedProperty = deleteServiceAdditionalInformation(serviceId, lastCreatedProperty, user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+ createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void updateServiceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ String updatedKey = "ZZZ ZZZ";
+ String updatedValue = "JJJJ";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ fromJson.setKey(updatedKey);
+ fromJson.setValue(updatedValue);
+
+ RestResponse updatedProperty = updateServiceAdditionalInformation(serviceId, fromJson, user, fromJson.getUniqueId());
+ assertNotNull("check response object is not null after update additional information", updatedProperty);
+ assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, updatedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(updatedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ assertEquals("check returned key", "ZZZ ZZZ", updatedJson.getKey());
+ assertEquals("check returned value", updatedValue, updatedJson.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ fromJson.setKey(updatedKey);
+ fromJson.setValue("");
+
+ updatedProperty = updateServiceAdditionalInformation(serviceId, fromJson, user, fromJson.getUniqueId());
+ assertNotNull("check response object is not null after update additional information", updatedProperty);
+ assertNotNull("check error code exists in response after additional information", updatedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 400, updatedProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void deleteServiceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = deleteServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", updatedJson.getKey());
+ assertEquals("check returned value", value, updatedJson.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ deletedProperty = deleteServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 409, deletedProperty.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void getResourceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = getAdditionalInformation(resourceId, fromJson.getUniqueId(), user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", updatedJson.getKey());
+ assertEquals("check returned value", value, updatedJson.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ }
+
+ @Test
+ public void getServiceAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = getServiceAdditionalInformation(serviceId, fromJson.getUniqueId(), user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", updatedJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", updatedJson.getKey());
+ assertEquals("check returned value", value, updatedJson.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), updatedJson.getUniqueId());
+
+ }
+
+ @Test
+ public void getResourceAllAdditionalInformationTest() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = getResourceAllAdditionalInformation(resourceId, user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInformationDefinition updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInformationDefinition.class);
+ assertEquals("check number of parameters", 1, updatedJson.getParameters().size());
+ AdditionalInfoParameterInfo info = updatedJson.getParameters().iterator().next();
+
+ assertFalse("check number of spaces", info.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", info.getKey());
+ assertEquals("check returned value", value, info.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), info.getUniqueId());
+
+ }
+
+ @Test
+ public void getServiceAllAdditionalInformationTest() throws Exception {
+ User user = getUser();
+
+ RestResponse createServiceResponse = createService();
+
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ RestResponse deletedProperty = getServiceAllAdditionalInformation(serviceId, user);
+ assertNotNull("check response object is not null after update additional information", deletedProperty);
+ assertNotNull("check error code exists in response after additional information", deletedProperty.getErrorCode());
+ assertEquals("Check response code after additional information", 200, deletedProperty.getErrorCode().intValue());
+
+ AdditionalInformationDefinition updatedJson = gson.fromJson(deletedProperty.getResponse(), AdditionalInformationDefinition.class);
+ assertEquals("check number of parameters", 1, updatedJson.getParameters().size());
+ AdditionalInfoParameterInfo info = updatedJson.getParameters().iterator().next();
+
+ assertFalse("check number of spaces", info.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", info.getKey());
+ assertEquals("check returned value", value, info.getValue());
+ assertEquals("check returned id", fromJson.getUniqueId(), info.getUniqueId());
+
+ }
+
+ @Test
+ public void createServiceAdditionalInformationTestDuringLifecycle() throws Exception {
+
+ User user = getUser();
+ RestResponse createServiceResponse = createService();
+ String serviceId = ResponseParser.convertServiceResponseToJavaObject(createServiceResponse.getResponse()).getUniqueId();
+ String key = "AAA AAA";
+ String value = "BBBB";
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createServiceAdditionalInformation(serviceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ AdditionalInfoParameterInfo fromJson = gson.fromJson(createProperty.getResponse(), AdditionalInfoParameterInfo.class);
+ assertFalse("check number of spaces", fromJson.getKey().contains(" "));
+ assertEquals("check returned key", "AAA AAA", fromJson.getKey());
+
+ ServiceReqDetails serviceDetails = getServiceDetails();
+
+ serviceDetails.setUniqueId(serviceId);
+
+ // serviceUtils.addServiceMandatoryArtifacts(user,
+ // createServiceResponse);
+
+ certifyService(user, serviceDetails, null);
+
+ }
+
+ @Test
+ public void createCascadeResource() {
+
+ // TODO: to check after rebase
+
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+ String newResourceNameSuffix = "aa";
+
+ RestResponse createResourceResponse = null;
+ try {
+
+ createResourceResponse = createResource(resource, user);
+ assertEquals("check invalid type", 201, createResourceResponse.getErrorCode().intValue());
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ String resourceVersion = "0.1";
+ // resourceUtils.addResourceMandatoryArtifacts(user,
+ // createResourceResponse);
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ resource.setUniqueId(resourceId);
+ Resource certifiedResource = certifyResource(user, resource, resourceVersion, 1);
+
+ ResourceReqDetails newResourceDetails = getResource();
+ String newResourceName = newResourceDetails.getName() + newResourceNameSuffix;
+ newResourceDetails.setName(newResourceName);
+ List<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add(certifiedResource.getName());
+ newResourceDetails.setDerivedFrom(derivedFrom);
+ newResourceDetails.getTags().add(newResourceName);
+
+ user.setUserId(UserRoleEnum.ADMIN.getUserId());
+ RestResponse newCreateResourceResponse = createResource(newResourceDetails, user);
+ assertEquals("Check response code after creating resource", 201, newCreateResourceResponse.getErrorCode().intValue());
+ Resource newResource = gson.fromJson(newCreateResourceResponse.getResponse(), Resource.class);
+
+ RestResponse allAdditionalInformation = getResourceAllAdditionalInformation(newResource.getUniqueId(), user);
+
+ assertNotNull("check response object is not null after update additional information", allAdditionalInformation);
+ assertNotNull("check error code exists in response after additional information", allAdditionalInformation.getErrorCode());
+ assertEquals("Check response code after additional information", 200, allAdditionalInformation.getErrorCode().intValue());
+
+ AdditionalInformationDefinition updatedJson = gson.fromJson(allAdditionalInformation.getResponse(), AdditionalInformationDefinition.class);
+ assertEquals("check number of parameters", 0, updatedJson.getParameters().size());
+ // AdditionalInfoParameterInfo info =
+ // updatedJson.getParameters().iterator().next();
+
+ String newResourceId = newResource.getUniqueId();
+ createProperty = createResourceAdditionalInformation(newResourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ allAdditionalInformation = getResourceAllAdditionalInformation(newResourceId, user);
+
+ assertNotNull("check response object is not null after update additional information", allAdditionalInformation);
+ assertNotNull("check error code exists in response after additional information", allAdditionalInformation.getErrorCode());
+ assertEquals("Check response code after additional information", 200, allAdditionalInformation.getErrorCode().intValue());
+
+ updatedJson = gson.fromJson(allAdditionalInformation.getResponse(), AdditionalInformationDefinition.class);
+ assertEquals("check number of parameters", 1, updatedJson.getParameters().size());
+
+ } catch (IOException e) {
+ assertTrue(false);
+ }
+
+ }
+
+ @Test
+ public void createSamePropertyAfterCiCOResource() {
+
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ RestResponse createResourceResponse = null;
+ try {
+
+ createResourceResponse = createResource(resource, user);
+ assertEquals("check invalid type", 201, createResourceResponse.getErrorCode().intValue());
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ String resourceVersion = "0.1";
+ // resourceUtils.addResourceMandatoryArtifacts(user,
+ // createResourceResponse);
+
+ String key = "AAA AAA";
+ String value = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ resource.setUniqueId(resourceId);
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKIN);
+
+ assertNotNull("check response object is not null after create user", checkInResponse);
+ assertNotNull("check error code exists in response after create user", checkInResponse.getErrorCode());
+ assertEquals("Check response code after create user", 200, checkInResponse.getErrorCode().intValue());
+
+ Resource resourceAfterOperation = gson.fromJson(checkInResponse.getResponse(), Resource.class);
+ assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().size());
+ assertEquals("check size of additional information", 1, resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ RestResponse checkOutResponse = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT);
+
+ assertNotNull("check response object is not null after create user", checkOutResponse);
+ assertNotNull("check error code exists in response after create user", checkOutResponse.getErrorCode());
+ assertEquals("Check response code after create user", 200, checkOutResponse.getErrorCode().intValue());
+
+ Resource resourceAfterCoOperation = gson.fromJson(checkOutResponse.getResponse(), Resource.class);
+ assertEquals("check size of additional information", 1, resourceAfterCoOperation.getAdditionalInformation().size());
+ assertEquals("check size of additional information", 1, resourceAfterCoOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ String newResourceId = ResponseParser.getUniqueIdFromResponse(checkOutResponse);
+
+ String key2 = "ZZZ";
+ String value2 = "BBBB";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo2 = new AdditionalInfoParameterInfo(null, key2, value2);
+
+ RestResponse createProperty2 = createResourceAdditionalInformation(newResourceId, additionalInfoParameterInfo2, user);
+ assertNotNull("check response object is not null after create property", createProperty2);
+ assertNotNull("check error code exists in response after create property", createProperty2.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty2.getErrorCode().intValue());
+
+ RestResponse afterCreateAI = ResourceRestUtils.getResource(user, newResourceId);
+ Resource resourceNew = gson.fromJson(afterCreateAI.getResponse(), Resource.class);
+ assertEquals("check size of additional information", 1, resourceNew.getAdditionalInformation().size());
+ assertEquals("check size of additional information", 2, resourceNew.getAdditionalInformation().get(0).getParameters().size());
+
+ resource.setUniqueId(newResourceId);
+ Resource certifiedResource = certifyResource(user, resource, resourceVersion, 2);
+ assertEquals("check size of additional information", 1, certifiedResource.getAdditionalInformation().size());
+ assertEquals("check size of additional information", 2, certifiedResource.getAdditionalInformation().get(0).getParameters().size());
+
+ user.setUserId(UserRoleEnum.DESIGNER.getUserId());
+ resource.setUniqueId(certifiedResource.getUniqueId());
+ RestResponse checkOutResponseAfterCertify = LifecycleRestUtils.changeResourceState(resource, user, resourceVersion, LifeCycleStatesEnum.CHECKOUT);
+
+ assertNotNull("check response object is not null after create user", checkOutResponseAfterCertify);
+ assertNotNull("check error code exists in response after create user", checkOutResponseAfterCertify.getErrorCode());
+ assertEquals("Check response code after create user", 200, checkOutResponseAfterCertify.getErrorCode().intValue());
+
+ Resource resourceAfterCertifyCoOperation = gson.fromJson(checkOutResponseAfterCertify.getResponse(), Resource.class);
+ assertEquals("check size of additional information", 1, resourceAfterCertifyCoOperation.getAdditionalInformation().size());
+ assertEquals("check size of additional information", 2, resourceAfterCertifyCoOperation.getAdditionalInformation().get(0).getParameters().size());
+
+ } catch (IOException e) {
+ assertTrue(false);
+ }
+
+ }
+
+ // public Resource certifyService(User user, ServiceReqDetails service,
+ // String resourceVersion) throws Exception {
+ //
+ // RestResponse checkInResponse =
+ // LifecycleRestUtils.changeServiceState(service, user, resourceVersion,
+ // LifeCycleStates.CHECKIN);
+ //
+ // assertNotNull("check response object is not null after create user",
+ // checkInResponse);
+ // assertNotNull("check error code exists in response after create user",
+ // checkInResponse.getErrorCode());
+ // assertEquals("Check response code after create user", 200,
+ // checkInResponse.getErrorCode().intValue());
+ //
+ // Resource resourceAfterOperation =
+ // gson.fromJson(checkInResponse.getResponse(), Resource.class);
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().size());
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+ //
+ //// TODO Andrey
+ // createAndAddCertResourceToService(service, user);
+ //
+ // RestResponse req4certResponse =
+ // LifecycleRestUtils.changeServiceState(service, user, resourceVersion,
+ // LifeCycleStates.CERTIFICATIONREQUEST);
+ //
+ // assertNotNull("check response object is not null after create user",
+ // req4certResponse);
+ // assertEquals("Check response code after checkout resource", 200,
+ // req4certResponse.getErrorCode().intValue());
+ //
+ // resourceAfterOperation = gson.fromJson(req4certResponse.getResponse(),
+ // Resource.class);
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().size());
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+ //
+ // //change modifier
+ // user.setUserId(UserRoleEnum.TESTER.getUserId());
+ //
+ // //start certification
+ // RestResponse startCertResourceResponse3 =
+ // LifecycleRestUtils.changeServiceState(service, user, resourceVersion,
+ // LifeCycleStates.STARTCERTIFICATION);
+ // assertNotNull("check response object is not null after create user",
+ // startCertResourceResponse3);
+ // assertEquals("Check response code after checkout resource", 200,
+ // startCertResourceResponse3.getErrorCode().intValue());
+ //
+ // resourceAfterOperation =
+ // gson.fromJson(startCertResourceResponse3.getResponse(), Resource.class);
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().size());
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+ //
+ // //certify
+ //
+ // RestResponse certifyResponse =
+ // LifecycleRestUtils.changeServiceState(service, user, resourceVersion,
+ // LifeCycleStates.CERTIFY);
+ // assertNotNull("check response object is not null after create user",
+ // certifyResponse);
+ // assertEquals("Check response code after checkout resource", 200,
+ // certifyResponse.getErrorCode().intValue());
+ //
+ // resourceAfterOperation = gson.fromJson(certifyResponse.getResponse(),
+ // Resource.class);
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().size());
+ // assertEquals("check size of additional information", 1,
+ // resourceAfterOperation.getAdditionalInformation().get(0).getParameters().size());
+ //
+ // Resource certifyResource = gson.fromJson(certifyResponse.getResponse(),
+ // Resource.class);
+ // return certifyResource;
+ // }
+
+ private void createAndAddCertResourceToService(ServiceReqDetails serviceDetails, User user) throws Exception {
+
+ User sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+
+ RestResponse response = ResourceRestUtils.createResource(resourceDetails, user);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetails.getUniqueId());
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, user, resourceDetails.getUniqueId());
+ assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), response.getErrorCode() == 200);
+
+ // certified resource
+ // response = LCSbaseTest.certifyResource(resourceDetails);
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, LifeCycleStatesEnum.CHECKIN);
+ assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, user, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200);
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterUser, LifeCycleStatesEnum.CERTIFY);
+ assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200);
+
+ // add resource instance with HEAT deployment artifact to the service
+ restResponseResource = LifecycleRestUtils.changeServiceState(serviceDetails, user, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertTrue("certify resource request returned status:" + restResponseResource.getErrorCode(), response.getErrorCode() == 200);
+ resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, user, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertTrue("response code is not 201, returned: " + response.getErrorCode(), response.getErrorCode() == 201);
+ }
+
+ @Test
+ public void createResourceAdditionalInformationTestAddValue() throws Exception {
+ User user = getUser();
+ ResourceReqDetails resource = getResource();
+
+ // deleteResource(resourceId, user);
+ RestResponse createResourceResponse = createResource(resource, user);
+
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResourceResponse);
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse);
+ assertNotNull("check error code exists in response after create resource", createResourceResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResourceResponse.getErrorCode().intValue());
+
+ String key = "AAA AAA";
+ String value = "";
+
+ AdditionalInfoParameterInfo additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ RestResponse createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ value = "";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 400, createProperty.getErrorCode().intValue());
+
+ value = "----<b></b><>;";
+
+ additionalInfoParameterInfo = new AdditionalInfoParameterInfo(null, key, value);
+
+ createProperty = createResourceAdditionalInformation(resourceId, additionalInfoParameterInfo, user);
+ assertNotNull("check response object is not null after create property", createProperty);
+ assertNotNull("check error code exists in response after create property", createProperty.getErrorCode());
+ assertEquals("Check response code after create property", 201, createProperty.getErrorCode().intValue());
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java
new file mode 100644
index 0000000000..6ba1b2ccca
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentInstancePropertyTest.java
@@ -0,0 +1,1263 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.property;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import fj.data.Either;
+
+// open bug for this class: DE199108 - closed, DE199741
+public class ComponentInstancePropertyTest extends ComponentBaseTest {
+
+ protected Resource basicVFC;
+ protected Resource vfc1FromBasicVFC;
+ protected Resource vfc2FromVfc1;
+ protected Resource vfResource;
+
+ private List<ComponentInstanceProperty> expectedPropertyList;
+ private List<ComponentInstanceProperty> actualPropertyList;
+ // protected String updatedStringValue = "{Not Default String Value}";
+ protected String updatedStringValue = "Not Default String Value";
+ protected String updatedIntegerValue = "666";
+ protected String updatedBooleanValue = "false";
+ protected String newStringPropName = "stringProp2";
+ protected String newIntegerPropName = "integerProp2";
+ protected String newBooleanPropName = "booleanProp2";
+ // bug DE199741 protected String newStringPropValue = "<second string
+ // value>";
+ protected String newStringPropValue = "second string value";
+ protected String newIntegerPropValue = "888";
+ protected String newBooleanPropValue = "false";
+
+ @BeforeMethod
+ public void init() {
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ComponentInstancePropertyTest() {
+ super(name, ComponentInstancePropertyTest.class.getName());
+ }
+
+ // --------------Regular
+ // resource-------------------------------------------------------------------------------
+
+ @Test
+ public void nestedResourceProperty3Levels() throws Exception {
+
+ // first res
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ // second resource
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ // third resource
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ // verify property
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, actualPropertyList);
+ assertTrue("check list size failed, expected 3", actualPropertyList.size() == 3);
+
+ }
+
+ // --------------VF
+ // resource-----------------------------------------------------------
+
+ @Test
+ public void nestedVfResourceProperty3Levels() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ // verify property
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+ }
+
+ @Test
+ public void nestedVfResourceProperty3LevelsAndCpWithProp() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // four resource
+ Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP,
+ NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty();
+ cpStringProperty.setName("Different Name");
+ cpStringProperty.setPropertyDefaultValue("Different value from default");
+ AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, cp, expectedPropertyList,
+ vfResource);
+ // verify property
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+ }
+
+ @Test
+ public void nestedCertifiedVfResourceProperty3Levels() throws Exception {
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CERTIFY, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ // verify property
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+ }
+
+ @Test
+ public void nestedVfResourceProperty3Levels2SameResInstances() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ // verify property
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+ }
+
+ // ------------------update resource
+ // property-----------------------------------
+
+ @Test
+ public void nestedVfResourceProperty3LevelsUpdateFirstLevelProperty() throws Exception {
+ // first res
+ basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addDefaultPropertyToResource(PropertyTypeEnum.STRING, basicVFC, UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+
+ // verify property
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedStringValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ @Test
+ public void nestedVfResourceProperty3LevelsUpdateSecondLevelProperty() throws Exception {
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+
+ // second resource
+ vfc1FromBasicVFC = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC,
+ basicVFC, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left().value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addCustomPropertyToResource(ElementFactory.getDefaultIntegerProperty(), vfc1FromBasicVFC,
+ UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(vfc1FromBasicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY,
+ true);
+
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+
+ // verify property
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedIntegerValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue(
+ "expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS
+ + " ,but was " + updatePropertyValueOnResourceInstance.getErrorCode(),
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated properly",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ @Test
+ public void nestedVfResourceProperty3LevelsUpdateThirdLevelProperty() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+
+ // third resource
+ vfc2FromVfc1 = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC,
+ vfc1FromBasicVFC, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addCustomPropertyToResource(ElementFactory.getDefaultBooleanProperty(), vfc2FromVfc1,
+ UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(vfc2FromVfc1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN,
+ true);
+
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+
+ // verify property
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedBooleanValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(vfResource, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ // ---------------------Service------------------------------------------------------------------------
+
+ /**
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1)
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3Levels() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ /**
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1)
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3LevelsAndVfProperty() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ PropertyReqDetails propDetails = ElementFactory.getDefaultBooleanProperty();
+ propDetails.setName(newBooleanPropName);
+ propDetails.setPropertyDefaultValue(newBooleanPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true);
+ propDetails = ElementFactory.getDefaultStringProperty();
+ propDetails.setName(newStringPropName);
+ propDetails.setPropertyDefaultValue(newStringPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true);
+ propDetails = ElementFactory.getDefaultIntegerProperty();
+ propDetails.setName(newIntegerPropName);
+ propDetails.setPropertyDefaultValue(newIntegerPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(propDetails, vfResource, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfResource, expectedPropertyList);
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ /**
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1) CP(VF inst) (p5)
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3LevelsAndCp() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // four resource
+ Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP,
+ NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty();
+ cpStringProperty.setName("Different Name");
+ cpStringProperty.setPropertyDefaultValue("Different value from default");
+ AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, cp, expectedPropertyList,
+ vfResource);
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ /**
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1) CP(inst) (p5)
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3LevelsAndCpResInst() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ // expectedPropertyList =
+ // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1,
+ // expectedPropertyList);
+
+ // four resource
+ Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP,
+ NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty();
+ cpStringProperty.setName("Different Name");
+ cpStringProperty.setPropertyDefaultValue("Different value from default");
+ AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList);
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ /**
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) | (p3) (p2) (p1)
+ * | (VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1)
+ *
+ * VF2(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) | (p3') (p2') (p1') |
+ * (VFC(inst)-->VFC-->VFC-->VFC) (p3) (p2) (p1)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3Levels2SameResInstances() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1, expectedPropertyList);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ // verify property
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnResource(componentInstDetails, vfc2FromVfc1, expectedPropertyList,
+ vfResource);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ // service test template
+ /**
+ * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3LevelsAndSelfVfProperty() throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+ PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty();
+ newProp.setName(newStringPropName);
+ newProp.setPropertyDefaultValue(newStringPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ }
+
+ /**
+ * update property(p4)
+ *
+ *
+ * VFC(p1) ^ | VFC(p2) ^ | Service-->VF(inst)-->VF-->(VFC(inst)-->VFC(p3)
+ * (p4)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3LevelsAndSelfVfProperty_UpdateVfproperty() throws Exception {
+ // Create VFC(check-in state) derived from another resource
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+
+ // add property to VF
+ PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty();
+ newProp.setName(newStringPropName);
+ newProp.setPropertyDefaultValue(newStringPropValue);
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update VF instance property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedStringValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ /**
+ * update property(p1)
+ * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance1LevelProperty()
+ throws Exception {
+
+ basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addDefaultPropertyToResource(PropertyTypeEnum.STRING, basicVFC, UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // verify property
+ PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty();
+ newProp.setName(newStringPropName);
+ newProp.setPropertyDefaultValue(newStringPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update VF property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedStringValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ /**
+ * update property(p2)
+ * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance2LevelProperty()
+ throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC,
+ basicVFC, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left().value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addCustomPropertyToResource(ElementFactory.getDefaultIntegerProperty(), vfc1FromBasicVFC,
+ UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(vfc1FromBasicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY,
+ true);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+
+ // verify property
+ PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty();
+ newProp.setName(newStringPropName);
+ newProp.setPropertyDefaultValue(newStringPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update VF property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedIntegerValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ /**
+ * update property(p3)
+ * Service-->VF(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1)
+ */
+ @Test
+ public void serviceNestedVfResourceProperty3LevelsAndSelfVfPropertyUpdateVfInheritance3LevelProperty()
+ throws Exception {
+
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC,
+ vfc1FromBasicVFC, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
+ Either<ComponentInstanceProperty, RestResponse> propDetailsToUpdate = AtomicOperationUtils
+ .addCustomPropertyToResource(ElementFactory.getDefaultBooleanProperty(), vfc2FromVfc1,
+ UserRoleEnum.DESIGNER, true);
+ String propNameToUpdate = propDetailsToUpdate.left().value().getName();
+ String propTypeToUpdate = propDetailsToUpdate.left().value().getType();
+ AtomicOperationUtils.changeComponentState(vfc2FromVfc1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN,
+ true);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // verify property
+ PropertyReqDetails newProp = ElementFactory.getDefaultStringProperty();
+ newProp.setName(newStringPropName);
+ newProp.setPropertyDefaultValue(newStringPropValue);
+ AtomicOperationUtils.addCustomPropertyToResource(newProp, vfResource, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ // update VF property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils
+ .getPropFromListByPropNameAndType(actualPropertyList, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedBooleanValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, null);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+
+ }
+
+ /**
+ * update property p5'
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1) CP(inst on VF) (p5) CP(inst) (p5')
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3LevelsAndCpOnVfUpdateCpInstanceOfService() throws Exception {
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CHECKIN, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ // expectedPropertyList =
+ // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1,
+ // expectedPropertyList);
+
+ // four resource
+ Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP,
+ NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty();
+ cpStringProperty.setName("Different Name");
+ cpStringProperty.setPropertyDefaultValue("Different value from default");
+ AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER);
+ // create VF + add RI
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList);
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ // service = AtomicOperationUtils.getServiceObject(service,
+ // UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ String propNameToUpdate = "cidr";
+ String propTypeToUpdate = "string";
+
+ // update CP property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(
+ service, componentInstDetails, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedStringValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ List<String> path = expectedUpdatePropDetails.getPath();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, path);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+ }
+
+ /**
+ * update property p5
+ * Service-->VF1(inst)-->VF-->(VFC(inst)-->VFC-->VFC-->VFC) (p4) (p3) (p2)
+ * (p1) CP(inst on VF) (p5) CP(inst) (p5')
+ */
+ @Test
+ public void serviceWithNestedResourceProperty3LevelsAndCpOnVfUpdateCpInstanceOfVf() throws Exception {
+ basicVFC = createResourceWithProperty(ElementFactory.getDefaultStringProperty(), LifeCycleStatesEnum.CERTIFY);
+ vfc1FromBasicVFC = createResourceWithPropertyDerivedFromOtherResource(
+ ElementFactory.getDefaultIntegerProperty(), LifeCycleStatesEnum.CERTIFY, basicVFC);
+ vfc2FromVfc1 = createResourceWithPropertyDerivedFromOtherResource(ElementFactory.getDefaultBooleanProperty(),
+ LifeCycleStatesEnum.CERTIFY, vfc1FromBasicVFC);
+ vfc2FromVfc1 = AtomicOperationUtils.getResourceObject(vfc2FromVfc1, UserRoleEnum.DESIGNER);
+ // expectedPropertyList =
+ // PropertyRestUtils.addResourcePropertiesToList(vfc2FromVfc1,
+ // expectedPropertyList);
+
+ // four resource
+ Resource cp = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP,
+ NormativeTypesEnum.NETWORK, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails cpStringProperty = ElementFactory.getDefaultStringProperty();
+ cpStringProperty.setName("Different Name");
+ cpStringProperty.setPropertyDefaultValue("Different value from default");
+ AtomicOperationUtils.addCustomPropertyToResource(cpStringProperty, cp, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(cp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ // create VF + add RI
+ cp = AtomicOperationUtils.getResourceObject(cp, UserRoleEnum.DESIGNER);
+ vfResource = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ ComponentInstance componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfc2FromVfc1, vfResource, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, vfResource, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ vfResource = AtomicOperationUtils.getResourceObject(vfResource, UserRoleEnum.DESIGNER);
+
+ // Service
+ expectedPropertyList = new ArrayList<ComponentInstanceProperty>();
+ actualPropertyList = new ArrayList<ComponentInstanceProperty>();
+ expectedPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(vfResource, expectedPropertyList,
+ null);
+ expectedPropertyList = PropertyRestUtils.addResourcePropertiesToList(cp, expectedPropertyList);
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vfResource, service, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ componentInstDetails = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp, service, UserRoleEnum.DESIGNER, true).left().value();
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ PropertyRestUtils.updatePropertyListWithPathOnComponentInstance(componentInstDetails, service,
+ expectedPropertyList);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+ PropertyRestUtils.comparePropertyLists(expectedPropertyList, actualPropertyList, false);
+
+ String propNameToUpdate = "cidr";
+ String propTypeToUpdate = "string";
+
+ // update CP property
+ ComponentInstanceProperty expectedUpdatePropDetails = PropertyRestUtils.getCompPropInstListByInstIdAndPropName(
+ service, componentInstDetails, propNameToUpdate, propTypeToUpdate);
+ expectedUpdatePropDetails.setValue(updatedStringValue);
+ String propUniqeId = expectedUpdatePropDetails.getUniqueId();
+ List<String> path = expectedUpdatePropDetails.getPath();
+ RestResponse updatePropertyValueOnResourceInstance = ComponentInstanceRestUtils
+ .updatePropertyValueOnResourceInstance(service, componentInstDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), expectedUpdatePropDetails);
+ assertTrue("expected updatePropertyValueOnResourceInstance response code: " + BaseRestUtils.STATUS_CODE_SUCCESS,
+ updatePropertyValueOnResourceInstance.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ service = AtomicOperationUtils.getServiceObject(service, UserRoleEnum.DESIGNER);
+
+ actualPropertyList = new ArrayList<>();
+ actualPropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, actualPropertyList, null);
+
+ ComponentInstanceProperty actualUpdatedPropDetails = PropertyRestUtils
+ .getPropFromListByPropIdAndPath(actualPropertyList, propUniqeId, path);
+ assertTrue("property was not updated propely",
+ PropertyRestUtils.comparePropertyObjects(expectedUpdatePropDetails, actualUpdatedPropDetails, true));
+ }
+
+ // -------------------Methods--------------------------
+ public static PropertyDataDefinition convertToPropertyDataDefinitionObject(PropertyReqDetails prop) {
+ PropertyDataDefinition propDataDef = new PropertyDataDefinition();
+ propDataDef.setDefaultValue(prop.getPropertyDefaultValue());
+ propDataDef.setType(prop.getPropertyType());
+ propDataDef.setPassword(prop.getPropertyPassword());
+ propDataDef.setDescription(prop.getPropertyDescription());
+ return propDataDef;
+ }
+
+ protected Resource createResourceWithPropertyDerivedFromOtherResource(PropertyReqDetails propertyReqDetails,
+ LifeCycleStatesEnum state, Resource derivedFromResource) throws Exception {
+ Resource resource = AtomicOperationUtils.createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC,
+ derivedFromResource, ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ if (propertyReqDetails != null) {
+ AtomicOperationUtils.addCustomPropertyToResource(propertyReqDetails, resource, UserRoleEnum.DESIGNER, true);
+ }
+ AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, state, true);
+ return AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER);
+ // return resource;
+ }
+
+ protected Resource createResourceWithProperty(PropertyReqDetails propertyReqDetails, LifeCycleStatesEnum state)
+ throws Exception {
+ Resource resource = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ if (propertyReqDetails != null) {
+ AtomicOperationUtils.addCustomPropertyToResource(propertyReqDetails, resource, UserRoleEnum.DESIGNER, true);
+ }
+ AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, state, true);
+ return AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java
new file mode 100644
index 0000000000..e1c4c18270
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/ComponentProperty.java
@@ -0,0 +1,1796 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.property;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class ComponentProperty extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ComponentProperty() {
+ super(name, ComponentProperty.class.getName());
+ }
+
+ @DataProvider
+ private static final Object[][] propertiesListDefaultValueSuccessFlow() throws IOException, Exception {
+ return new Object[][] {
+ // integer
+ { "integer", "[1,2]", "[1,2]" },
+ { "tosca.datatypes.Credential",
+ "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2\"}]",
+ "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2\"}]" },
+ { "tosca.datatypes.Credential",
+ "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol<br>2\",\"token\":\"token2 2\"}]",
+ "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token\":\"token2 2\"}]" },
+ { "tosca.datatypes.Credential", null, null }, { "tosca.datatypes.Credential", "[]", "[]" },
+ { "integer", "[1,2,1,2]", "[1,2,1,2]" }, { "integer", "[1,,2]", "[1,2]" },
+ { "integer", "[1,null,2]", "[1,2]" }, { "integer", "[1,2,null]", "[1,2]" },
+ { "integer", "[null,1,2]", "[1,2]" }, { "integer", "[1,,2]", "[1,2]" },
+ { "integer", "[,1,2]", "[1,2]" },
+ // {"integer",
+ // "[1000000000000000000000000000000000000000000000000000,2]" ,
+ // "[1000000000000000000000000000000000000000000000000000,2]"},
+ { "integer", "[100000000,2]", "[100000000,2]" }, // Andrey, in
+ // success
+ // flow
+ // integer
+ // max value
+ // is
+ // 2147483647
+ { "integer", null, null }, // no default value
+ { "integer",
+ "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]",
+ "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]" },
+ // boolean
+ { "boolean", "[true,false]", "[true,false]" },
+ { "boolean", "[true,false,false]", "[true,false,false]" },
+ { "boolean", "[null,true,false]", "[true,false]" }, { "boolean", "[true,false,null]", "[true,false]" },
+ { "boolean", "[true,,false]", "[true,false]" }, { "boolean", "[true,false,]", "[true,false]" },
+ { "boolean", "[,true,false]", "[true,false]" }, { "boolean", null, null },
+ // DE199713 - Default value for property type Boolean should
+ // support also the following values: true, t , one , 1 ,
+ // false, f , off , 0
+ { "boolean", "[on,off]", "[true,false]" }, { "boolean", "[ON,OFF]", "[true,false]" },
+ { "boolean", "[On,Off]", "[true,false]" }, { "boolean", "[yes,no]", "[true,false]" },
+ { "boolean", "[YES,NO]", "[true,false]" }, { "boolean", "[Yes,No]", "[true,false]" },
+ { "boolean", "[y,n]", "[true,false]" }, { "boolean", "[Y,N]", "[true,false]" },
+ // float
+ { "float", "[10.0,0.0]", "[10.0,0.0]" }, { "float", "[10,0]", "[10,0]" }, // contain
+ // integer
+ { "float", "[-10,-5.30]", "[-10,-5.30]" }, // Negative numbers
+ { "float", "[10,null,0]", "[10,0]" }, { "float", "[null,10,0]", "[10,0]" },
+ { "float", "[10,0,null]", "[10,0]" },
+ { "float", "[10,0.1111111111111111111111111111111111111111]",
+ "[10,0.1111111111111111111111111111111111111111]" },
+ { "float", "[10, ,7.3 ]", "[10,7.3]" }, { "float", "[10 , 7.3 , ]", "[10,7.3]" },
+ { "float", "[, , 10 , 7.3 , ]", "[10,7.3]" }, { "float", "[4.7f, -5.5f ]", "[4.7,-5.5]" },
+ { "float", "[4.7f, 6.3 ,6.3, 4.7f]", "[4.7,6.3,6.3,4.7]" }, // duplicate
+ // value
+ { "float", null, null }, { "string", "[aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" },
+
+ { "string",
+ "[1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2]",
+ "[\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\",\"1\",\"2\"]" },
+ { "string", "[aaaa , AAAA, 1, off , true, false ]",
+ "[\"aaaa\",\"AAAA\",\"1\",\"off\",\"true\",\"false\"]" },
+ { "string", "[aaaa , AAAA, aaaa, Aaaa , aaaa ]", "[\"aaaa\",\"AAAA\",\"aaaa\",\"Aaaa\",\"aaaa\"]" },
+ { "string", "[aaaa , AAAA, , ]", "[\"aaaa\",\"AAAA\"]" },
+ { "string", "[ , aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" },
+ { "string", "[ aaaa , , AAAA ]", "[\"aaaa\",\"AAAA\"]" },
+ { "string", "[ aaaa , AAAA, null ]", "[\"aaaa\",\"AAAA\"]" },
+ { "string", "[ null, aaaa , AAAA ]", "[\"aaaa\",\"AAAA\"]" },
+ { "string", "[ aaaa , null , AAAA ]", "[\"aaaa\",\"AAAA\"]" }, { "string", null, null }, // without
+ // default
+ // values
+ // -
+ // Property
+ // will
+ // be
+ // without
+ // default
+ // parameter
+ { "string", "[ <b>AAA</b> ]", "[\"AAA\"]" }, // BUG DE199715 -
+ // Error 400
+ // response
+ // received
+ // while adding
+ // property with
+ // default value
+ // contain HTML
+ // tags.
+ // Need to check
+ // whether / is
+ // legal in yaml
+
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] invalidListProperties() throws IOException, Exception {
+ return new Object[][] {
+
+ { "integer", "[1,aaa]" },
+ { "tosca.datatypes.Credential",
+ "[{\"protocol\":\"protocol1\",\"token\":\"token1\"},{\"protocol\":\"protocol2\",\"token1\":\"token2\"}]" },
+ { "integer", "[1,false]" }, { "integer", "[1,3.5]" }, { "integer", "[1,3#]" },
+ { "boolean", "[true,3.5]" }, { "boolean", "[true,1000]" }, { "boolean", "[false,trueee]" },
+ { "boolean", "[true,false!]" }, { "float", "[5.0000001,true]" }, { "float", "[0.0001,koko]" },
+ { "float", "[0.0001,6.3@]" }, { "float", "[0.0001f,6.3x]" }, };
+ }
+
+ @DataProvider
+ private static final Object[][] updatePropertiesListDefaultValueSuccessFlow() throws IOException, Exception {
+ return new Object[][] {
+ // integer
+ // Setting --- update properties
+ // -----------------------------------------------------------------------
+ { "integer", "[1,2]", "[1,2]", "integer", "[200,100]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[200,100,null]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[null, 200,100]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[200,null,100]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[200,100, ]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[ , 200,100 ]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[200 , ,100 ]", "[200,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", null, null },
+ { "integer", "[1,2]", "[1,2]", "integer", "[200 , 100 , 200, 100]", "[200,100,200,100]" },
+ //
+ // ////DE199829 update resource property schema_type is not
+ // updated
+ { "integer", "[1,2]", "[1,2]", "string", "[aaaa , bbbb ]", "[\"aaaa\",\"bbbb\"]" },
+ { "integer", "[1,2]", "[1,2]", "boolean", "[true , false ]", "[true,false]" },
+ { "integer", "[1,2]", "[1,2]", "float", "[3.5,4.8f ]", "[3.5,4.8]" },
+ // {"string", "[aaa,bbb]" , "[\"aaa\",\"bbb\"]","integer","[100,
+ // 200]" , "[\"100\",\"200\"]"},
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "integer", "[100, 200]", "[100,200]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "float", "[0.1f, 3.01]", "[0.1,3.01]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "boolean", "[true, false]", "[true,false]" },
+ { "float", "[1.2,2.3]", "[1.2,2.3]", "boolean", "[true, false]", "[true,false]" },
+ { "float", "[1.2,2.3]", "[1.2,2.3]", "integer", "[100, 200]", "[100,200]" },
+ { "float", "[1.2,2.3]", "[1.2,2.3]", "string", "[koko, moko]", "[\"koko\",\"moko\"]" },
+ { "boolean", "[true,false]", "[true,false]", "string", "[koko, moko]", "[\"koko\",\"moko\"]" },
+ // {"boolean", "[true,false]" ,
+ // "[\"true\",\"false\"]","integer","[100, 300000000000000]" ,
+ // "[\"100\",\"300000000000000\"]"},// Andrey, value not valid
+ // for integer success flow
+ { "boolean", "[true,false]", "[true,false]", "integer", "[100,2147483647]", "[100,2147483647]" }, // Andrey,
+ // in
+ // success
+ // flow
+ // integer
+ // max
+ // value
+ // is
+ // 2147483647
+ { "boolean", "[true,false]", "[true,false]", "float", "[3.000000000000002, 5.67f]",
+ "[3.000000000000002,5.67]" },
+ // ////DE199829
+ //
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx, yyy]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx , yyy ,null]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[null, xxx, yyy]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx ,null,yyy]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx ,yyy, ]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[ , xxx,yyy ]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx , ,yyy ]", "[\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[ xxx , yyy , xxx , yyy]",
+ "[\"xxx\",\"yyy\",\"xxx\",\"yyy\"]" },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", null, null },
+ { "string", "[aaa,bbb]", "[\"aaa\",\"bbb\"]", "string", "[xxx_-x, y__y--y]",
+ "[\"xxx_-x\",\"y__y--y\"]" },
+ // DE199715
+ // {"string", "[aaa,bbb]" , "[\"aaa\",\"bbb\"]", "string" ,
+ // "[\"<b>xxx</b>\", \"<b>yyy</b>\"]" , "[\"xxx\",\"yyy\"]"},
+ //
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , -0.1]", "[2.1,-0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1, 0.1 ,null]", "[2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[null , 2.1, 0.1]", "[2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1,null,0.1]", "[2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1,0.1, ]", "[2.1,0.1]" },
+ // {"float", "[1.00,0.02]" , "[1.00,0.02]","float","[ ,
+ // 2.00000000000001,0.00000000000000100 ]" ,
+ // "[2.00000000000001,0.00000000000000100]"},
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , ,0.1 ]", "[2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", null, null },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1f , ,0.1f ]", "[2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[2.1 , 0.1 , 2.1, 0.1]", "[2.1,0.1,2.1,0.1]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[200 , 100.11]", "[200,100.11]" },
+ { "float", "[1.00,0.02]", "[1.00,0.02]", "float", "[-2.35 , 100.11]", "[-2.35,100.11]" },
+ //
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[false , false]", "[false,false]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[false, true ,null]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[null , false, true]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[false,null,true]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[false ,true , ]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[ , false, true ]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", "[false , ,true ]", "[false,true]" },
+ { "boolean", "[true,false]", "[true,false]", "boolean", null, null }, { "boolean", "[true,false]",
+ "[true,false]", "boolean", "[false , true , false, true]", "[false,true,false,true]" }, };
+ }
+
+ @DataProvider
+ private static final Object[][] updatePropertiesListDefaultValueFailureFlow() throws IOException, Exception {
+ return new Object[][] {
+ // integer
+ // Setting --- update properties
+ // -----------------------------------------------------------------------
+ { "integer", "[1,2]", "[1,2]", "integer", "[aaa,bbb]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[true,false]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[1.0,100]" },
+ { "integer", "[1,2]", "[1,2]", "integer", "[@12,100]" },
+ { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[aaa, bbb]" },
+ { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[0.88, false]" },
+ { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[0.88g, 0.3]" },
+ { "float", "[0.11,0.22]", "[0.11,0.22]", "float", "[@0.88, 0.3]" },
+ { "boolean", "[true, false]", "[true,false]", "boolean", "[true, 100]" },
+ { "boolean", "[true, false]", "[true,false]", "boolean", "[false, 0.01]" },
+ { "boolean", "[true, false]", "[true,false]", "boolean", "[koko, true]" },
+ { "boolean", "[true, false]", "[true,false]", "boolean", "[@false, true]" },
+
+ };
+ }
+
+ // Map properties
+ @DataProvider
+ private static final Object[][] updatePropertiesMapDefaultValueSuccessFlow() throws IOException, Exception {
+ return new Object[][] {
+ // entrySchemaType , propertyDefaultValues ,
+ // expectedDefaultValue , newEntrySchemaType ,
+ // newPropertyDefaultValue , newExpectedDefaultValue
+ // integer
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":200,\"key2\":null , \"key3\":300}", "{\"key1\":200,\"key2\":null,\"key3\":300}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":null,\"key2\":200 , \"key3\":100}", "{\"key1\":null,\"key2\":200,\"key3\":100}" },
+ // string
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "string",
+ "{\"key1\":\"aaaa\" , \"key2\":\"aaaa\"}", "{\"key1\":\"aaaa\",\"key2\":\"aaaa\"}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "boolean",
+ "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "float",
+ "{\"key1\":3.5 , \"key2\":4.8f}", "{\"key1\":3.5,\"key2\":4.8}" },
+ // string
+ { "string", "{\"key1\":aaa , \"key2\":bbb}", "{\"key1\":\"aaa\",\"key2\":\"bbb\"}", "string",
+ "{\"key1\":xxx , \"key2\":yyy}", "{\"key1\":\"xxx\",\"key2\":\"yyy\"}" },
+ // float
+ { "float", "{\"key1\":1.00 , \"key2\":0.02}", "{\"key1\":1.00,\"key2\":0.02}", "float",
+ "{\"key1\":2.1, \"key2\":-0.1}", "{\"key1\":2.1,\"key2\":-0.1}" },
+ { "float", "{\"key1\":1.00 , \"key2\":0.02}", "{\"key1\":1.00,\"key2\":0.02}", "float",
+ "{\"key1\":2.1 , \"key2\":0.1 , \"key3\":null}", "{\"key1\":2.1,\"key2\":0.1,\"key3\":null}" },
+ // boolean
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":false , \"key2\":false}", "{\"key1\":false,\"key2\":false}" },
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":false , \"key2\":true , \"key3\":null}",
+ "{\"key1\":false,\"key2\":true,\"key3\":null}" },
+ // null
+ { "boolean", "{\"key1\":null , \"key2\":false}", "{\"key1\":null,\"key2\":false}", "boolean",
+ "{\"key1\":false , \"key2\":true , \"key3\":null}",
+ "{\"key1\":false,\"key2\":true,\"key3\":null}" },
+ // tosca.datatypes.Credential
+ { "tosca.datatypes.Credential",
+ "{\"key1\":{\"protocol\":\"protocol<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "tosca.datatypes.Credential",
+ "{\"key1\":{\"protocol\":\"protocol<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}" },
+
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] propertiesMapDefaultValueSuccessFlow() throws IOException, Exception {
+ return new Object[][] {
+
+ // entrySchemaType , propertyDefaultValues ,
+ // expectedDefaultValue
+ //
+ // {"string",
+ // "{\"vf_module_id\":{\"get_input\":\"vf_module_id\"},
+ // \"vnf_idw\": 2}",
+ // "{\"vf_module_id\":{\"get_input\":\"vf_module_id\"},
+ // \"vnf_idw\": 2}"},
+
+ // tosca.datatypes.Credential
+ { "tosca.datatypes.Credential",
+ "{\"key1\":{\"protocol\":\"protocol<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}" },
+ // integer
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}" },
+ { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":2}",
+ "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":2}" },
+ { "integer", "{\"key1\":1,\"key2\":null,\"key3\":1,\"key4\":2}",
+ "{\"key1\":1,\"key2\":null,\"key3\":1,\"key4\":2}" },
+ { "integer", "{\"key1\":null,\"key2\":1,\"key3\":1,\"key4\":2}",
+ "{\"key1\":null,\"key2\":1,\"key3\":1,\"key4\":2}" },
+ { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}",
+ "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" },
+ { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":NULL}",
+ "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" },
+ { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":Null}",
+ "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" },
+ { "integer", "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":nuLL}",
+ "{\"key1\":1,\"key2\":2,\"key3\":1,\"key4\":null}" },
+ { "integer", null, null }, // no default value
+ // //BUG
+ //// {"integer",
+ // "{\"key1\":1000000000000000000000000000000000000000000000000000,\"key2\":2}"
+ // ,"{\"key1\":1000000000000000000000000000000000000000000000000000,\"key2\":2}"},
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":true , \"key2\":false, \"key3\":false }",
+ "{\"key1\":true,\"key2\":false,\"key3\":false}" },
+ { "boolean", "{\"key1\":null , \"key2\":true, \"key3\":false }",
+ "{\"key1\":null,\"key2\":true,\"key3\":false}" },
+ { "boolean", "{\"key1\":true , \"key2\":Null, \"key3\":false }",
+ "{\"key1\":true,\"key2\":null,\"key3\":false}" },
+ { "boolean", "{\"key1\":true , \"key2\":false, \"key3\":nULL }",
+ "{\"key1\":true,\"key2\":false,\"key3\":null}" },
+ { "boolean", null, null },
+ { "boolean", "{\"key1\":on , \"key2\":off}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":ON , \"key2\":OFF}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":On , \"key2\":Off}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":yes , \"key2\":no}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":YES , \"key2\":NO}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":Yes , \"key2\":No}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":y , \"key2\":n}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{\"key1\":Y , \"key2\":N}", "{\"key1\":true,\"key2\":false}" },
+ { "boolean", "{null:false}", "{\"null\":false}" },
+ // float
+ { "float", "{\"key1\":10.0 , \"key2\":0.0}", "{\"key1\":10.0,\"key2\":0.0}" },
+ { "float", "{\"key1\":10 , \"key2\":0}", "{\"key1\":10,\"key2\":0}" }, // contain
+ // integer
+ { "float", "{\"key1\":null , \"key2\":Null}", "{\"key1\":null,\"key2\":null}" }, // contain
+ // null
+ { "float", "{\"key1\":3.5 , \"key2\":nULL}", "{\"key1\":3.5,\"key2\":null}" },
+ // BUG
+ { "float", "{\"key1\":3.5 , \"key2\":0.1111111111111111111111111111111111111111}",
+ "{\"key1\":3.5,\"key2\":0.1111111111111111111111111111111111111111}" },
+ { "float", "{\"key1\":4.7f , \"key2\":-5.5f}", "{\"key1\":4.7,\"key2\":-5.5}" },
+ { "float", "{\"key1\":4.7f , \"key2\":-5.5f, \"key3\":-5.5f}",
+ "{\"key1\":4.7,\"key2\":-5.5,\"key3\":-5.5}" },
+ { "boolean", null, null },
+ { "string", "{\"key1\":aaaa , \"key2\":AAAA}", "{\"key1\":\"aaaa\",\"key2\":\"AAAA\"}" },
+ { "string", "{\"key1\":off , \"key2\":true , \"key3\":1}",
+ "{\"key1\":\"off\",\"key2\":\"true\",\"key3\":\"1\"}" },
+ { "string", "{\"key1\":aaaa , \"key2\":Aaaa , \"key3\":aaaa}",
+ "{\"key1\":\"aaaa\",\"key2\":\"Aaaa\",\"key3\":\"aaaa\"}" },
+ { "string", "{\"key1\":aaaa , \"key2\":bbbb , \"key3\":null}",
+ "{\"key1\":\"aaaa\",\"key2\":\"bbbb\",\"key3\":null}" },
+ { "string", "{\"key1\":NULL , \"key2\":bbbb , \"key3\":aaaa}",
+ "{\"key1\":null,\"key2\":\"bbbb\",\"key3\":\"aaaa\"}" },
+ { "string", "{\"key1\":aaaa , \"key2\":Null , \"key3\":bbbb}",
+ "{\"key1\":\"aaaa\",\"key2\":null,\"key3\":\"bbbb\"}" },
+ { "string", null, null }, // without default values - Property
+ // will be without default parameter
+ { "string", "{\"key1\":\"<b>AAAA</b>\" }", "{\"key1\":\"AAAA\"}" },
+
+ };
+ }
+
+ @DataProvider
+ private static final Object[][] updatePropertiesMapDefaultValueFailureFlow() throws IOException, Exception {
+ return new Object[][] {
+
+ // integer
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":aaa , \"key2\":bbb}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":true , \"key2\":false}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":1.0 , \"key2\":100}" },
+ { "integer", "{\"key1\":1 , \"key2\":2}", "{\"key1\":1,\"key2\":2}", "integer",
+ "{\"key1\":12@ , \"key2\":100}" },
+ // float
+ { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float",
+ "{\"key1\":aaa , \"key2\":bbb}" },
+ { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float",
+ "{\"key1\":0.88 , \"key2\":false}" },
+ { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float",
+ "{\"key1\":0.88g , \"key2\":0.3}" },
+ { "float", "{\"key1\":0.11 , \"key2\":0.22}", "{\"key1\":0.11,\"key2\":0.22}", "float",
+ "{\"key1\":@0.88g , \"key2\":0.3}" },
+ // boolean
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":true , \"key2\":100}" },
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":false , \"key2\":0.01}" },
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":koko , \"key2\":true}" },
+ { "boolean", "{\"key1\":true , \"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":@false , \"key2\":true}" },
+ { "boolean", "{\"key1\":true,\"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{:false , \"key2\":true}" },
+ { "boolean", "{\"key1\":true,\"key2\":false}", "{\"key1\":true,\"key2\":false}", "boolean",
+ "{\"key1\":true , , \"key2\":false}" },
+ // tosca.datatypes.Credential
+ { "tosca.datatypes.Credential",
+ "{\"key1\":{\"protocol\":\"protocol<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "{\"key1\":{\"protocol\":\"protocol1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token\":\"token2\"}}",
+ "tosca.datatypes.Credential",
+ "{\"key1\":{\"protocol\":\"protocol<br>1\",\"token\":\"token1\"},\"key2\":{\"protocol\":\"protocol2\",\"token2\":\"token2\"}}" },
+
+ };
+ }
+
+ // US594938 - UPDATE PROPERTY
+ // DE199718
+ @Test(dataProvider = "updatePropertiesListDefaultValueFailureFlow")
+ public void updateDefaultValueOfResourcePropertyListFailureFlow(String entrySchemaType, String propertyDefaltValues,
+ String expecteddefaultValues, String newEntrySchemaType, String newPropertyDefaltValues) throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.setPropertyDefaultValue(propertyDefaltValues);
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // verify properties return from response
+ assertEquals("list", resourcePropertiesFromResponse.getType());
+ assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ // Update resource property type = "list"
+ propertyDetails.setPropertyDefaultValue(newPropertyDefaltValues);
+ propertyDetails.getSchema().getProperty().setType(newEntrySchemaType);
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(propertyDetails.getName());
+ variables.add(propertyDetails.getPropertyType());
+ variables.add(propertyDetails.getSchema().getProperty().getType());
+ variables.add(newPropertyDefaltValues);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables,
+ updatePropertyResponse.getResponse());
+ }
+
+ @Test
+ public void updatePropertyOfDerivedResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String derivedResourcePropertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ // second resource derived from basicVFC
+ Resource vfc1FromBasicVFC = AtomicOperationUtils
+ .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC,
+ ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ // add property Type list to second resource
+ PropertyReqDetails defaultListProperty = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(defaultListProperty, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Update property (list) of derived resource
+ RestResponse updatePropertyResponse = AtomicOperationUtils.updatePropertyOfResource(propertyDetails, basicVFC,
+ derivedResourcePropertyUniqueId, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[\"a\",\"b\"]");
+ }
+
+ @Test
+ public void updatePropertyOfNonDerivedResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ // second resource derived from basicVFC
+ Resource vfc1FromBasicVFC = AtomicOperationUtils
+ .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC,
+ ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ // add property Type list to second resource
+ PropertyReqDetails defaultListProperty = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(defaultListProperty, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // Update property (list) of derived resource
+ defaultListProperty.setPropertyDefaultValue("[1,2,3,4]");
+ String expectedDefaultValue = "[1,2,3,4]";
+ ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils
+ .updatePropertyOfResource(defaultListProperty, vfc1FromBasicVFC, propertyUniqueId,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+ assertEquals(resourcePropertyAfterUpdate.getType(), "list");
+ assertEquals(resourcePropertyAfterUpdate.getDefaultValue(), expectedDefaultValue);
+ assertEquals(resourcePropertyAfterUpdate.getSchema().getProperty().getType(),
+ defaultListProperty.getSchema().getProperty().getType()); // string/integer/boolean/float
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(vfc1FromBasicVFC.getUniqueId());
+ String expectedDefaultValueFromDerivedResource = "[\"a\",\"b\"]";
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ resource.getProperties().get(0).getDefaultValue().equals(expectedDefaultValue);
+ resource.getProperties().get(1).getDefaultValue().equals(expectedDefaultValueFromDerivedResource);
+ }
+
+ @Test
+ public void updateListPropertyToNonCheckedOutResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ // Update resource property type = "list"
+ propertyDetails.setPropertyDefaultValue("[3,4]");
+ propertyDetails.getSchema().getProperty().setType("integer");
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ @Test
+ public void updateListPropertyResourceByNonResouceOwner() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // AtomicOperationUtils.changeComponentState(basicVFC,
+ // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ // Update resource property type = "list"
+ propertyDetails.setPropertyDefaultValue("[3,4]");
+ propertyDetails.getSchema().getProperty().setType("integer");
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER2, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ @Test
+ public void updateListPropertyResourceByTester() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // AtomicOperationUtils.changeComponentState(basicVFC,
+ // UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ // Update resource property type = "list"
+ propertyDetails.setPropertyDefaultValue("[3,4]");
+ propertyDetails.getSchema().getProperty().setType("integer");
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.TESTER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ // DE199964
+ @Test(enabled = false)
+ public void updateListPropertyToNonExistingResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ String resourceUniqueId = basicVFC.getUniqueId();
+ basicVFC.setUniqueId("1111111");
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(basicVFC.getUniqueId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ basicVFC.setUniqueId(resourceUniqueId);
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ // DE199725
+ @Test
+ public void updateResourcePropertyListNonSupportedPropertyType() throws Exception { // Not
+ // "list"
+ // type
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // update resource property
+ String propertyType = "listttttttt";
+ propertyDetails.setPropertyType(propertyType);
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(propertyDetails.getPropertyType()); // property data type
+ // (koko instead
+ // list)
+ variables.add(propertyDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables,
+ updatePropertyResponse.getResponse());
+ // Verify resource's priority list did not changed
+ propertyDetails.setPropertyType("list");
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ @Test(enabled = false) // DE199732
+ public void updateResourcePropertyListNonSupportedEntrySchemaType() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String PropertyDefaultValue = "[2,3]";
+ propertyDetails.setPropertyDefaultValue(PropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType("integer");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // update resource property
+ String EntrySchemaType = "integerrrrrr";
+ propertyDetails.getSchema().getProperty().setType(EntrySchemaType);
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(EntrySchemaType);
+ variables.add(propertyDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables,
+ updatePropertyResponse.getResponse());
+ propertyDetails.getSchema().getProperty().setType("integer");
+ verifyResourcePropertyList(basicVFC, propertyDetails, "[2,3]");
+ }
+
+ @Test(dataProvider = "updatePropertiesListDefaultValueSuccessFlow")
+ public void updateResourcePropertyListSuccessFlow(String entrySchemaType, String propertyDefaltValues,
+ String expecteddefaultValues, String newEntrySchemaType, String newPropertyDefaltValues,
+ String newExpecteddefaultValues) throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.setPropertyDefaultValue(propertyDefaltValues);
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // verify properties return from response
+ assertEquals("list", resourcePropertiesFromResponse.getType());
+ assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ // Update resource property type = "list"
+ propertyDetails.setPropertyDefaultValue(newPropertyDefaltValues);
+ propertyDetails.getSchema().getProperty().setType(newEntrySchemaType);
+ ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ assertEquals("list", resourcePropertyAfterUpdate.getType());
+ assertEquals(newExpecteddefaultValues, resourcePropertyAfterUpdate.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertyAfterUpdate.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, newExpecteddefaultValues);
+ }
+
+ // Add property type list to resource
+ // DE199718
+ @Test(dataProvider = "invalidListProperties") // invalid default values
+ public void addListPropertyToResourceFailureFlow(String entrySchemaType, String propertyDefaltValues)
+ throws Exception {
+ // String propertyType = "list";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ propertyDetails.setPropertyDefaultValue(propertyDefaltValues);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(propertyDetails.getName());
+ variables.add(propertyDetails.getPropertyType());
+ variables.add(propertyDetails.getSchema().getProperty().getType());
+ variables.add(propertyDefaltValues);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables,
+ addPropertyToResourceResponse.getResponse());
+
+ }
+
+ // DE199964
+ @Test
+ public void addListPropertyToNonExistingResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType("integer");
+ propertyDetails.setPropertyDefaultValue("[1,2]");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to non existing resource
+ basicVFC.setUniqueId("1111111");
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ addPropertyToResourceResponse.getResponse());
+ }
+
+ @Test
+ public void addListPropertyToNonCheckedOutResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType("integer");
+ propertyDetails.setPropertyDefaultValue("[1,2]");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ // Add property type list to non Checked-Out resource
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ addPropertyToResourceResponse.getResponse());
+ }
+
+ @Test
+ public void addListPropertyToResourceByNonResourceOwner() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType("integer");
+ propertyDetails.setPropertyDefaultValue("[1,2]");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to non Checked-Out resource
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER2, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ addPropertyToResourceResponse.getResponse());
+ }
+
+ @Test
+ public void addListPropertyToResourcePropertyAlreadyExists01() throws Exception {
+ String propertyType = "list";
+ String propertySchemaType = "integer";
+ String defaultValues = "[1,2]";
+ String expecteddefaultValues = "[1,2]";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType(propertySchemaType);
+ propertyDetails.setPropertyDefaultValue(defaultValues);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // check-in and check-out resource
+ RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ // verify properties return from response
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyType);
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), propertySchemaType); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ // Add same property again to resource
+ RestResponse addPropertyRestResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables,
+ addPropertyRestResponse.getResponse());
+ // verify property not deleted
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ }
+
+ @Test
+ public void addListPropertyToResourcePropertyAlreadyExists02() throws Exception {
+ String propertyType = "list";
+ String propertySchemaType = "integer";
+ String defaultValues = "[1,2]";
+ String expecteddefaultValues = "[1,2]";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType(propertySchemaType);
+ propertyDetails.setPropertyDefaultValue(defaultValues);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ // verify properties return from response
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyType);
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), propertySchemaType); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ // check-in and check-out resource
+ RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ // Add same property again to resource
+ RestResponse addPropertyRestResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables,
+ addPropertyRestResponse.getResponse());
+ // verify property not deleted
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ }
+
+ @Test // DE199725
+ public void addListPropertyToResourceNonSupportedPropertyType() throws Exception { // Not
+ // "list"
+ // type
+ String propertyType = "listttttttt";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.setPropertyType(propertyType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ RestResponse addPropertyRestResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyRestResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(propertyDetails.getPropertyType()); // property data type
+ // (koko instead
+ // list)
+ variables.add(propertyDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_TYPE.name(), variables,
+ addPropertyRestResponse.getResponse());
+ }
+
+ @Test // DE199732
+ public void addListPropertyToResourceNonSupportedEntrySchemaType() throws Exception {
+ String EntrySchemaType = "stringggg"; // instead "string"
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType(EntrySchemaType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ RestResponse addPropertyRestResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyRestResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(EntrySchemaType);
+ variables.add(propertyDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_PROPERTY_INNER_TYPE.name(), variables,
+ addPropertyRestResponse.getResponse());
+ }
+
+ @Test
+ public void addHundredPropertyListToResourceSuccessFlow() throws Exception {
+ String propertyType = "list";
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ String propertyName = propertyDetails.getName();
+ int numberOfPropertiesToAddToResource = 100;
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ for (int x = 0; x < numberOfPropertiesToAddToResource; x++) {
+ propertyDetails.setName(propertyName + x);
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ // verify properties return from response
+ assertEquals(resourcePropertiesFromResponse.getName(), propertyName + x);
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyType);
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetails.getSchema().getProperty().getType()); // string/integer/boolean/float
+ }
+ // get resource and verify that 100 properties exist
+ Resource resourceObject = AtomicOperationUtils.getResourceObject(basicVFC, UserRoleEnum.DESIGNER);
+ assertEquals(numberOfPropertiesToAddToResource, resourceObject.getProperties().size());
+
+ }
+
+ @Test(dataProvider = "propertiesListDefaultValueSuccessFlow")
+ public void addListPropertyToResourceSuccessFlow(String entrySchemaType, String propertyDefaltValues,
+ String expecteddefaultValues) throws Exception {
+ String propertyType = "list";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ propertyDetails.setPropertyDefaultValue(propertyDefaltValues);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ // verify properties return from response
+ assertEquals(propertyType, resourcePropertiesFromResponse.getType());
+ assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(entrySchemaType, resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyType);
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expecteddefaultValues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(), entrySchemaType); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ }
+
+ // Delete property type list
+ @Test
+ public void deleteOneOfTheListPropertiesFromResourceAndAddItAgain() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, "[\"a\",\"b\"]");
+ // Add deleted property again to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ }
+
+ @Test
+ public void deletePropertyListTypeInteger() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[\"a\",\"b\"]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]");
+ }
+
+ @Test
+ public void deletePropertyListTypeBoolean() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.BOOLEAN_LIST);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[true,false]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one property
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]");
+ }
+
+ @Test
+ public void deletePropertyListTypeFloat() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1.0,2.0]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one property
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]");
+ }
+
+ @Test
+ public void deletePropertyListAlreadyDeleted() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1.0,2.0]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), "[1,2]");
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one property
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "[1,2]");
+ // delete again the same property
+ deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_NOT_FOUND == deletePropertyOfResource.getErrorCode());
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables,
+ deletePropertyOfResource.getResponse());
+ }
+
+ @Test
+ public void deletePropertyListResourceIsNotCheckedOutState() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST);
+ String expectedDefaultvalues = "[1.0,2.0]";
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ // Get resource and verify updated default value
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ // Check-in resource
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ // Delete property
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION == deletePropertyOfResource.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deletePropertyOfResource.getResponse());
+ // Get resource and verify property is not deleted
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ }
+
+ @Test
+ public void deletePropertyListResourceByNotIsNonResouceOwner() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST);
+ String expectedDefaultvalues = "[1.0,2.0]";
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ // Get resource and verify updated default value
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ // Delete property by non resource owner
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER2);
+ assertTrue(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION == deletePropertyOfResource.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ deletePropertyOfResource.getResponse());
+ // Get resource and verify property is not deleted
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ }
+
+ @Test
+ public void deletePropertyListFromNonExistingResource() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.FLOAT_LIST);
+ String expectedDefaultvalues = "[1.0,2.0]";
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String actualResourceUniqueId = basicVFC.getUniqueId();
+ // Add property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals(resourcePropertiesFromResponse.getDefaultValue(), expectedDefaultvalues);
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ // Get resource and verify updated default value
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ // Delete property from non existing resource
+ basicVFC.setUniqueId("1111111");
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(deletePropertyOfResource.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ deletePropertyOfResource.getResponse());
+ // Get resource and verify property is not deleted
+ basicVFC.setUniqueId(actualResourceUniqueId);
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, expectedDefaultvalues);
+ }
+
+ @Test
+ public void deletePropertyOfDerivedResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String derivedResourcePropertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ // second resource derived from basicVFC
+ Resource vfc1FromBasicVFC = AtomicOperationUtils
+ .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC,
+ ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ // Delete property (list) of derived resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(
+ vfc1FromBasicVFC.getUniqueId(), derivedResourcePropertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(deletePropertyOfResource.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables,
+ deletePropertyOfResource.getResponse());
+ // Verify resource's priority list did not changed
+ verifyResourcePropertyList(vfc1FromBasicVFC, propertyDetails, "[\"a\",\"b\"]");
+ }
+
+ @Test
+ public void deletePropertyOfNonDerivedResource() throws Exception {
+ PropertyReqDetails propertyListString = ElementFactory.getDefaultListProperty(PropertyTypeEnum.STRING_LIST);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyListString, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.changeComponentState(basicVFC, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ // second resource derived from basicVFC
+ Resource vfc1FromBasicVFC = AtomicOperationUtils
+ .createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum.VFC, basicVFC,
+ ResourceCategoryEnum.APPLICATION_L4_BORDER, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ // add property Type list to second resource
+ PropertyReqDetails propertyListInteger = ElementFactory.getDefaultListProperty(PropertyTypeEnum.INTEGER_LIST);
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyListInteger, vfc1FromBasicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // Delete property (list) of derived resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils
+ .deletePropertyOfResource(vfc1FromBasicVFC.getUniqueId(), propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyListString, "[\"a\",\"b\"]");
+ }
+
+ private void verifyResourcePropertyList(Resource resource, PropertyReqDetails expectedProperty,
+ String expecteddefaultValues) throws Exception {
+ // get resource and verify property from type list
+ Resource getResource = AtomicOperationUtils.getResourceObject(resource, UserRoleEnum.DESIGNER);
+ List<PropertyDefinition> actualResourceProperties = getResource.getProperties();
+ boolean isPropertyAppear = false;
+ for (PropertyDefinition pro : actualResourceProperties) {
+ if (expectedProperty.getName().equals(pro.getName())) {
+ assertTrue("Check Property Type ", pro.getType().equals(expectedProperty.getPropertyType()));
+ assertEquals("Check Property default values ", expecteddefaultValues, pro.getDefaultValue());
+ // assertTrue("Check Property default values ",
+ // pro.getDefaultValue().equals(expecteddefaultValues));
+ assertTrue("Check entrySchema Property Type ", pro.getSchema().getProperty().getType()
+ .equals(expectedProperty.getSchema().getProperty().getType()));
+ isPropertyAppear = true;
+ }
+ }
+ assertTrue(isPropertyAppear);
+ }
+
+ // US656905
+ // --------------------- Map Property
+ // ----------------------------------------------------------------
+ @Test(dataProvider = "updatePropertiesMapDefaultValueFailureFlow")
+ public void updateDefaultValueOfResourcePropertyMapFailureFlow(String entrySchemaType, String propertyDefaultValues,
+ String expectedDefaultValue, String newEntrySchemaType, String newPropertyDefaultValue) throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty();
+ propertyDetails.setPropertyDefaultValue(propertyDefaultValues);
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // verify properties return from response
+ assertEquals("map", resourcePropertiesFromResponse.getType());
+ assertEquals(expectedDefaultValue, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expectedDefaultValue);
+ // Update resource property type = "map"
+ propertyDetails.setPropertyDefaultValue(newPropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType(newEntrySchemaType);
+ RestResponse updatePropertyResponse = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, false)
+ .right().value();
+ assertTrue(updatePropertyResponse.getErrorCode().equals(STATUS_CODE_INVALID_CONTENT));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(propertyDetails.getName());
+ variables.add(propertyDetails.getPropertyType());
+ variables.add(propertyDetails.getSchema().getProperty().getType());
+ variables.add(newPropertyDefaultValue);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE.name(), variables,
+ updatePropertyResponse.getResponse());
+ }
+
+ @Test(dataProvider = "updatePropertiesMapDefaultValueSuccessFlow")
+ public void updateResourcePropertyMapSuccessFlow(String entrySchemaType, String propertyDefaultValues,
+ String expectedDefaultValue, String newEntrySchemaType, String newPropertyDefaultValue,
+ String newExpectedDefaultValue) throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty();
+ propertyDetails.setPropertyDefaultValue(propertyDefaultValues);
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ // verify properties return from response
+ assertEquals("map", resourcePropertiesFromResponse.getType());
+ assertEquals(expectedDefaultValue, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expectedDefaultValue);
+ // Update resource property type = "map"
+ propertyDetails.setPropertyDefaultValue(newPropertyDefaultValue);
+ propertyDetails.getSchema().getProperty().setType(newEntrySchemaType);
+ ComponentInstanceProperty resourcePropertyAfterUpdate = AtomicOperationUtils
+ .updatePropertyOfResource(propertyDetails, basicVFC, propertyUniqueId, UserRoleEnum.DESIGNER, true)
+ .left().value();
+ assertEquals("map", resourcePropertyAfterUpdate.getType());
+ assertEquals(newExpectedDefaultValue, resourcePropertyAfterUpdate.getDefaultValue());
+ assertEquals(propertyDetails.getSchema().getProperty().getType(),
+ resourcePropertyAfterUpdate.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, newExpectedDefaultValue);
+ }
+
+ @Test
+ public void deletePropertyMapTypeString() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultMapProperty(PropertyTypeEnum.STRING_MAP);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals("{\"key1\":\"val1\",\"key2\":\"val2\"}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}");
+ }
+
+ @Test
+ public void deletePropertyMapTypeFloat() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeFloat = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.FLOAT_MAP);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeFloat, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeFloat.getPropertyType());
+ assertEquals("{\"key1\":0.2123,\"key2\":43.545}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeFloat.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}");
+ }
+
+ @Test
+ public void deletePropertyMapTypeBoolean() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeBoolean = ElementFactory
+ .getDefaultMapProperty(PropertyTypeEnum.BOOLEAN_MAP);
+ PropertyReqDetails propertyDetailsInteger = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeBoolean, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeBoolean.getPropertyType());
+ assertEquals("{\"key1\":true,\"key2\":false}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeBoolean.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsInteger.getPropertyType());
+ assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsInteger.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsInteger, "{\"key1\":123,\"key2\":-456}");
+ }
+
+ @Test
+ public void deletePropertyMapTypeInteger() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeInteger = ElementFactory
+ .getDefaultMapProperty(PropertyTypeEnum.INTEGER_MAP);
+ PropertyReqDetails propertyDetailsBoolean = ElementFactory.getDefaultMapProperty(PropertyTypeEnum.BOOLEAN_MAP);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeInteger, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ String propertyUniqueId = resourcePropertiesFromResponse.getUniqueId();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeInteger.getPropertyType());
+ assertEquals("{\"key1\":123,\"key2\":-456}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeInteger.getSchema().getProperty().getType()); // string/integer/boolean/float
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsBoolean, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsBoolean.getPropertyType());
+ assertEquals("{\"key1\":true,\"key2\":false}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsBoolean.getSchema().getProperty().getType());
+ // Get resource and verify updated default value
+ RestResponse restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(2, resource.getProperties().size());
+ // Delete one resource
+ RestResponse deletePropertyOfResource = AtomicOperationUtils.deletePropertyOfResource(basicVFC.getUniqueId(),
+ propertyUniqueId, UserRoleEnum.DESIGNER);
+ assertTrue(BaseRestUtils.STATUS_CODE_DELETE == deletePropertyOfResource.getErrorCode());
+ // Get resource and verify updated default value
+ restResponse = ResourceRestUtils.getResource(basicVFC.getUniqueId());
+ resource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ assertEquals(1, resource.getProperties().size());
+ verifyResourcePropertyList(basicVFC, propertyDetailsBoolean, "{\"key1\":true,\"key2\":false}");
+ }
+
+ @Test(dataProvider = "propertiesMapDefaultValueSuccessFlow")
+ public void addMapPropertyToResourceSuccessFlow(String entrySchemaType, String propertyDefaltValues,
+ String expecteddefaultValues) throws Exception {
+ String propertyType = "map";
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultMapProperty();
+ propertyDetails.getSchema().getProperty().setType(entrySchemaType);
+ propertyDetails.setPropertyDefaultValue(propertyDefaltValues);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to resource
+ ComponentInstanceProperty resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, true).left().value();
+ // verify properties return from response
+ assertEquals(propertyType, resourcePropertiesFromResponse.getType());
+ assertEquals(expecteddefaultValues, resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(entrySchemaType, resourcePropertiesFromResponse.getSchema().getProperty().getType()); // string/integer/boolean/float
+ verifyResourcePropertyList(basicVFC, propertyDetails, expecteddefaultValues);
+ }
+
+ @Test
+ public void addMapPropertyToNonExistingResource() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType("integer");
+ propertyDetails.setPropertyDefaultValue("{\"key1\":1 , \"key2\":2}");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to non existing resource
+ basicVFC.setUniqueId("1111111");
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_NOT_FOUND));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ addPropertyToResourceResponse.getResponse());
+ }
+
+ @Test
+ public void addMaptPropertyToResourceByNonResourceOwner() throws Exception {
+ PropertyReqDetails propertyDetails = ElementFactory.getDefaultListProperty();
+ propertyDetails.getSchema().getProperty().setType("integer");
+ propertyDetails.setPropertyDefaultValue("{\"key1\":1 , \"key2\":2}");
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add property type list to non Checked-Out resource
+ RestResponse addPropertyToResourceResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetails, basicVFC, UserRoleEnum.DESIGNER2, false).right().value();
+ assertTrue(addPropertyToResourceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION));
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ addPropertyToResourceResponse.getResponse());
+ }
+
+ @Test
+ public void addMapPropertyToResourcePropertyAlreadyExists() throws Exception {
+ ComponentInstanceProperty resourcePropertiesFromResponse;
+ PropertyReqDetails propertyDetailsTypeString = ElementFactory
+ .getDefaultListProperty(PropertyTypeEnum.STRING_MAP);
+ // create resource
+ Resource basicVFC = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC,
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ // Add 2 property type list to resource
+ resourcePropertiesFromResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, true).left()
+ .value();
+ assertEquals(resourcePropertiesFromResponse.getType(), propertyDetailsTypeString.getPropertyType());
+ assertEquals("{\"key1\":\"val1\",\"key2\":\"val2\"}", resourcePropertiesFromResponse.getDefaultValue());
+ assertEquals(resourcePropertiesFromResponse.getSchema().getProperty().getType(),
+ propertyDetailsTypeString.getSchema().getProperty().getType()); // string/integer/boolean/float
+ // check-in and check-out resource
+ RestResponse changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ changeComponentState = LifecycleRestUtils.changeComponentState(basicVFC,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKOUT);
+ assertTrue(changeComponentState.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS));
+ // Add same property again to resource
+ RestResponse addPropertyRestResponse = AtomicOperationUtils
+ .addCustomPropertyToResource(propertyDetailsTypeString, basicVFC, UserRoleEnum.DESIGNER, false).right()
+ .value();
+ assertTrue(addPropertyRestResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_ALREADY_EXISTS));
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_ALREADY_EXIST.name(), variables,
+ addPropertyRestResponse.getResponse());
+ // verify property not deleted
+ verifyResourcePropertyList(basicVFC, propertyDetailsTypeString, "{\"key1\":\"val1\",\"key2\":\"val2\"}");
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java
new file mode 100644
index 0000000000..d1302c8d8c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/property/PropertyApisTest.java
@@ -0,0 +1,383 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.property;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.preRequisites.SimpleOneRsrcOneServiceTest;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class PropertyApisTest extends SimpleOneRsrcOneServiceTest {
+
+ protected static final String RESOURCE_CATEGORY = "Generic/Databases";
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";;
+
+ // protected User sdncDesignerDetails;
+ // protected ResourceReqDetails resourceDetails;
+ protected PropertyReqDetails property;
+ protected String body;
+
+ protected HttpRequest httpRequest = new HttpRequest();
+ protected Map<String, String> headersMap = new HashMap<String, String>();
+
+ @Rule
+ public static TestName testName = new TestName();
+
+ public PropertyApisTest() {
+ super(testName, PropertyApisTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+ // //Create user
+ // sdncDesignerDetails = createUser("tu1234", "Test", "User",
+ // "tu1234@intl.sdc.com", "DESIGNER");
+ //
+ // //Delete resource
+ //
+ // resourceDetails = new ResourceReqDetails();
+ // resourceDetails.setResourceName("testresourceDetails");
+ //
+ // resourceUtils.deleteResource_allVersions(resourceDetails,
+ // sdncDesignerDetails);
+ //
+ // //Create resource
+ // resourceDetails = createResource(sdncDesignerDetails,
+ // "testresourceDetails");
+
+ // Create property
+ // property.setPropertyName("test");
+ // property.setPropertyType("integer");
+ // property.setPropertySource("A&AI");
+ // property.setPropertyDescription("test property");
+
+ // body = gson.toJson(property);
+ property = ElementFactory.getDefaultProperty();
+ body = property.propertyToJsonString();
+ // System.out.println(body);
+ // HTTP (for negative tests)
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncDesignerDetails.getUserId());
+
+ }
+
+ @Test
+ public void testPropertyApis() throws Exception {
+ // Create property
+ // System.out.println ("---- Create Property (POST) ----");
+
+ String propertyId = UniqueIdBuilder.buildPropertyUniqueId(getResourceId(resourceDetails), property.getName());
+
+ PropertyRestUtils.deleteProperty(getResourceId(resourceDetails), propertyId, sdncDesignerDetails);
+ RestResponse createPropertyResponse = PropertyRestUtils.createProperty(getResourceId(resourceDetails), body,
+ sdncDesignerDetails);
+ AssertJUnit.assertTrue("Expected result code - 201, received - " + createPropertyResponse.getErrorCode(),
+ createPropertyResponse.getErrorCode() == 201);
+
+ // Get property
+ // System.out.println ("---- Get Property (GET) ----");
+ RestResponse getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId,
+ sdncDesignerDetails);
+ AssertJUnit.assertTrue("Expected result code - 200, received - " + getPropertyResponse.getErrorCode(),
+ getPropertyResponse.getErrorCode() == 200);
+
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(getPropertyResponse.getResponse());
+
+ // assertTrue("Wrong 'type' in the
+ // response",jsonResp.get("type").equals(property.getPropertyType()));
+ // assertTrue("Wrong 'source' in the
+ // response",jsonResp.get("name").equals(property.getPropertyName()));
+ // assertTrue("Wrong 'name' in the
+ // response",jsonResp.get("source").equals(property.getPropertySource()));
+ // assertTrue("Wrong 'description' in the
+ // response",jsonResp.get("description").equals(property.getPropertyDescription()));
+
+ // Update property
+ // System.out.println ("---- Update Property (UPDATE) ----");
+ property.setPropertyDescription("Updated description");
+ // body = gson.toJson(property);
+ body = property.propertyToJsonString();
+
+ RestResponse updatePropertyResponse = PropertyRestUtils.updateProperty(getResourceId(resourceDetails),
+ propertyId, body, sdncDesignerDetails);
+ AssertJUnit.assertTrue("Expected result code - 200, received - " + updatePropertyResponse.getErrorCode(),
+ updatePropertyResponse.getErrorCode() == 200);
+
+ // Get property
+ // System.out.println ("---- Get Property (GET) ----");
+ getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId,
+ sdncDesignerDetails);
+ AssertJUnit.assertTrue("Expected result code - 200, received - " + getPropertyResponse.getErrorCode(),
+ getPropertyResponse.getErrorCode() == 200);
+
+ jsonResp = (JSONObject) JSONValue.parse(getPropertyResponse.getResponse());
+
+ // assertTrue("Wrong 'type' in the
+ // response",jsonResp.get("type").equals(property.getPropertyType()));
+ // assertTrue("Wrong 'source' in the
+ // response",jsonResp.get("name").equals(property.getPropertyName()));
+ // assertTrue("Wrong 'name' in the
+ // response",jsonResp.get("source").equals(property.getPropertySource()));
+ // assertTrue("Wrong 'description' in the
+ // response",jsonResp.get("description").equals(property.getPropertyDescription()));
+
+ // Delete property
+ // System.out.println ("---- Delete Property (DELETE) ----");
+ RestResponse deletePropertyResponse = PropertyRestUtils.deleteProperty(getResourceId(resourceDetails),
+ propertyId, sdncDesignerDetails);
+ AssertJUnit.assertTrue("Expected result code - 204, received - " + deletePropertyResponse.getErrorCode(),
+ deletePropertyResponse.getErrorCode() == 204);
+
+ // Get property - verify that the property doesn't exist.
+ // System.out.println("---- GET - Property Not Found ----");
+ getPropertyResponse = PropertyRestUtils.getProperty(getResourceId(resourceDetails), propertyId,
+ sdncDesignerDetails);
+ List<String> variables = Arrays.asList("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables,
+ getPropertyResponse.getResponse());
+
+ }
+
+ // --------------------------------------------------------------------------------------
+
+ protected String getPropertyId(ResourceReqDetails resource, PropertyReqDetails property) {
+ // return
+ // resource.getResourceName().toLowerCase()+".0.1."+property.getPropertyName();
+ return UniqueIdBuilder.buildPropertyUniqueId(resource.getUniqueId(), property.getName());
+ }
+
+ protected String getResourceId(ResourceReqDetails resource) {
+ // String resourceUid =
+ // UniqueIdBuilder.buildResourceUniqueId(resource.getResourceName(),
+ // "0.1");
+
+ return resource.getUniqueId();
+ }
+
+ protected User createUser(String cspUserId, String firstName, String lastName, String email, String role)
+ throws Exception {
+ User sdncUserDetails = new User(firstName, lastName, cspUserId, email, role, null);
+
+ User adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ UserRestUtils.createUser(sdncUserDetails, adminUser);
+
+ return sdncUserDetails;
+ }
+
+ protected ResourceReqDetails createResource(User sdncUserDetails, String resourceName) throws Exception {
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ // String category = ResourceCategoryEnum.DATABASE.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.0";
+ String contactId = sdncUserDetails.getUserId();
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(),
+ ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory());
+ // deleteResource(resourceName.toLowerCase()+".0.1",sdncUserDetails.getUserId());
+ // TODO delete by name
+ // deleteResource(UniqueIdBuilder.buildResourceUniqueId(resourceName,
+ // "0.1"), sdncUserDetails.getUserId());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ AssertJUnit.assertTrue(createResource.getErrorCode().intValue() == 201);
+ String resourceId = ResponseParser.getUniqueIdFromResponse(createResource);
+ resourceDetails.setUniqueId(resourceId);
+
+ return resourceDetails;
+
+ }
+
+ @Test
+ public void putReqToCreateUriNotAllowed() throws Exception {
+ // System.out.println("---- PUT request to Create uri - Not Allowed
+ // ----");
+ String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails));
+ RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap);
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void getReqToCreateUriNotAllowed() throws Exception {
+ // System.out.println("---- GET request to Create uri - Not Allowed
+ // ----");
+ String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails));
+ RestResponse propertyErrorResponse = httpRequest.httpSendGet(url, headersMap);
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void deleteReqToCreateUriNotAllowed() throws Exception {
+ // System.out.println("---- DELETE request to Create uri - Not Allowed
+ // ----");
+ String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails));
+ RestResponse propertyErrorResponse = httpRequest.httpSendDelete(url, headersMap);
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void postReqToUpdateUriNotAllowed() throws Exception {
+ // System.out.println("---- POST request to Update uri - Not Allowed
+ // ----");
+ String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), getPropertyId(resourceDetails, property));
+ RestResponse propertyErrorResponse = httpRequest.httpSendPost(url, body, headersMap);
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void deleteReqPropertyNotFound() throws Exception {
+ // System.out.println("---- DELETE - Property Not Found ----");
+ String unknownPropertyId = getPropertyId(resourceDetails, property) + "111";
+ String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), unknownPropertyId);
+ RestResponse propertyErrorResponse = httpRequest.httpSendDelete(url, headersMap);
+ List<String> variables = Arrays.asList("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void updateReqPropertyNotFound() throws Exception {
+ // System.out.println("---- PUT - Property Not Found ----");
+ String unknownPropertyId = getPropertyId(resourceDetails, property) + "111";
+ String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), unknownPropertyId);
+ RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap);
+ List<String> variables = Arrays.asList("");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.PROPERTY_NOT_FOUND.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void modifierNotTheStateOwner() throws Exception {
+ // System.out.println("---- The modifier is not the state owner -
+ // Operation Not Allowed ----");
+ User sdncUserDetails2 = createUser("tu5555", "Test", "User", "tu5555@intl.sdc.com", "DESIGNER");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails2.getUserId());
+ property.setPropertyDescription("new description");
+ // body = gson.toJson(property);
+ body = property.propertyToJsonString();
+ String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), getPropertyId(resourceDetails, property));
+ RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap);
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ propertyErrorResponse.getResponse());
+
+ }
+
+ @Test
+ public void postReqInvalidContent() throws Exception {
+ // System.out.println("---- POST - Invalid Content ----");
+ body = "invalid";
+ String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), getPropertyId(resourceDetails, property));
+ RestResponse propertyErrorResponse = httpRequest.httpSendPost(url, body, headersMap);
+
+ // System.out.println(propertyErrorResponse.getResponse()+" "+
+ // propertyErrorResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ @Test
+ public void putReqInvalidContent() throws Exception {
+
+ // Create property
+ // System.out.println ("---- Create Property (POST) ----");
+ RestResponse createPropertyResponse = PropertyRestUtils.createProperty(getResourceId(resourceDetails), body,
+ sdncDesignerDetails);
+ assertTrue("Expected result code - 201, received - " + createPropertyResponse.getErrorCode(),
+ createPropertyResponse.getErrorCode() == 201);
+
+ // System.out.println("---- PUT - Invalid Content ----");
+ body = "invalid";
+
+ String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ getResourceId(resourceDetails), getPropertyId(resourceDetails, property));
+
+ // System.out.println(url + "\n" + body);
+
+ RestResponse propertyErrorResponse = httpRequest.httpSendByMethod(url, "PUT", body, headersMap);
+
+ // System.out.println(propertyErrorResponse.getResponse()+" "+
+ // propertyErrorResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables,
+ propertyErrorResponse.getResponse());
+ }
+
+ // --------------------------------------------------------------------------------------
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java
new file mode 100644
index 0000000000..85dfe4e13a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CheckGetResource.java
@@ -0,0 +1,52 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.common.util.SerializationUtils;
+
+import fj.data.Either;
+
+public class CheckGetResource {
+
+ public void checkGetVmmsc6() throws Exception {
+
+ try {
+
+ System.out.println("dddd");
+ RestResponse getResource = ResourceRestUtils.getResource("96eb6583-2822-448b-a284-bfc144fa627e");
+
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+
+ Either<byte[], Boolean> serialize = SerializationUtils.serializeExt(resource);
+
+ SerializationUtils.deserializeExt(serialize.left().value(), Resource.class, "ffff");
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java
new file mode 100644
index 0000000000..d05dd1039a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ComponentRelationshipInVfTest.java
@@ -0,0 +1,1408 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.http.client.ClientProtocolException;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ComponentRelationshipInVfTest extends ComponentBaseTest {
+
+ public ComponentRelationshipInVfTest() {
+ super(new TestName(), ComponentRelationshipInVfTest.class.getName());
+ }
+
+ private ResourceReqDetails resourceDetailsVF;
+ private User designerUser;
+ private User adminUser;
+ private User testerUser;
+ private ResourceReqDetails resourceDetailsReq;
+ private ResourceReqDetails resourceDetailsCap;
+
+ @BeforeMethod
+ public void before() throws Exception {
+ designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+
+ resourceDetailsVF = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VF.toString());
+ createResource(resourceDetailsVF, designerUser);
+
+ resourceDetailsReq = ElementFactory.getDefaultResourceByType("SoftCompRouter",
+ NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType
+ // =
+ // VFC
+ resourceDetailsCap = ElementFactory.getDefaultResourceByType("MyCompute", NormativeTypesEnum.COMPUTE,
+ ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType
+ // =
+ // VFC
+
+ }
+
+ private void createResource(ResourceReqDetails resourceDetails, User user) throws Exception, IOException {
+ RestResponse createResourceResponse = ResourceRestUtils.createResource(resourceDetails, user);
+ ResourceRestUtils.checkCreateResponse(createResourceResponse);
+ if (!resourceDetails.getResourceType().equals("VF"))
+ LifecycleRestUtils.changeResourceState(resourceDetails, user, "0.1", LifeCycleStatesEnum.CHECKIN);
+ }
+
+ private void createAtomicResource(ResourceReqDetails resourceDetails, User user) throws Exception {
+ createResource(resourceDetails, user);
+ }
+
+ private RequirementCapabilityRelDef setRelationshipBetweenInstances(ComponentInstance riReq,
+ ComponentInstance riCap, CapReqDef capReqDef) throws Exception {
+
+ String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.Container").get(0).getUniqueId();
+ String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.Container").get(0).getUniqueId();
+
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(riReq.getUniqueId());
+ requirementDef.setToNode(riCap.getUniqueId());
+
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(riReq.getUniqueId());
+ pair.setCapabilityOwnerId(riCap.getUniqueId());
+ pair.setRequirement("host");
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("tosca.capabilities.Container");
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capbilityUid);
+ pair.setRequirementUid(requirementUid);
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+ return requirementDef;
+ }
+
+ private ComponentInstance createComponentInstance(ResourceReqDetails res) throws Exception {
+ return createComponentInstance(res, designerUser);
+ }
+
+ private ComponentInstance createComponentInstance(ResourceReqDetails res, User user, ResourceReqDetails vf)
+ throws Exception {
+ RestResponse response = ResourceRestUtils.createResourceInstance(res, user, vf.getUniqueId());
+ ResourceRestUtils.checkCreateResponse(response);
+ ComponentInstance compInstance = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
+ return compInstance;
+ }
+
+ private ComponentInstance createComponentInstance(ResourceReqDetails res, User user) throws Exception {
+ return createComponentInstance(res, user, resourceDetailsVF);
+ }
+
+ private void createTwoAtomicResourcesByType(String reqType, String capType, User user1, User user2)
+ throws Exception {
+ resourceDetailsReq.setResourceType(reqType);
+ createAtomicResource(resourceDetailsReq, user1);
+ resourceDetailsCap.setResourceType(capType);
+ createAtomicResource(resourceDetailsCap, user2);
+ }
+
+ private void createTwoAtomicResourcesByType(String reqType, String capType) throws Exception {
+ createTwoAtomicResourcesByType(reqType, capType, designerUser, designerUser);
+ }
+
+ @Test
+ public void associateInVF() throws Exception {
+
+ createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get("tosca.capabilities.Container");
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get("tosca.capabilities.Container");
+
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(riReq.getUniqueId());
+ requirementDef.setToNode(riCap.getUniqueId());
+
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(riReq.getUniqueId());
+ pair.setCapabilityOwnerId(riCap.getUniqueId());
+ pair.setRequirement("host");
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("tosca.capabilities.Container");
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capList.get(0).getUniqueId());
+ pair.setRequirementUid(reqList.get(0).getUniqueId());
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser,
+ resourceDetailsVF);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+
+ List<RequirementDefinition> list = capReqDef.getRequirements().get("tosca.capabilities.Container");
+ assertEquals("Check requirement", null, list);
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser, resourceDetailsVF);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+
+ list = capReqDef.getRequirements().get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, list.size());
+ }
+
+ //////////////////////////////// Q A //////////////////////////////
+ private boolean checkRealtionship(String fromNode, String toNode, String resourceUniqueId) throws Exception {
+ List<RequirementCapabilityRelDef> componentInstancesRelations = getComponentInstancesRelations(
+ resourceUniqueId);
+ RequirementCapabilityRelDef requirementCapabilityRelDef = componentInstancesRelations.get(0);
+ boolean fromNodeCheck = requirementCapabilityRelDef.getFromNode().equals(fromNode);
+ boolean toNodeCheck = requirementCapabilityRelDef.getToNode().equals(toNode);
+
+ return fromNodeCheck && toNodeCheck;
+ }
+
+ private List<RequirementCapabilityRelDef> getComponentInstancesRelations(String resourceUniqueId)
+ throws ClientProtocolException, IOException {
+ Resource resource = getVfAsResourceObject(resourceUniqueId);
+ List<RequirementCapabilityRelDef> componenRelationInstances = resource.getComponentInstancesRelations();
+
+ return componenRelationInstances;
+ }
+
+ private Resource getVfAsResourceObject(String resourceUniqueId) throws ClientProtocolException, IOException {
+ RestResponse getResource = ResourceRestUtils.getResource(resourceUniqueId);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ return resource;
+ }
+
+ private List<ComponentInstance> getComponentInstancesList(String resourceUniqueId) throws Exception {
+ Resource resource = getVfAsResourceObject(resourceUniqueId);
+ List<ComponentInstance> componentInstances = resource.getComponentInstances();
+ return componentInstances;
+ }
+
+ @Test
+ public void associateCpToCpTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ requirementsBeforeAssociate.remove("tosca.capabilities.Container");
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+
+ List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
+ for (CapabilityDefinition cap : list) {
+ cap.setMinOccurrences("0");
+ }
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ }
+
+ private CapReqDef getResourceReqCap(ResourceReqDetails res) throws IOException {
+ RestResponse getResourceBeforeAssociate = ComponentRestUtils.getComponentRequirmentsCapabilities(designerUser,
+ resourceDetailsVF);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class);
+ return capReqDef;
+ }
+
+ private CapReqDef getResourceReqCap() throws IOException {
+ return getResourceReqCap(resourceDetailsVF);
+ }
+
+ @Test
+ public void associateCpToVLTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ requirementsBeforeAssociate.remove("tosca.capabilities.Container");
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+
+ List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
+ for (CapabilityDefinition cap : list) {
+ cap.setMinOccurrences("0");
+ }
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+
+ }
+
+ // Error handling
+ // ELLA - more informative error
+ @Test
+ public void associateCpToVlInVFCTest() throws Exception {
+ ResourceReqDetails vfcDetails = ElementFactory.getDefaultResourceByType("VFC100", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VFC.toString());
+ RestResponse createVfcResponse = ResourceRestUtils.createResource(vfcDetails, designerUser);
+ ResourceRestUtils.checkCreateResponse(createVfcResponse);
+
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ vfcDetails.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue());
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "SoftCompRouter 1",
+ // "MyCompute 2",
+ // "host"
+ // ]
+ }
+
+ // Error handling
+ @Test
+ public void associateCpToVfTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riCapInVfInstance = createComponentInstance(resourceDetailsCap, designerUser,
+ resourceDetailsVF);
+ ComponentInstance riReqInVfInstance = createComponentInstance(resourceDetailsReq, designerUser,
+ resourceDetailsVF);
+
+ ResourceReqDetails vfHigh = new ResourceReqDetails(resourceDetailsVF, "0.1");
+ vfHigh.setName("vfHigh");
+ vfHigh.setTags(new ArrayList<String>(Arrays.asList(vfHigh.getName())));
+ vfHigh.setResourceType(ResourceTypeEnum.VF.toString());
+ createResource(vfHigh, designerUser);
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq, designerUser, vfHigh);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVF, designerUser, "0.1", LifeCycleStatesEnum.CHECKIN);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsVF, designerUser, vfHigh);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ associateInstances.getResponse());
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "SoftCompRouter 1",
+ // "VF100 2",
+ // "host"
+ // ]
+ }
+
+ // Error handling
+ @Test
+ public void associateVfcToVfcNotFoundTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+ riCap.setUniqueId("123");
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_BAD_REQUEST.name(),
+ new ArrayList<String>(), associateInstances.getResponse());
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "SoftCompRouter 1",
+ // "012f6dcd-bcdf-4d9b-87be-ff1442b95831.5d265453-0b6a-4453-8f3d-57a253b88432.softcomprouter1",
+ // "host"
+ }
+
+ @Test
+ public void associateCpToDeletedVfcTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(),
+ designerUser.getUserId());
+ ResourceRestUtils.checkDeleteResponse(deleteResourceResponse);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ }
+
+ @Test
+ public void associateCpToDeletedVlTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(),
+ designerUser.getUserId());
+ ResourceRestUtils.checkDeleteResponse(deleteResourceResponse);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ }
+
+ @Test
+ public void associateCpToDeletedCpTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(),
+ designerUser.getUserId());
+ ResourceRestUtils.checkDeleteResponse(deleteResourceResponse);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ }
+
+ // Error handling
+ @Test
+ public void associateCpToDeletedCpInstanceTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse deleteComponentInstance = ComponentInstanceRestUtils.deleteComponentInstance(designerUser,
+ resourceDetailsVF.getUniqueId(), riReq.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ComponentInstanceRestUtils.checkDeleteResponse(deleteComponentInstance);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue());
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "7d6aca08-9321-4ea1-a781-c52c8214a30e.c0e63466-5283-44d8-adff-365c0885a6ba.softcomprouter1",
+ // "MyCompute 2",
+ // "host"
+ // ]
+ }
+
+ // Error handling
+ @Test
+ public void associateVfcToDeletedVFCInstanceTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.VFC.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse deleteComponentInstance = ComponentInstanceRestUtils.deleteComponentInstance(designerUser,
+ resourceDetailsVF.getUniqueId(), riReq.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ComponentInstanceRestUtils.checkDeleteResponse(deleteComponentInstance);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue());
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "7d6aca08-9321-4ea1-a781-c52c8214a30e.c0e63466-5283-44d8-adff-365c0885a6ba.softcomprouter1",
+ // "MyCompute 2",
+ // "host"
+ // ]
+ }
+
+ @Test
+ public void associateWithDifferentOwnerOfVf() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), resourceDetailsVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ associateInstances.getResponse());
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterAssociate = capReqDef.getRequirements();
+
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate));
+ }
+
+ @Test
+ public void associateWithTester() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), resourceDetailsVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ associateInstances.getResponse());
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterAssociate = capReqDef.getRequirements();
+
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate));
+ }
+
+ // Error handling
+ @Test
+ public void associateCpToVLIntoVFNotFound() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ String uidNotFound = "123";
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ uidNotFound, ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList("")), associateInstances.getResponse());
+
+ // {"serviceException":{"messageId":"SVC4063","text":"Error: Requested
+ // '%1' resource was not found.","variables":[""]}}}
+ }
+
+ // Error Handling
+ @Test
+ public void associateCpToVlWithMissingUid() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ requirementDef.setToNode("");
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 400, associateInstances.getErrorCode().intValue());
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(),
+ // new ArrayList<String>(), associateInstances.getResponse());
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "SoftCompRouter 1",
+ // "fd3a689b-fa1c-4105-933d-d1310e642f05.95bce626-ce73-413b-8c14-2388d1589d5c.softcomprouter1",
+ // "host"
+ // ]
+ }
+
+ @Test
+ public void associateInServiceWithUidOfVf() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList("")), associateInstances.getResponse());
+ }
+
+ @Test
+ public void associateCpToVl_DifferentOwners() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString(), designerUser,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2));
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ requirementsBeforeAssociate.remove("tosca.capabilities.Container");
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+
+ List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
+ for (CapabilityDefinition cap : list) {
+ cap.setMinOccurrences("0");
+ }
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test(enabled = false)
+ public void associateToNotCheckedoutVf() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse changeResourceStateToCheckin = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ associateInstances.getResponse());
+
+ CapReqDef capReqDef = getResourceReqCap();
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDef.getCapabilities().equals(capabilitiesBeforeAssociate));
+
+ String firstUniqueId = resourceDetailsVF.getUniqueId();
+
+ // checkout
+
+ RestResponse changeResourceStateToCheckout = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout);
+ String secondUniqueId = resourceDetailsVF.getUniqueId();
+
+ CapReqDef capReqDefAfterFirstCheckout = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterFirstCheckout = capReqDefAfterFirstCheckout
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterFirstCheckout = capReqDefAfterFirstCheckout
+ .getRequirements();
+
+ requirementDef = setUidsOfInstancesAfterLifecycleStateChange(riReq, riCap, capReqDefBeforeAssociate);
+
+ RestResponse firstAssociateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, firstAssociateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDefAfterFirstAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterFirstAssociate = capReqDefAfterFirstAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterFirstAssociate = capReqDefAfterFirstAssociate
+ .getRequirements();
+
+ requirementsAfterFirstCheckout.remove("tosca.capabilities.Container");
+ assertTrue(requirementsAfterFirstAssociate.equals(requirementsAfterFirstCheckout));
+ assertTrue(capabilitiesAfterFirstAssociate.equals(capabilitiesAfterFirstCheckout));
+
+ resourceDetailsVF.setUniqueId(firstUniqueId);
+ CapReqDef capReqDefOfFirstVersion = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesOfFirstVersion = capReqDefOfFirstVersion.getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsOfFirstVersion = capReqDefOfFirstVersion.getRequirements();
+
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+ assertTrue(requirementsBeforeAssociate.equals(requirementsOfFirstVersion));
+ assertTrue(capabilitiesBeforeAssociate.equals(capabilitiesOfFirstVersion));
+
+ // checkin-checkout
+ resourceDetailsVF.setUniqueId(secondUniqueId);
+ RestResponse changeResourceStateToCheckin2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin2);
+ RestResponse changeResourceStateToCheckout2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout2);
+
+ List<RequirementCapabilityRelDef> componentInstancesRelations = getComponentInstancesRelations(
+ resourceDetailsVF.getUniqueId());
+ assertFalse(componentInstancesRelations.isEmpty());
+ assertEquals(1, componentInstancesRelations.size());
+ List<ComponentInstance> componentInstancesList = getComponentInstancesList(resourceDetailsVF.getUniqueId());
+ for (ComponentInstance comp : componentInstancesList) {
+ String instanceUid = comp.getUniqueId();
+ assertTrue(checkNodesInRelations(instanceUid, componentInstancesRelations.get(0)));
+ }
+ assertEquals(2, componentInstancesList.size());
+
+ }
+
+ private RequirementCapabilityRelDef setUidsOfInstancesAfterLifecycleStateChange(ComponentInstance riReq,
+ ComponentInstance riCap, CapReqDef capReqDefBeforeAssociate)
+ throws ClientProtocolException, IOException, Exception {
+ RequirementCapabilityRelDef requirementDef;
+ // RestResponse getResourceResponse =
+ // ResourceRestUtils.getResource(resourceDetailsVF.getUniqueId());
+ // Resource resource_0_2 =
+ // ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(),
+ // Resource.class);
+ // List<ComponentInstance> componentInstances =
+ // resource_0_2.getComponentInstances();
+ List<ComponentInstance> componentInstances = getComponentInstancesList(resourceDetailsVF.getUniqueId());
+
+ for (ComponentInstance comp : componentInstances) {
+ if (comp.getName().equals(riReq.getName())) {
+ riReq.setUniqueId(comp.getUniqueId());
+ } else if (comp.getName().equals(riCap.getName())) {
+ riCap.setUniqueId(comp.getUniqueId());
+ }
+ }
+ requirementDef = setRelationshipBetweenInstances(riReq, riCap, capReqDefBeforeAssociate);
+ return requirementDef;
+ }
+
+ private boolean checkNodesInRelations(String instanceUid, RequirementCapabilityRelDef relation) {
+ if (relation.getToNode().equals(instanceUid)) {
+ return true;
+ } else if (relation.getFromNode().equals(instanceUid)) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ @Test
+ public void associateOneOfTwoCPsToVl_ThenDiscocciate() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+ ResourceReqDetails secondResourceDetailsReq = new ResourceReqDetails(resourceDetailsReq, "0.1");
+ secondResourceDetailsReq.setName("secondCP");
+ secondResourceDetailsReq.setTags(Arrays.asList(secondResourceDetailsReq.getName()));
+ createAtomicResource(secondResourceDetailsReq, designerUser);
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riReq2 = createComponentInstance(secondResourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ List<RequirementDefinition> expectedList = requirementsBeforeAssociate.get("tosca.capabilities.Container");
+ for (RequirementDefinition req : expectedList) {
+ if (req.getOwnerName().equals(riReq2.getName())) {
+ expectedList = new ArrayList<RequirementDefinition>(Arrays.asList(req));
+ break;
+ }
+ }
+ requirementsBeforeAssociate.put("tosca.capabilities.Container", expectedList);
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+
+ List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
+ for (CapabilityDefinition cap : list) {
+ cap.setMinOccurrences("0");
+ }
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+
+ // second relationship
+
+ RequirementCapabilityRelDef secondRequirementDef = setRelationshipBetweenInstances(riReq2, riCap,
+ capReqDefBeforeAssociate);
+ RestResponse secondAssociateInstances = ComponentInstanceRestUtils.associateInstances(secondRequirementDef,
+ designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, secondAssociateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(secondRequirementDef.getFromNode(), secondRequirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ CapReqDef capReqDefAfterSecondAssociation = getResourceReqCap();
+
+ requirementsBeforeAssociate.remove("tosca.capabilities.Container");
+ assertTrue(capReqDefAfterSecondAssociation.getRequirements().equals(requirementsBeforeAssociate));
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterSecondAssociate = capReqDefAfterSecondAssociation
+ .getCapabilities();
+ assertTrue(capabilitiesAfterSecondAssociate.equals(capabilitiesBeforeAssociate));
+
+ // dissociate
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(secondRequirementDef,
+ designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ CapReqDef capReqDefAfterDissociation = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterDissociate = capReqDefAfterDissociation
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterDissociate = capReqDefAfterDissociation
+ .getRequirements();
+
+ assertTrue(capabilitiesAfterDissociate.equals(capReqDef.getCapabilities()));
+ requirementsBeforeAssociate.put("tosca.capabilities.Container", expectedList);
+ assertTrue(requirementsAfterDissociate.equals(requirementsBeforeAssociate));
+ }
+
+ @Test
+ public void associateNotCompitableCapAndReq() throws Exception {
+ resourceDetailsReq = ElementFactory.getDefaultResourceByType("Database", NormativeTypesEnum.DATABASE,
+ ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, designerUser.getUserId(), ResourceTypeEnum.CP.toString()); // resourceType
+ // =
+ // VFC
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ assertTrue(requirementDef.getRelationships().size() == 1);
+ String requirement = requirementDef.getRelationships().get(0).getRequirement();
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 404, associateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList(riReq.getName(), riCap.getName(), requirement)),
+ associateInstances.getResponse());
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsAfterAssociate = capReqDef.getRequirements();
+
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ assertTrue(requirementsAfterAssociate.equals(requirementsBeforeAssociate));
+
+ }
+
+ @Test
+ public void disassociateCpAndCpTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.CP.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test
+ public void disassociateCpAndVfcTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test
+ public void disassociateCpAndVLTest() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ // Error handliing
+ // in the error should we get the unique id of instances instead of names
+ @Test
+ public void disassociateNotFoundAssociation() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+ String requirementName = requirementDef.getRelationships().get(0).getRequirement();
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList(riReq.getName(), riCap.getName(), requirementName)),
+ dissociateInstances.getResponse());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ // Error handliing
+ @Test
+ public void disassociateRelationInVfNotFound() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ String uidNotFound = "123";
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ uidNotFound, ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList(uidNotFound)), dissociateInstances.getResponse());
+
+ // "serviceException": {
+ // "messageId": "SVC4063",
+ // "text": "Error: Requested \u0027%1\u0027 resource was not found.",
+ // "variables": [
+ // ""
+ // ]
+ }
+
+ @Test
+ public void disassociateWithDifferentDesigner() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), resourceDetailsVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ dissociateInstances.getResponse());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+
+ }
+
+ @Test
+ public void disassociateWithTester() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), resourceDetailsVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ dissociateInstances.getResponse());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertNotNull("Requierment is null after disassociate with tester", listOfRequierments);
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test
+ public void disassociateServiceWithUidOfVF() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VFC.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(),
+ new ArrayList<String>(Arrays.asList("")), dissociateInstances.getResponse());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertTrue(listOfRequierments == null);
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).size() != 0);
+ }
+
+ @Test
+ public void disassociateWithEmptyVfUid() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ "", ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 404, dissociateInstances.getErrorCode().intValue());
+
+ CapReqDef capReqDef = getResourceReqCap();
+
+ requirementsBeforeAssociate.remove("tosca.capabilities.Container");
+ assertTrue(capReqDef.getRequirements().equals(requirementsBeforeAssociate));
+
+ List<CapabilityDefinition> list = capabilitiesBeforeAssociate.get("tosca.capabilities.Container");
+ for (CapabilityDefinition cap : list) {
+ cap.setMinOccurrences("0");
+ }
+
+ Map<String, List<CapabilityDefinition>> capabilitiesAfterAssociate = capReqDef.getCapabilities();
+ assertTrue(capabilitiesAfterAssociate.equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test
+ public void disassociateOneComponentDeleted() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+
+ RestResponse deleteResourceResponse = ResourceRestUtils.deleteResource(resourceDetailsCap.getUniqueId(),
+ designerUser.getUserId());
+ ResourceRestUtils.checkDeleteResponse(deleteResourceResponse);
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+
+ List<RequirementDefinition> listOfRequierments = capReqDefAfterDissociate.getRequirements()
+ .get("tosca.capabilities.Container");
+ assertEquals("Check requirement", 1, listOfRequierments.size());
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+ }
+
+ @Test
+ public void disassociateNotCheckedoutVf() throws Exception {
+ createTwoAtomicResourcesByType(ResourceTypeEnum.CP.toString(), ResourceTypeEnum.VL.toString());
+
+ ComponentInstance riReq = createComponentInstance(resourceDetailsReq);
+ ComponentInstance riCap = createComponentInstance(resourceDetailsCap);
+
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap();
+ Map<String, List<CapabilityDefinition>> capabilitiesBeforeAssociate = capReqDefBeforeAssociate
+ .getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementsBeforeAssociate = capReqDefBeforeAssociate
+ .getRequirements();
+
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(riReq, riCap,
+ capReqDefBeforeAssociate);
+
+ RestResponse changeResourceStateToCheckin = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckin);
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", 409, dissociateInstances.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ dissociateInstances.getResponse());
+
+ CapReqDef capReqDefAfterDissociate = getResourceReqCap();
+ assertTrue(capReqDefAfterDissociate.getRequirements().equals(requirementsBeforeAssociate));
+ assertTrue(capReqDefAfterDissociate.getCapabilities().equals(capabilitiesBeforeAssociate));
+
+ RestResponse changeResourceStateToCheckout = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout);
+
+ requirementDef = setUidsOfInstancesAfterLifecycleStateChange(riReq, riCap, capReqDefBeforeAssociate);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, designerUser,
+ resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF.getUniqueId()));
+
+ RestResponse secondDisociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ designerUser, resourceDetailsVF.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, secondDisociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ RestResponse changeResourceStateToCheckout2 = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout2);
+ RestResponse changeResourceStateToCheckout3 = LifecycleRestUtils.changeResourceState(resourceDetailsVF,
+ designerUser, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.checkSuccess(changeResourceStateToCheckout3);
+
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF.getUniqueId()).isEmpty());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java
new file mode 100644
index 0000000000..a9ed54ef15
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/CreateResourceApiTest.java
@@ -0,0 +1,2199 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+/**
+ * @author yshlosberg
+ *
+ */
+public class CreateResourceApiTest extends ComponentBaseTest {
+
+ private static Logger log = LoggerFactory.getLogger(CreateResourceApiTest.class.getName());
+
+ String contentTypeHeaderData = "application/json";
+ String acceptHeaderDate = "application/json";
+ String resourceVersion = "0.1";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CreateResourceApiTest() {
+ super(name, CreateResourceApiTest.class.getName());
+ }
+
+ @Test
+ public void createResourceTest() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // ResourceReqDetails resourceDetails = new
+ // ResourceReqDetails(resourceName, description, resourceTags, category,
+ // derivedFrom, vendorName, vendorRelease, contactId, icon);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ String resourceName = resourceDetails.getName();
+ resourceDetails.setTags(Arrays.asList(resourceName, resourceName, resourceName, resourceName, "tag2", "tag2"));
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void createResourceNonDefaultResourceTypeTest() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ String resourceType = ResourceTypeEnum.CP.toString();
+ resourceDetails.setResourceType(resourceType);
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ resourceRespJavaObject.setResourceType(resourceType);
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void createResourceTest_costAndLicenseType() throws Exception {
+
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+
+ }
+
+ // ////Benny
+ @Test
+ public void createResourceTest_CostIsMissing() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ // resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ }
+
+ @Test
+ public void createResourceTest_LicenseTypeMissing() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ // resourceDetails.setLicenseType("User");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ }
+
+ @Test
+ public void createResourceTest_LicenseType_Installation() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("99999.999");
+ resourceDetails.setLicenseType("Installation");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ }
+
+ @Test
+ public void createResourceTest_LicenseType_CPU() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("0.0");
+ resourceDetails.setLicenseType("CPU");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ // validate response
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails,
+ resourceDetails.getUniqueId());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ }
+
+ @Test
+ public void createResourceTest_LicenseType_Uppercase() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("0.0");
+ resourceDetails.setLicenseType("INSTALLATION");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage());
+ }
+
+ @Test
+ public void createResourceTest_LicenseType_Invalid() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("0.0");
+ resourceDetails.setLicenseType("CPUUU");
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage());
+ }
+
+ @Test
+ public void createResourceTest_CostValidation_noNumeric() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+ resourceDetails.setCost("12355.34b");
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ }
+
+ @Test
+ public void createResourceTest_CostValidation_valueLength() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+
+ // Adding invalid cost
+ resourceDetails.setCost("12355.3434");
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+ }
+
+ @Test
+ public void createResourceTest_CostValidation_PriceLimitations() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+
+ // Adding invalid cost
+ RestResponse createResponse;
+ // create resource
+
+ resourceDetails.setCost("000000.000");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ /*
+ * resourceDetails.setCost("0550.457"); createResponse =
+ * resourceUtils.createResource(resourceDetails, sdncModifierDetails);
+ * assertNotNull("check response object is not null after create resource"
+ * , createResponse);
+ * assertNotNull("check error code exists in response after create resource"
+ * , createResponse.getErrorCode());
+ * assertEquals("Check response code after create resource", 400,
+ * createResponse.getErrorCode().intValue());
+ * assertEquals("Check response code after create resource",
+ * "Bad Request", createResponse.getResponseMessage().toString());
+ */
+
+ resourceDetails.setCost("1");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ resourceDetails.setCost("123555.340");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ resourceDetails.setCost("123.4570");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ resourceDetails.setCost("123555.30");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ resourceDetails.setCost("123.5550");
+ createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request",
+ createResponse.getResponseMessage().toString());
+
+ }
+
+ @Test
+ public void createResourceTest_CostIsNull() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+ resourceDetails.setCost("");
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage());
+
+ }
+
+ @Test
+ public void createResourceTest_LicenseIsNull() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // set resource details
+ String resourceName = "CISCO4572";
+ String description = "description";
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add(resourceName);
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ // Adding cost and licenseType
+ resourceDetails.setCost("12355.345");
+ resourceDetails.setLicenseType("User");
+ resourceDetails.setLicenseType("");
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 400, createResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create resource", "Bad Request", createResponse.getResponseMessage());
+
+ }
+
+ @Test
+ public void createResourceTest_uri_methods() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ ResourceReqDetails resourceDetails = createRandomResource();
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ log.debug(userBodyJson);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ RestResponse createResourceResponse2 = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name());
+
+ assertNotNull("check response object is not null after create resource", createResourceResponse2);
+ assertNotNull("check error code exists in response after create resource",
+ createResourceResponse2.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(),
+ createResourceResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ createResourceResponse2.getResponse());
+
+ }
+
+ private ResourceReqDetails createRandomResource() {
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ return resourceDetails;
+ }
+
+ @Test
+ public void createResource_role_tester() throws Exception {
+
+ // init TESTER user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+
+ ResourceReqDetails resourceDetails2 = createRandomResource();
+
+ // create resource
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.TESTER.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.TESTER.getUserName());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ // TODO DE171450(to check)
+ @Test
+ public void createResource_role_DESIGNER() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ResourceReqDetails resourceDetails = createRandomResource();
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ // validate response
+ assertNotNull("check response object is not null after create resource", restResponse);
+ assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode());
+ assertEquals(
+ "Check response code after create resource, response message is: " + restResponse.getResponseMessage(),
+ 201, restResponse.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResource_missing_header() throws Exception {
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ ResourceReqDetails resourceDetails = createRandomResource();
+
+ // set null in userId header
+ sdncModifierDetails.setUserId(null);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_INFORMATION.name(), variables,
+ restResponse2.getResponse());
+
+ // //validate audit
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // resourceUtils.constructFieldsForAuditValidation(resourceDetails,resourceVersion);
+ //
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setModifierUid("null null");
+ // expectedResourceAuditJavaObject.setModifierName("null null");
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setCurrState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrVersion("");
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ //
+ // String auditDesc =
+ // AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ // expectedResourceAuditJavaObject.setDesc(auditDesc);
+ //
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction);
+ // TODO: yshlosberg enable back
+
+ }
+
+ @Test
+ public void createResource_existing_resource() throws Exception {
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // ResourceReqDetails resourceDetails = createRandomResource();
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", restResponse);
+ assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+
+ // set resource details
+ ResourceReqDetails resourceDetails2 = ElementFactory.getDefaultResource();
+
+ // clean ES DB
+ DbUtils.cleanAllAudits();
+
+ // create resource
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", resourceDetails2.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_category() throws Exception {
+
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ ;
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ category = null;
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_empty_category() throws Exception {
+
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ category = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_tags() throws Exception {
+
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ ;
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_TAGS.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_TAGS.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ // TODO DE171450(to check)
+ @Test
+ public void createResourceTest_with_multiple_tags() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setTags(Arrays.asList(resourceDetails.getName(), "tag2"));
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", restResponse);
+ assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createResourceTest_empty_tag() throws Exception {
+
+ // init ADMIN user
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse);
+ assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), restResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", "tag");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_with_empty_vendorName() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ vendorName = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_NAME.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_vendorName() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ vendorName = null;
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+ assertNotNull("check response object is not null after create resource", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create resource", 400, restResponse2.getErrorCode().intValue());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), variables,
+ restResponse2.getResponse());
+
+ }
+
+ @Test
+ public void createResourceTest_with_empty_vendorRelease() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ vendorRelease = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_RELEASE.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_vendorRelease() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ vendorRelease = null;
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_VENDOR_RELEASE.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_with_empty_contactId() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ contactId = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_contactId() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ contactId = null;
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CONTACT.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_with_empty_icon() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ icon = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_icon() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ icon = null;
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_ICON.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_with_empty_description() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ description = "";
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createResourceTest_without_description() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // set resource details
+ String resourceName = "CISCO4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ // set resource details
+ description = null;
+
+ ResourceReqDetails resourceDetails2 = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ // create resource
+
+ RestResponse restResponse2 = ResourceRestUtils.createResource(resourceDetails2, sdncModifierDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name());
+
+ assertNotNull("check response object is not null after create resouce", restResponse2);
+ assertNotNull("check error code exists in response after create resource", restResponse2.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse2.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables,
+ restResponse2.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails2, resourceVersion);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createAndGetResourceByNameAndVersion() throws Exception {
+
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ ResourceReqDetails resourceDetailsComp = ElementFactory.getDefaultResource("testresourceComp",
+ NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, sdncModifierDetails.getUserId());
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetailsComp, sdncModifierDetails);
+ // validate response
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ String resourceVersion = "0.1";
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetailsComp,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResourceByNameAndVersion(
+ sdncModifierDetails.getUserId(), resourceDetailsComp.getName(), resourceDetailsComp.getVersion());
+ assertEquals("Check response code after delete resource", 200, resourceGetResponse.getErrorCode().intValue());
+ // Resource resource =
+ // ResourceRestUtils.parseResourceFromListResp(resourceGetResponse);
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ // resourceDetailsComp.setUniqueId(resource.getUniqueId());
+
+ }
+
+ @Test
+ public void createResourceResourceTypeNotExistsTest() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ String resourceType = "NOT EXISTS";
+ resourceDetails.setResourceType(resourceType);
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+
+ assertNotNull("check response object is not null after create resouce", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), createResponse.getErrorCode());
+
+ List<String> variables = new ArrayList<>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables,
+ createResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor
+ .constructFieldsForAuditValidation(resourceDetails, resourceVersion);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @Test
+ public void createResourceResourceTypeEmptyTest() throws Exception {
+
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ // String resourceType = "";
+ // resourceDetails.setResourceType(resourceType);
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // ErrorInfo errorInfo =
+ // ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+ //
+ // assertNotNull("check response object is not null after create
+ // resouce", createResponse);
+ // assertNotNull("check error code exists in response after create
+ // resource", createResponse.getErrorCode());
+ // assertEquals("Check response code after create service",
+ // errorInfo.getCode(), createResponse.getErrorCode());
+ //
+ // List<String> variables = new ArrayList<>();
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(),
+ // variables, createResponse.getResponse());
+ //
+ // // validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // Convertor.constructFieldsForAuditValidation(resourceDetails,
+ // resourceVersion);
+ // String auditAction = "Create";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState("");
+ // expectedResourceAuditJavaObject.setCurrVersion("");
+ // expectedResourceAuditJavaObject.setResourceName("");
+ // expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId());
+ // expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getFullName());
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ //
+ // String auditDesc =
+ // AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ // expectedResourceAuditJavaObject.setDesc(auditDesc);
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ }
+
+ @Test
+ public void checkInvariantUuidIsImmutable() throws Exception {
+ // choose the user to create resource
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!";
+ resourceDetails.setInvariantUUID(invariantUuidDefinedByUser);
+ String resourceName = resourceDetails.getName();
+ resourceDetails.setTags(Arrays.asList(resourceName, resourceName, resourceName, resourceName, "tag2", "tag2"));
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ BaseRestUtils.checkStatusCode(createResponse, "create request failed", false, 201);
+ // validate response
+ assertNotNull("check response object is not null after create resource", createResponse);
+ assertNotNull("check error code exists in response after create resource", createResponse.getErrorCode());
+ assertEquals("Check response code after create resource", 201, createResponse.getErrorCode().intValue());
+
+ Resource resourceCreation = ResponseParser.convertResourceResponseToJavaObject(createResponse.getResponse());
+ String invariantUUIDcreation = resourceCreation.getInvariantUUID();
+ // validate response
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ ResourceValidationUtils.validateResp(createResponse, resourceRespJavaObject);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncUserDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(resourceGetResponse);
+ Resource resourceGetting = ResponseParser
+ .convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+ String invariantUUIDgetting = resourceGetting.getInvariantUUID();
+ assertEquals(invariantUUIDcreation, invariantUUIDgetting);
+
+ // Update resource with new invariant UUID
+ RestResponse restResponseUpdate = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncUserDetails,
+ resourceDetails.getUniqueId());
+ BaseRestUtils.checkSuccess(restResponseUpdate);
+ Resource updatedResource = ResponseParser.convertResourceResponseToJavaObject(restResponseUpdate.getResponse());
+ String invariantUUIDupdating = updatedResource.getInvariantUUID();
+ assertEquals(invariantUUIDcreation, invariantUUIDupdating);
+
+ // Do checkin
+ RestResponse restResponseCheckin = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ BaseRestUtils.checkSuccess(restResponseCheckin);
+ Resource checkinResource = ResponseParser
+ .convertResourceResponseToJavaObject(restResponseCheckin.getResponse());
+ String invariantUUIDcheckin = checkinResource.getInvariantUUID();
+ String version = checkinResource.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckin);
+ assertEquals(version, "0.1");
+
+ // Do checkout
+ RestResponse restResponseCheckout = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ BaseRestUtils.checkSuccess(restResponseCheckout);
+ Resource ResourceResource = ResponseParser
+ .convertResourceResponseToJavaObject(restResponseCheckout.getResponse());
+ String invariantUUIDcheckout = ResourceResource.getInvariantUUID();
+ version = ResourceResource.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckout);
+ assertEquals(version, "0.2");
+
+ // do certification request
+ RestResponse restResponseCertificationRequest = LifecycleRestUtils.changeResourceState(resourceDetails,
+ sdncUserDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ BaseRestUtils.checkSuccess(restResponseCertificationRequest);
+ Resource certificationRequestResource = ResponseParser
+ .convertResourceResponseToJavaObject(restResponseCertificationRequest.getResponse());
+ String invariantUUIDcertificationRequest = certificationRequestResource.getInvariantUUID();
+ version = certificationRequestResource.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcertificationRequest);
+ assertEquals(version, "0.2");
+
+ // start certification
+ RestResponse restResponseStartCertification = LifecycleRestUtils.changeResourceState(resourceDetails,
+ sdncUserDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ BaseRestUtils.checkSuccess(restResponseStartCertification);
+ Resource startCertificationRequestResource = ResponseParser
+ .convertResourceResponseToJavaObject(restResponseStartCertification.getResponse());
+ String invariantUUIDStartCertification = startCertificationRequestResource.getInvariantUUID();
+ version = startCertificationRequestResource.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDStartCertification);
+ assertEquals(version, "0.2");
+
+ // certify
+ RestResponse restResponseCertify = LifecycleRestUtils.changeResourceState(resourceDetails, sdncUserDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ BaseRestUtils.checkSuccess(restResponseCertify);
+ Resource certifyResource = ResponseParser
+ .convertResourceResponseToJavaObject(restResponseCertify.getResponse());
+ String invariantUUIDcertify = certifyResource.getInvariantUUID();
+ version = certifyResource.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcertify);
+ assertEquals(version, "1.0");
+
+ }
+
+ // US672129 BENNY
+
+ private void getResourceValidateInvariantUuid(String resourceUniqueId, String invariantUUIDcreation)
+ throws Exception {
+ RestResponse getResource = ResourceRestUtils.getResource(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER),
+ resourceUniqueId);
+ BaseRestUtils.checkSuccess(getResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ assertEquals(invariantUUIDcreation, resource.getInvariantUUID());
+ }
+
+ @Test
+ public void resourceInvariantUuid() throws Exception {
+
+ User designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ User testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResourceByType("VF200", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, designerUser.getUserId(), ResourceTypeEnum.VF.toString());
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService("newtestservice1",
+ ServiceCategoriesEnum.MOBILITY, designerUser.getUserId());
+
+ // ResourceReqDetails resourceDetails =
+ // ElementFactory.getDefaultResource();
+ resourceDetails.setInvariantUUID("kokomoko");
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, designerUser);
+ assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED,
+ createResponse.getErrorCode().intValue());
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResponse.getResponse(), Resource.class);
+ String invariantUUIDcreation = resource.getInvariantUUID(); // generated
+ // when the
+ // component
+ // is
+ // created
+ // and never
+ // changed
+ // get resource and verify InvariantUuid is not changed
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+
+ // Update resource with new invariant UUID
+ resourceDetails.setInvariantUUID("1234567890");
+ RestResponse updateResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, designerUser,
+ resourceDetails.getUniqueId());
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS,
+ updateResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+
+ // checkIn resource
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+
+ // checkIn resource
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+ // certification request
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+ // start certification
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+ // certify
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getResourceValidateInvariantUuid(resource.getUniqueId(), invariantUUIDcreation);
+ // update resource
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ resourceDetails.setDescription("updatedDescription");
+ resourceDetails.setVendorRelease("1.2.3.4");
+ updateResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, designerUser,
+ resourceDetails.getUniqueId());
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, updateResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certification request
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // checkout resource
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certification request
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+ // start certification
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // cancel certification
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser,
+ LifeCycleStatesEnum.CANCELCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // start certification
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // failure
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, testerUser,
+ LifeCycleStatesEnum.FAILCERTIFICATION);
+ assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // upload artifact
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ ArtifactReqDetails artifactDetails = ElementFactory.getDefaultArtifact();
+ ArtifactRestUtils.addInformationalArtifactToResource(artifactDetails, designerUser,
+ resourceDetails.getUniqueId());
+ assertEquals(STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // checkIn resource
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, designerUser,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ // create instance
+ RestResponse createServiceResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ ResourceRestUtils.checkCreateResponse(createServiceResponse);
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, designerUser, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getResourceValidateInvariantUuid(resourceDetails.getUniqueId(), invariantUUIDcreation);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java
new file mode 100644
index 0000000000..a3372098a0
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetAllResourceVersions.java
@@ -0,0 +1,580 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GetAllResourceVersions extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(GetAllResourceVersions.class.getName());
+ protected User designerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ protected ResourceReqDetails resourceDetails;
+
+ public static TestName name = new TestName();
+
+ public GetAllResourceVersions() {
+ super(name, GetAllResourceVersions.class.getName());
+
+ }
+
+ //// NEW
+
+ protected void deleteAllVersionOfResource() throws Exception {
+ RestResponse response = null;
+
+ String[] versions = { "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "1.0", "1.1", "1.2", "1.3", "1.4", "1.5", "2.0",
+ "2.1", "2.2", "2.3", "2.4", "2.5", "3.0", "4.0", "4.1" };
+
+ for (String version : versions) {
+
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(designerDetails,
+ resourceDetails.getName().toUpperCase(), version);
+ AssertJUnit.assertTrue("delete request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 204 || response.getErrorCode() == 404);
+
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(designerDetails, resourceDetails.getName(),
+ version);
+ AssertJUnit.assertTrue("delete request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 204 || response.getErrorCode() == 404);
+
+ }
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+ resourceDetails = defineResourse();
+ deleteAllVersionOfResource();
+
+ }
+
+ @AfterMethod
+ public void endOfTests() throws Exception {
+ deleteAllVersionOfResource();
+ }
+
+ protected ResourceReqDetails defineResourse() {
+ String resourceName = "cisco4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ // String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(),
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory());
+
+ return resourceDetails;
+ }
+
+ @Test
+ public void getResourceAllVersions_version15() throws Exception {
+ // create resource
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ AssertJUnit.assertTrue("create request returned status:" + restResponse.getErrorCode(),
+ restResponse.getErrorCode() == 201);
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ // change resource version to 1.5
+ for (int x = 0; x < 5; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ AssertJUnit.assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ protected RestResponse createResource(User sdncModifierDetails, ResourceReqDetails resourceDetails)
+ throws Exception {
+ // clean ES DB
+ DbUtils.cleanAllAudits();
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after create resource", restResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource",
+ restResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create resource", 201,
+ restResponse.getErrorCode().intValue());
+
+ return restResponse;
+ }
+
+ @Test
+ public void getResourceAllVersions_version05() throws Exception {
+
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+
+ logger.debug("Changing resource life cycle ");
+ for (int x = 0; x < 4; x++) {
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ }
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_version01() throws Exception {
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_version25() throws Exception {
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201);
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // resource version 1.0
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ // change resource version to 1.5
+ for (int x = 0; x < 5; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // resource version 2.0
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ // change resource version to 2.5
+ for (int x = 0; x < 5; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_ReadyForCertification_version05() throws Exception {
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201);
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ }
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_CertifactionInProgress_version05() throws Exception {
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201);
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ }
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_Certified_version10() throws Exception {
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201);
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+
+ }
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_Certified_version20() throws Exception {
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+
+ // create resource
+ RestResponse restResponse = createResource(designerDetails, resourceDetails);
+ assertTrue("create request returned status:" + restResponse.getErrorCode(), restResponse.getErrorCode() == 201);
+ String resourceName = resourceDetails.getName();
+ // resourceUtils.addResourceMandatoryArtifacts(designerDetails,
+ // restResponse);
+
+ // change resource version to 0.5
+ RestResponse checkoutResource;
+ for (int x = 0; x < 4; x++) {
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // get to version 1.0
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ // change resource version to 1.5
+ for (int x = 0; x < 4; x++) {
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, designerDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200,
+ checkoutResource.getErrorCode().intValue());
+ }
+
+ // get to version 1.0
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+ origVersionsMap.put(resourceDetails.getVersion(), resourceDetails.getUniqueId());
+
+ // validate get response
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails,
+ resourceDetails.getUniqueId());
+ Resource res = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void getResourceAllVersions_ResourceNotFound() throws Exception {
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(designerDetails, "123456789");
+ assertEquals("Check response code after checkout resource", 404, resourceGetResponse.getErrorCode().intValue());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java
new file mode 100644
index 0000000000..ccf6142538
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/GetResourceNotAbstractApiTest.java
@@ -0,0 +1,326 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.imports.ImportGenericResourceCITest;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public class GetResourceNotAbstractApiTest extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
+ protected static final int STATUS_CODE_GET_SUCCESS = 200;
+
+ protected Config config = Config.instance();
+ protected String contentTypeHeaderData = "application/json";
+ protected String acceptHeaderDate = "application/json";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetResourceNotAbstractApiTest() {
+ super(name, GetResourceNotAbstractApiTest.class.getName());
+ }
+
+ @Test
+ public void getNotAbstractResourceList() throws Exception {
+
+ // remove all the not abstract resources
+ // Map<NormativeTypes, Boolean> originalState =
+ // ImportResourceCITest.removeAllNormativeTypeResources();
+
+ // import all the default not abstract resources
+ // ImportGenericResourceCITest.importAllNormativeTypesResources(UserRoleEnum.ADMIN);
+
+ // Get not abstract resources
+ RestResponse getResourceNotAbstarctResponse = getNotAbstractResources();
+ // Check that received 200.
+ assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS,
+ getResourceNotAbstarctResponse.getErrorCode().intValue());
+ // Verify that all the resources not abstract
+ assertTrue("One or more resources are abstract", isAllResourcesNotAbstract(getResourceNotAbstarctResponse));
+ // Verify that all the resources are certified
+ assertTrue("Not all the resources are certified", isAllResourcesCertified(getResourceNotAbstarctResponse));
+
+ String objectStorageUid = "ObjectStorage";
+ String computeUid = "Compute";
+ String blockStorageUid = "BlockStorage";
+ String loadBalancerUid = "LoadBalancer";
+ // String portUid = "tosca.nodes.Network.Port";
+ String portUid = "Port";
+ String networkUid = "Network";
+ String databaseUid = "Database";
+
+ // Compare expected list of abstract resources to actual list of
+ // abstract resources.
+ List<String> expectedNotAbstractResourcesUniqueIdArray = new ArrayList<String>(Arrays.asList(computeUid,
+ databaseUid, objectStorageUid, blockStorageUid, loadBalancerUid, portUid, networkUid));
+
+ List<String> actualNotAbstarctResourcesUniqueIdArray = restResponseToListByHeader(
+ getResourceNotAbstarctResponse, "name");
+
+ // Collections.sort(actualNotAbstarctResourcesUniqueIdArray);
+ // Collections.sort(expectedNotAbstractResourcesUniqueIdArray);
+
+ List<String> toFind = new ArrayList<>();
+ toFind.add(objectStorageUid);
+ toFind.add(computeUid);
+ toFind.add(blockStorageUid);
+ toFind.add(loadBalancerUid);
+ toFind.add(portUid);
+
+ boolean removeAll = toFind.removeAll(actualNotAbstarctResourcesUniqueIdArray);
+ logger.debug("Cannot find resources {}", toFind.toString());
+
+ for (String expectedResource : expectedNotAbstractResourcesUniqueIdArray) {
+ if (false == actualNotAbstarctResourcesUniqueIdArray.contains(expectedResource)) {
+ // System.out.println("Not found abstract resource " +
+ // expectedResource);
+ }
+ }
+
+ assertTrue(
+ "Expected abstract resources list: " + expectedNotAbstractResourcesUniqueIdArray.toString()
+ + " Actual: " + actualNotAbstarctResourcesUniqueIdArray.toString(),
+ actualNotAbstarctResourcesUniqueIdArray.containsAll(expectedNotAbstractResourcesUniqueIdArray));
+
+ /*
+ * java.lang.AssertionError: Expected abstract resources list:
+ * [tosca.nodes.Compute, tosca.nodes.ObjectStorage,
+ * tosca.nodes.BlockStorage, tosca.nodes.LoadBalancer,
+ * tosca.nodes.Network.Port] Actual: [resourceforproperty216,
+ * tosca.nodes.Compute, tosca.nodes.Database, resourceforproperty217,
+ * resourceforproperty217, tosca.nodes.ObjectStorage,
+ * tosca.nodes.BlockStorage, tosca.nodes.LoadBalancer,
+ * tosca.nodes.network.Port, tosca.nodes.network.Network,
+ * resourceforproperty217, resourceforproperty217,
+ * resourceforproperty217, resourceforproperty217,
+ * resourceforproperty217, resourceforproperty217,
+ * resourceforproperty217, resourceforproperty217,
+ * resourceforproperty217, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317,
+ * resourceforproperty317, resourceforproperty317]
+ */
+
+ // Create resource (not certified)
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ String resourceName = "TestResource";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.0";
+ String contactId = "Peter";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ // assertEquals("Check response code after create user", 201,
+ // restResponse.getErrorCode().intValue());
+
+ // Get not abstract resources
+ getResourceNotAbstarctResponse = getNotAbstractResources();
+ // Check that received 200.
+ assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS,
+ getResourceNotAbstarctResponse.getErrorCode().intValue());
+ // Verify that all the resources not abstract
+ assertTrue("One or more resources are abstract", isAllResourcesNotAbstract(getResourceNotAbstarctResponse));
+ // Verify that all the resources are certified
+ assertTrue("Not all the resources are certified", isAllResourcesCertified(getResourceNotAbstarctResponse));
+
+ // Compare expected list of abstract resources to actual list of
+ // abstract resources.
+ // expectedNotAbstractResourcesUniqueIdArray = new
+ // ArrayList<String>(Arrays.asList("tosca.nodes.compute.1.0",
+ // "tosca.nodes.objectstorage.1.0", "tosca.nodes.blockstorage.1.0",
+ // "tosca.nodes.loadbalancer.1.0", "tosca.nodes.network.port.1.0"));
+
+ // actualNotAbstarctResourcesUniqueIdArray =
+ // restResponseToListByHeader(getResourceNotAbstarctResponse,
+ // "uniqueId");
+
+ actualNotAbstarctResourcesUniqueIdArray = restResponseToListByHeader(getResourceNotAbstarctResponse, "name");
+
+ Collections.sort(actualNotAbstarctResourcesUniqueIdArray);
+ Collections.sort(expectedNotAbstractResourcesUniqueIdArray);
+
+ for (String expectedResource : expectedNotAbstractResourcesUniqueIdArray) {
+ if (false == actualNotAbstarctResourcesUniqueIdArray.contains(expectedResource)) {
+ // System.out.println("Not found abstract resource " +
+ // expectedResource);
+ }
+ }
+ assertTrue(
+ "Expected abstract resources list: " + expectedNotAbstractResourcesUniqueIdArray.toString()
+ + " Actual: " + actualNotAbstarctResourcesUniqueIdArray.toString(),
+ actualNotAbstarctResourcesUniqueIdArray.containsAll(expectedNotAbstractResourcesUniqueIdArray));
+ // assertTrue("Expected abstract resources list: "+
+ // expectedNotAbstractResourcesUniqueIdArray.toString()+ " Actual:
+ // "+actualNotAbstarctResourcesUniqueIdArray.toString(),expectedNotAbstractResourcesUniqueIdArray.equals(actualNotAbstarctResourcesUniqueIdArray));
+
+ // restore the resources
+ // ImportResourceCITest.restoreToOriginalState(originalState);
+
+ }
+
+ protected RestResponse getNotAbstractResources() throws Exception {
+ HttpRequest httpRequest = new HttpRequest();
+
+ String url = String.format(Urls.GET_ALL_NOT_ABSTRACT_RESOURCES, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
+
+ RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap);
+
+ return getResourceNotAbstarctResponse;
+ }
+
+ protected List<String> restResponseToListByHeader(RestResponse restResponse, String restResponseHeader) {
+ JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
+ JsonArray jsonArray = jelement.getAsJsonArray();
+
+ List<String> restResponseArray = new ArrayList<>();
+
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JsonObject jobject = (JsonObject) jsonArray.get(i);
+ String header = jobject.get(restResponseHeader).toString();
+ header = header.replace("\"", "");
+ restResponseArray.add(header);
+ }
+
+ return restResponseArray;
+
+ }
+
+ protected boolean isAllResourcesNotAbstract(RestResponse restResponse) {
+ JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
+ JsonArray jsonArray = jelement.getAsJsonArray();
+
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JsonObject jobject = (JsonObject) jsonArray.get(i);
+
+ if (jobject.get("abstract").getAsBoolean()) {
+ return false;
+ }
+
+ }
+ return true;
+
+ }
+
+ protected boolean isEmptyList(RestResponse restResponse) {
+ JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
+ JsonArray jsonArray = jelement.getAsJsonArray();
+
+ if (jsonArray.size() == 0) {
+ return true;
+ }
+ return false;
+ }
+
+ protected boolean isAllResourcesCertified(RestResponse restResponse) {
+ JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
+ JsonArray jsonArray = jelement.getAsJsonArray();
+
+ String certified = "CERTIFIED";
+ String lifecycleState;
+
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JsonObject jobject = (JsonObject) jsonArray.get(i);
+ lifecycleState = jobject.get("lifecycleState").getAsString();
+ if (!lifecycleState.equals(certified)) {
+ return false;
+ }
+
+ }
+ return true;
+ }
+
+ @Test(enabled = false)
+ public void getEmptyNonAbstractResourcesList() throws Exception {
+ // remove all the not abstract resources
+ Map<NormativeTypesEnum, Boolean> originalState = ImportGenericResourceCITest.removeAllNormativeTypeResources();
+
+ // Get not abstract resources
+ RestResponse getResourceNotAbstarctResponse = getNotAbstractResources();
+ // Check that received 200.
+ assertEquals("Check response code after get abstract resources", STATUS_CODE_GET_SUCCESS,
+ getResourceNotAbstarctResponse.getErrorCode().intValue());
+ // Verify empty list
+ assertTrue("Received list is not empty", isEmptyList(getResourceNotAbstarctResponse));
+
+ // restore the resources
+ // ImportResourceCITest.restoreToOriginalState(originalState);
+ // import the resources
+ ImportGenericResourceCITest.importAllNormativeTypesResources(UserRoleEnum.ADMIN);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java
new file mode 100644
index 0000000000..eac33242ed
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ResourceApiTest.java
@@ -0,0 +1,366 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class ResourceApiTest extends ComponentBaseTest {
+
+ protected final String contentTypeHeaderData = "application/json";
+ protected final String acceptHeaderDate = "application/json";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ResourceApiTest() {
+ super(name, ResourceApiTest.class.getName());
+ }
+
+ // Keep
+ @Test
+ public void updateResourceMetadataSuccess() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncModifierDetails.setUserId("jh0003");
+ RestResponse restResponse = createResourceForUpdate(sdncModifierDetails);
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ // set resource details
+ ResourceReqDetails resourceDetails = new ResourceReqDetails();
+ resourceDetails.setDescription("updatedDescription");
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ // Duplicate tags are allowed and should be de-duplicated by the server
+ // side
+ resourceTags.add(resourceRespJavaObject.getName());
+ resourceTags.add("tag1");
+ resourceTags.add("tag1");
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ resourceDetails.setTags(resourceTags);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.NETWORK_L2_3_ROUTERS.getCategory(),
+ ResourceCategoryEnum.NETWORK_L2_3_ROUTERS.getSubCategory());
+ resourceDetails.setVendorName("OracleUp");
+ resourceDetails.setVendorRelease("1.5Up");
+ resourceDetails.setContactId("pe1116");
+
+ resourceDetails.setIcon(resourceRespJavaObject.getIcon());
+ resourceDetails.setName(resourceRespJavaObject.getName());
+ resourceDetails.setDerivedFrom(resourceRespJavaObject.getDerivedFrom());
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceRespJavaObject.getUniqueId());
+ RestResponse updateResourceResponse = http.httpSendByMethod(url, "PUT", userBodyJson, headersMap);
+
+ // resourceDetails.setResourceName(resourceRespJavaObject.getResourceName());
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails,
+ ResponseParser.convertResourceResponseToJavaObject(updateResourceResponse.getResponse()));
+
+ // Delete resource
+ deleteResource(resourceRespJavaObject.getUniqueId(), sdncModifierDetails.getUserId());
+
+ }
+
+ protected void deleteResource(String resourceUniqueId, String httpCspUserId) throws Exception {
+ RestResponse res = ResourceRestUtils.deleteResource(resourceUniqueId, httpCspUserId);
+
+ // System.out.println("Delete resource was finished with response: " +
+ // res.getErrorCode());
+ }
+
+ protected RestResponse createResourceForUpdate(User sdncModifierDetails) throws Exception {
+
+ ResourceReqDetails resourceDetails = getResourceObj();
+
+ // create resource
+ return ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ }
+
+ public ResourceReqDetails getResourceObj() {
+ // set resource details
+ String resourceName = "ResourceForUpdate" + (int) (Math.random() * 100);
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ // String category = ResourceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "pe1116";
+ String icon = "myICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(),
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory());
+ return resourceDetails;
+ }
+
+ // -------------------------------------------------------------------
+
+ protected ResourceReqDetails defineResourse_Benny(int n) {
+ String resourceName = "cisco" + String.valueOf(n);
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("tag1");
+ String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "borderElement";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ return resourceDetails;
+ }
+
+ @Test
+ public void getAllAbstractResources() throws Exception {
+ RestResponse abstractResources = CatalogRestUtils.getAbstractResources();
+
+ int status = abstractResources.getErrorCode();
+ assertTrue(status == 200);
+ String json = abstractResources.getResponse();
+ JSONArray array = (JSONArray) JSONValue.parse(json);
+ for (Object o : array) {
+ JSONObject value = (JSONObject) o;
+ Boolean element = (Boolean) value.get("abstract");
+ assertTrue(element);
+ }
+
+ }
+
+ @Test
+ public void getAllNotAbstractResources() throws Exception {
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+ String url = String.format(Urls.GET_ALL_NOT_ABSTRACT_RESOURCES, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+ HttpGet httpget = new HttpGet(url);
+
+ httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+
+ httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+
+ httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+
+ // System.out.println("Executing request " +
+ // httpget.getRequestLine());
+ CloseableHttpResponse response = httpclient.execute(httpget);
+ int status = response.getStatusLine().getStatusCode();
+ assertTrue(status == 200);
+ try {
+ String json = EntityUtils.toString(response.getEntity());
+ JSONArray array = (JSONArray) JSONValue.parse(json);
+ for (Object o : array) {
+ JSONObject value = (JSONObject) o;
+ Boolean element = (Boolean) value.get("abstract");
+ assertTrue(!element);
+ }
+
+ } finally {
+ response.close();
+ }
+ } finally {
+ httpclient.close();
+ }
+ }
+
+ @Test
+ public void updateResourceMetadata_methodNotAllowed() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ // set resource details
+ String resourceName = "ResForUpdate";
+ String description = "updatedDescription";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("tag1");
+ resourceTags.add("tag2");
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add("tosca.nodes.root");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ String vendorName = "OracleUp";
+ String vendorRelease = "1.5Up";
+ String contactId = "pe1117";
+ String icon = "myICON.jpgUp";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category,
+ derivedFrom, vendorName, vendorRelease, contactId, icon);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ "NotExistsId");
+
+ RestResponse updateResourceResponse = http.httpSendByMethod(url, "POST", userBodyJson, headersMap);
+
+ assertNotNull("Check error code exists in response after wrong update resource",
+ updateResourceResponse.getErrorCode());
+ assertEquals("Check error code after update resource", 405, updateResourceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void validateResourceNameTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncModifierDetails.setUserId("jh0003");
+
+ ResourceReqDetails resourceDetails = getResourceObj();
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ Resource resourceRespJavaObject = ResponseParser
+ .convertResourceResponseToJavaObject(restResponse.getResponse());
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ try {
+
+ // check invalid
+ String url = String.format(Urls.VALIDATE_RESOURCE_NAME, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetails.getName());
+
+ HttpGet httpget = new HttpGet(url);
+
+ httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+
+ httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+
+ httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ // System.out.println("Executing request " +
+ // httpget.getRequestLine());
+ CloseableHttpResponse response = httpclient.execute(httpget);
+ int status = response.getStatusLine().getStatusCode();
+ assertTrue(status == 200);
+ try {
+ String json = EntityUtils.toString(response.getEntity());
+ JSONObject object = (JSONObject) JSONValue.parse(json);
+ Boolean element = (Boolean) object.get("isValid");
+ assertTrue(!element);
+
+ } finally {
+ response.close();
+ }
+ // check valid
+ url = String.format(Urls.VALIDATE_RESOURCE_NAME, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceDetails.getName() + "temp");
+
+ httpget = new HttpGet(url);
+
+ httpget.addHeader(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+
+ httpget.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+
+ httpget.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ // System.out.println("Executing request " +
+ // httpget.getRequestLine());
+ response = httpclient.execute(httpget);
+ status = response.getStatusLine().getStatusCode();
+ assertTrue(status == 200);
+ try {
+ String json = EntityUtils.toString(response.getEntity());
+ JSONObject object = (JSONObject) JSONValue.parse(json);
+ Boolean element = (Boolean) object.get("isValid");
+ assertTrue(element);
+
+ } finally {
+ response.close();
+ }
+ } finally {
+ httpclient.close();
+ }
+
+ // Delete resource
+ ResourceRestUtils.deleteResource(resourceDetails, sdncModifierDetails, "0.1");
+
+ }
+
+ // -------------------------------------------------------------------
+ // //Benny Tal
+ // @Test
+ // public void createResource_Benny() throws Exception {
+ // for (int i = 0; i < 100; i++) {
+ // ResourceReqDetails resourceDetails = defineResourse_Benny(i);
+ //
+ // ResourceRestUtils.createResource(resourceDetails,
+ // UserUtils.getDesignerDetails());
+ // // resourceUtils.deleteResource(resourceDetails,
+ // UserUtils.getDesignerDetails(), "0.1");
+ // }
+ // }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java
new file mode 100644
index 0000000000..f4a4fa108a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SampleDataProvider.java
@@ -0,0 +1,41 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import java.io.IOException;
+
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.testng.ITestContext;
+import org.testng.annotations.DataProvider;
+
+public class SampleDataProvider {
+
+ @DataProvider
+ public static Object[][] getResourceByType(ITestContext context) throws IOException, Exception {
+ return new Object[][] {
+ { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true) },
+ { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true) },
+ { AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true) } };
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java
new file mode 100644
index 0000000000..de83385029
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/SimultaneousApiTest.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.Test;
+
+public class SimultaneousApiTest extends ComponentBaseTest {
+
+ protected static ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+
+ @Rule
+ public static TestName name = new TestName();
+
+ static String httpCspUserId = "km2000";
+ static String userFirstName = "Kot";
+ static String userLastName = "Matroskin";
+ static String email = "km2000@intl.sdc.com";
+ static String role = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getRole();
+
+ public SimultaneousApiTest() {
+ super(name, SimultaneousApiTest.class.getName());
+
+ }
+
+ public static class WorkerThread implements Runnable {
+ CountDownLatch countDownLatch;
+ int threadIndex;
+
+ public WorkerThread(int threadIndex, CountDownLatch countDownLatch) {
+ this.threadIndex = threadIndex;
+ this.countDownLatch = countDownLatch;
+ }
+
+ @Override
+ public void run() {
+ System.out.println("**** Thread started " + threadIndex);
+ try {
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ String id = ResponseParser.getUniqueIdFromResponse(createResource);
+ // System.out.println("**** Thread " + threadIndex + " create
+ // resource status " + createResource.getErrorCode() + " id = "
+ // + id + " error " + createResource.getResponse());
+ // assertEquals("**** create resource: " +
+ // createResource.getErrorCode() + " thread " + threadIndex,
+ // 201, status);
+ } catch (Exception e) {
+ // System.out.println("**** Thread " + threadIndex + " exception
+ // " + e);
+ }
+ countDownLatch.countDown();
+ // System.out.println("**** Thread finished " + threadIndex);
+
+ }
+
+ }
+
+ @Test
+ public void create2Resources() throws InterruptedException {
+ int threadCount = 5;
+ CountDownLatch countDownLatch = new CountDownLatch(threadCount);
+ ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ Runnable worker = new WorkerThread(i + 1, countDownLatch);
+ executor.execute(worker);
+ }
+ countDownLatch.await();
+ // System.out.println(" finished ");
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java
new file mode 100644
index 0000000000..b61489d12d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/UpdateResourceMetadataTest.java
@@ -0,0 +1,2254 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class UpdateResourceMetadataTest extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(UpdateResourceMetadataTest.class.getName());
+ protected List<String> Empty_List = new ArrayList<String>();
+ protected String extendedChars;
+
+ protected final String contentTypeHeaderData = "application/json";
+ protected final String acceptHeaderDate = "application/json";
+ protected final String CHARSET_ISO_8859 = "charset=ISO-8859-1";
+
+ public static TestName name = new TestName();
+ protected User sdncModifierDetails;
+ protected ResourceReqDetails resourceDetails;
+
+ public UpdateResourceMetadataTest() {
+ super(name, UpdateResourceMetadataTest.class.getName());
+
+ }
+
+ public String extendedCharsStringBuilder() throws Exception {
+ char[] extendedCharsArray = new char[128];
+ char ch = 128;
+ for (int i = 0; i < extendedCharsArray.length - 1; i++) {
+ extendedCharsArray[i] = ch;
+ ch++;
+ }
+ extendedChars = new String(extendedCharsArray);
+ return extendedChars;
+
+ }
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ resourceDetails = defineResourse();
+
+ }
+
+ // Keep
+ @Test
+ public void UpdateDerivedFromSuccess() throws Exception {
+
+ String oldDerivedFromName = NormativeTypesEnum.ROOT.getNormativeName();
+ String newDerivedFromName = NormativeTypesEnum.SOFTWARE_COMPONENT.getNormativeName();
+
+ // Getting both derived from resources for validation
+ /*
+ * RestResponse resourceByNameAndVersion = resourceUtils.getResourceByNameAndVersion(sdncModifierDetails, oldDerivedFromName, "1.0"); assertEquals("Check response code after get database normative", 200,
+ * resourceByNameAndVersion.getErrorCode().intValue()); Resource databaseNormative = resourceUtils.parseResourceResp(resourceByNameAndVersion);
+ *
+ * resourceByNameAndVersion = resourceUtils.getResourceByNameAndVersion(sdncModifierDetails, newDerivedFromName, "1.0"); assertEquals("Check response code after get database normative", 200,
+ * resourceByNameAndVersion.getErrorCode().intValue()); Resource lbNormative = resourceUtils.parseResourceResp(resourceByNameAndVersion);
+ */
+
+ // Derived from set to Database
+ List<String> derivedFrom = new ArrayList<>();
+ derivedFrom.add(oldDerivedFromName);
+ resourceDetails.setDerivedFrom(derivedFrom);
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ AssertJUnit.assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResource = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ derivedFrom.clear();
+ derivedFrom.add(newDerivedFromName);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResource.getUniqueId(), "");
+ AssertJUnit.assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue());
+
+ }
+
+ protected ResourceReqDetails defineUpdateResourceWithNonUpdatableFields(Resource resourceBeforeUpdate) {
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceBeforeUpdate.getName());
+
+ updatedResourceDetails.setVersion("mumu");
+ updatedResourceDetails.setIsAbstract(true);
+ updatedResourceDetails.setIsHighestVersion(true);
+ updatedResourceDetails.setCreatorUserId("df4444");
+ updatedResourceDetails.setCreatorFullName("John Doe");
+ updatedResourceDetails.setLastUpdaterUserId("gf5646");
+ updatedResourceDetails.setLastUpdaterFullName("Viktor Tzoy");
+ updatedResourceDetails.setCreationDate(new Long(4444));
+ updatedResourceDetails.setLastUpdateDate(new Long("534535"));
+ updatedResourceDetails.setLifecycleState(LifecycleStateEnum.READY_FOR_CERTIFICATION);
+ updatedResourceDetails.setCost("6.1");
+ updatedResourceDetails.setLicenseType("Installation");
+ updatedResourceDetails.setUUID("dfsfsdf");
+ return updatedResourceDetails;
+ }
+
+ public void UpdateResourceNotFoundTest() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ String resourceName = "cisco4";
+ // update resource
+ String description = "updatedDescription";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.MOBILITY.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "newOracle";
+ String vendorRelease = "2.5";
+ String contactId = "jh0003";
+ String icon = "myICON";
+
+ ResourceReqDetails updatedResourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ updatedResourceDetails.setUniqueId("dummyId");
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, "0.1");
+
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after update resource", 404, updatedRestResponse.getErrorCode().intValue());
+ // String resourceId =
+ // UniqueIdBuilder.buildResourceUniqueId(resourceName, "0.1");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), Arrays.asList("dummyId"), updatedRestResponse.getResponse());
+
+ resourceName = "";
+ // resourceId = UniqueIdBuilder.buildResourceUniqueId(resourceName,
+ // "0.1");
+ updatedResourceDetails = defineUpdatedResourse(resourceName);
+ updatedResourceDetails.setUniqueId("dummyId");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, "0.1");
+ AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), Arrays.asList("dummyId"), updatedRestResponse.getResponse());
+
+ }
+
+ public char[] getInValidChars() throws Exception {
+
+ char[] extendedCharsArray = new char[59];
+ char ch = 1;
+ for (int i = 0; i < 44; i++) {
+ extendedCharsArray[i] = ch;
+ ch++;
+ }
+ ch = 58;
+ for (int i = 44; i < 51; i++) {
+ extendedCharsArray[i] = ch;
+ ch++;
+ }
+ ch = 91;
+ for (int i = 51; i < 55; i++) {
+ extendedCharsArray[i] = ch;
+ ch++;
+ }
+ ch = 123;
+ for (int i = 55; i < 59; i++) {
+ extendedCharsArray[i] = ch;
+ ch++;
+ }
+ return extendedCharsArray;
+ }
+
+ public char[] getTagInValidFormatChars() throws Exception {
+ // Tag format is the same as defined for Resource Name :
+ // Allowed characters: Alphanumeric (a-zA-Z0-9), space (' '), underscore
+ // ('_'), dash ('-'), dot ('.')
+ char[] notValidCharsArray = new char[30];
+ char ch = 33;
+ for (int i = 0; i < 12; i++) {
+ notValidCharsArray[i] = ch;
+ ch++;
+ }
+ notValidCharsArray[13] = 47;
+ ch = 58;
+ for (int i = 14; i < 21; i++) {
+ notValidCharsArray[i] = ch;
+ ch++;
+ }
+ ch = 91;
+ for (int i = 21; i < 24; i++) {
+ notValidCharsArray[i] = ch;
+ ch++;
+ }
+ notValidCharsArray[24] = 96;
+ ch = 123;
+ for (int i = 25; i < 30; i++) {
+ notValidCharsArray[i] = ch;
+ ch++;
+ }
+ return notValidCharsArray;
+ }
+
+ public void Validation_UpdateWithIncompleteJsonBodyTest() throws Exception {
+ // init ADMIN user
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // define and create resource
+ ResourceReqDetails resourceDetails = defineResourse();
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "0.1");
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.0");
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.1");
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceId = resourceDetails.getUniqueId();
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
+
+ // build Json Object
+ JSONObject jsonObject = JsonObjectBuilder(resourceDetails);
+
+ List<String> resource = new ArrayList<>();
+ resource.add("Resource");
+
+ // remove Description
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "description", ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource);
+ // remove Tags
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "tags", ActionStatus.COMPONENT_MISSING_TAGS.name(), Empty_List);
+ // remove Category
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "category", ActionStatus.COMPONENT_MISSING_CATEGORY.name(), resource);
+ // remove VendorName
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "vendorName", ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List);
+ // remove VendorRelease
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "vendorRelease", ActionStatus.MISSING_VENDOR_RELEASE.name(), Empty_List);
+ // remove AT&T Contact
+ UpdateAndValidateWithIncompletedJsonBody(sdncModifierDetails, jsonObject, resourceId, "contactId", ActionStatus.COMPONENT_MISSING_CONTACT.name(), resource);
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, "0.1");
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after get resource", getRestResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "0.1");
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.0");
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, resourceDetails.getName(), "1.1");
+ }
+
+ // End of validation tests
+ // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+ protected ResourceReqDetails defineUpdatedResourse(String resourceName) {
+ String description = "updatedDescription";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ // Duplicate tags are allowed and should be de-duplicated by server side
+ resourceTags.add(resourceName);
+ resourceTags.add("tag1");
+ resourceTags.add("tag1");
+ resourceTags.add("tag2");
+ resourceTags.add("tag2");
+ String category = ServiceCategoriesEnum.VOIP.getValue();
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());
+ String vendorName = "updatedOracle";
+ String vendorRelease = "3.5";
+ String contactId = "jh0001";
+ String icon = "myUpdatedICON";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, category, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory());
+
+ return resourceDetails;
+ }
+
+ protected ResourceReqDetails defineResourse() {
+ String resourceName = "cisco4";
+ String description = "description";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(NormativeTypesEnum.ROOT.getNormativeName());// "tosca.nodes.Root");
+ String vendorName = "Oracle";
+ String vendorRelease = "1.5";
+ String contactId = "jh0003";
+ String icon = "objectStorage";
+
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getCategory(), ResourceCategoryEnum.GENERIC_INFRASTRUCTURE.getSubCategory());
+
+ return resourceDetails;
+ }
+
+ protected RestResponse createResource(User sdncModifierDetails, ResourceReqDetails resourceDetails) throws Exception {
+ // clean ES DB
+ DbUtils.cleanAllAudits();
+
+ // create resource
+ RestResponse restResponse = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after create resource", restResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create resource", restResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+
+ return restResponse;
+ }
+
+ protected RestResponse TryUpdateByAnotherVerb(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, String uri) throws Exception {
+ // delete resource
+ Config config;
+ RestResponse ResourceResponse;
+ try {
+ config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), updatedResourceDetails.getName() + ".0.1");
+
+ if (uri == "GET") {
+ ResourceResponse = http.httpSendGet(url, headersMap);
+ } else if (uri == "POST") {
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(updatedResourceDetails);
+ ResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ } else if (uri == "DELETE") {
+ ResourceResponse = http.httpSendDelete(url, headersMap);
+ } else
+ return null;
+
+ return ResourceResponse;
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return null;
+
+ }
+
+ protected JSONObject JsonObjectBuilder(ResourceReqDetails resourceDetails) throws JSONException {
+ // json object: resourceName and icon are must
+ JSONObject jObject = new JSONObject();
+
+ List<String> tagsList = Arrays.asList(resourceDetails.getName());
+ List<String> derivedFromList = Arrays.asList("[tosca.nodes.Root]");
+
+ jObject.put("name", resourceDetails.getName());
+ jObject.put("description", "updatedDescription");
+ jObject.put("tags", tagsList);
+ jObject.put("category", ServiceCategoriesEnum.VOIP.getValue());
+ jObject.put("derivedFrom", derivedFromList);
+ jObject.put("vendorName", "newOracle");
+ jObject.put("vendorRelease", "1.5");
+ jObject.put("contactId", "jh0003");
+ jObject.put("icon", resourceDetails.getIcon());
+
+ return jObject;
+ }
+
+ protected JSONObject RemoveFromJsonObject(JSONObject jObject, String removedPropery) {
+ jObject.remove(removedPropery);
+
+ return jObject;
+ }
+
+ // purpose: function for controlling json body fields and validating
+ // response
+ protected void UpdateAndValidateWithIncompletedJsonBody(User sdncModifierDetails, JSONObject jsonObject, String resourceId, String removedField, String errorMessage, List<String> variables) throws Exception {
+
+ JSONObject jObject = new JSONObject(jsonObject, JSONObject.getNames(jsonObject));
+ // remove description from jsonObject
+ jObject = RemoveFromJsonObject(jObject, removedField);
+ // update with incomplete body.
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(jObject.toString(), sdncModifierDetails, resourceId);
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(errorMessage, variables, updatedRestResponse.getResponse());
+
+ }
+
+ // purpose: function for validating error response
+ protected void UpdateAndValidate(User sdncModifierDetails, ResourceReqDetails resourceDetails, String recievedMessage, List<String> variables) throws Exception {
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, "0.1");
+ // validate response
+ AssertJUnit.assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(recievedMessage, variables, updatedRestResponse.getResponse());
+
+ }
+
+ protected void parseResponseAndValidateNonUpdatable(ResourceReqDetails resourceDetails, RestResponse restResponse) throws Exception {
+ // parse response to javaObject
+ Resource updatedResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ AssertJUnit.assertTrue(!resourceDetails.getIsHighestVersion().equals(updatedResourceRespJavaObject.isHighestVersion()));
+ AssertJUnit.assertTrue(!resourceDetails.getVersion().equals(updatedResourceRespJavaObject.getName()));
+ AssertJUnit.assertTrue(!resourceDetails.getIsAbstract().equals(updatedResourceRespJavaObject.isAbstract()));
+ AssertJUnit.assertTrue(!resourceDetails.getCreatorUserId().equals(updatedResourceRespJavaObject.getCreatorUserId()));
+ AssertJUnit.assertTrue(!resourceDetails.getCreatorFullName().equals(updatedResourceRespJavaObject.getCreatorFullName()));
+ AssertJUnit.assertTrue(!resourceDetails.getLastUpdateDate().equals(updatedResourceRespJavaObject.getLastUpdateDate()));
+ AssertJUnit.assertTrue(!resourceDetails.getCreationDate().equals(updatedResourceRespJavaObject.getCreationDate()));
+ AssertJUnit.assertTrue(!resourceDetails.getLastUpdaterUserId().equals(updatedResourceRespJavaObject.getLastUpdaterUserId()));
+ AssertJUnit.assertTrue(!resourceDetails.getLastUpdaterFullName().equals(updatedResourceRespJavaObject.getLastUpdaterFullName()));
+ AssertJUnit.assertTrue(!resourceDetails.getLifecycleState().equals(updatedResourceRespJavaObject.getLifecycleState()));
+ AssertJUnit.assertTrue(!resourceDetails.getCost().equals(updatedResourceRespJavaObject.getCost()));
+ AssertJUnit.assertTrue(!resourceDetails.getLicenseType().equals(updatedResourceRespJavaObject.getLicenseType()));
+ AssertJUnit.assertTrue(!resourceDetails.getUUID().equals(updatedResourceRespJavaObject.getUUID()));
+ }
+
+ protected void parseResponseAndValidate(ResourceReqDetails ResourceDetails, RestResponse restResponse) throws Exception {
+ // parse response to javaObject
+ Resource updatedResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ // validate request vs response
+ ResourceValidationUtils.validateResourceReqVsResp(ResourceDetails, updatedResourceRespJavaObject);
+ }
+
+ public ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails, String resourceVersion) {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+
+ expectedResourceAuditJavaObject.setAction("Checkout");
+ expectedResourceAuditJavaObject.setModifierUid(UserRoleEnum.ADMIN.getUserId());
+ expectedResourceAuditJavaObject.setModifierName(UserRoleEnum.ADMIN.getUserName());
+ expectedResourceAuditJavaObject.setStatus("200.0");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName().toLowerCase());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(resourceVersion) - 0.1f));
+ expectedResourceAuditJavaObject.setCurrVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public enum FieldToValidate {
+ ContactId, Tags, VendorName, VendorRelease, Description
+ }
+
+ @Test
+ public void UpdateBy_postTest() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // update resource - without changing resourceName
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+
+ RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, "POST");
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, updatedRestResponse.getResponse());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(resourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateBy_getTest() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // update resource - without changing resourceName
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, "GET");
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, updatedRestResponse.getResponse());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(resourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateBy_deleteTest() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // update resource - without changing resourceName
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ RestResponse updatedRestResponse = TryUpdateByAnotherVerb(updatedResourceDetails, sdncModifierDetails, "DELETE");
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), Empty_List, updatedRestResponse.getResponse());
+
+ RestResponse getRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(resourceDetails, getRestResponse);
+
+ }
+
+ // TODO DE
+ // @Ignore("")
+ @Test
+ public void UpdateWithInvaldJsonBodyTest() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
+ String resourceId = resourceDetails.getUniqueId();
+
+ // update Descirption value
+ String description = "updatedDescription";
+
+ // send update with incompleted json, only description string
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(description, sdncModifierDetails, resourceId);
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("check error code after update resource", 400, updatedRestResponse.getErrorCode().intValue());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(resourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateResourceNameSensitiveTest() throws Exception {
+ User sdncModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+ String resourceName = "Ab";
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ // Delete resources
+ RestResponse response = null;
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.1");
+ BaseRestUtils.checkDeleteResponse(response);
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.2");
+ BaseRestUtils.checkDeleteResponse(response);
+
+ RestResponse restResponse = createResource(sdncModifierDetails, updatedResourceDetails);
+ assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue());
+
+ // check-in Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(updatedResourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // String resourceCertifyVersion = "0.1";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(updatedResourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ updatedResourceDetails.setName("ABC_-bt.aT");
+ ArrayList<String> resourceTag = new ArrayList<String>();
+ resourceTag.add(0, "ABC_-bt.aT");
+ updatedResourceDetails.setTags(resourceTag);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, updatedResourceDetails.getUniqueId(), "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(updatedResourceDetails, updatedRestResponse);
+
+ // Delete resources
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.1");
+ BaseRestUtils.checkDeleteResponse(response);
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.2");
+ BaseRestUtils.checkDeleteResponse(response);
+
+ }
+
+ @Test
+ public void UpdateIcon_InegativeFlow() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ List<String> resourceList = new ArrayList<String>();
+ resourceList.add(0, "Resource");
+ // check InValid Characters
+ char[] notValidCharsArray = new char[59];
+ notValidCharsArray = getInValidChars();
+ // update metadata details
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ RestResponse updatedRestResponse;
+
+ for (int i = 0; i < notValidCharsArray.length; i++) {
+ // change icon of metadata
+ updatedResourceDetails.setIcon("MyIcon" + notValidCharsArray[i]);
+ // PUT request
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource icon", 400, updatedRestResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating resource icon", "Bad Request", updatedRestResponse.getResponseMessage().toString());
+
+ }
+
+ // empty icon
+ String updateIcon = "";
+ updatedResourceDetails.setIcon(updateIcon);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), resourceList, updatedRestResponse.getResponse());
+
+ // Icon length more then 25 characters
+ resourceList.add(1, "25");
+ updatedResourceDetails.setIcon("1234567890_-qwertyuiopASDNNN");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after create resource", 400, updatedRestResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating resource icon", "Bad Request", updatedRestResponse.getResponseMessage().toString());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResource_NoTagsEqualToResourceName() throws Exception {
+
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+ updatedResourceDetails.setName("updatedResourceName");
+ List<String> tags = updatedResourceDetails.getTags();
+
+ for (Iterator<String> iter = tags.listIterator(); iter.hasNext();) {
+ String a = iter.next();
+ if (a.equals("updatedResourceName")) {
+ iter.remove();
+ }
+ }
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource icon", 400, updatedRestResponse.getErrorCode().intValue());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResourceName_negativeFlow() throws Exception {
+ // The validation are done in Tag's validation
+ User sdncAdminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ RestResponse updatedRestResponse;
+ RestResponse restResponse = createResource(sdncAdminModifierDetails, resourceDetails);
+ assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue());
+ String uniqueId = resourceDetails.getUniqueId();
+ String resourceName = resourceDetails.getName();
+ // check InValid Characters
+ char[] notValidCharsArray = new char[59];
+ notValidCharsArray = getInValidChars();
+ ArrayList<String> resource_Name = new ArrayList<String>();
+ List<String> resourceList = new ArrayList<String>();
+
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceList.add(0, "Resource");
+
+ // update metadata details
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ for (int i = 0; i < notValidCharsArray.length; i++, resource_Name.clear()) {
+ if (i != 1 && i != 46 && /*
+ * i != 8 && i != 9 && i != 10 && i != 11 && i != 12 &&
+ */ i != 31) // space ("") and dot(.)
+ {
+ // change resourceName parameter
+ updatedResourceDetails.setName("UpdatedResourceName" + notValidCharsArray[i]);
+ resource_Name.add("UpdatedResourceName" + notValidCharsArray[i]);
+ updatedResourceDetails.setTags(resource_Name);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, uniqueId, "");
+ // validate response
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_TAG.name(),
+ // Empty_List, updatedRestResponse.getResponse());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), resourceList, updatedRestResponse.getResponse());
+
+ }
+ }
+
+ // resourceName length more then 50 characters
+ // Duplicate tags are allowed and should be de-duplicated by server side
+ resource_Name.add(resourceName);
+ resource_Name.add("tag1");
+ resource_Name.add("tag1");
+ resource_Name.add("tag2");
+ resource_Name.add("tag2");
+
+ resourceList.add(1, "1024");
+ // updatedResourceDetails.setName("123456789012345678901234567890123456789012345678901");
+ updatedResourceDetails.setName(new String(new char[1025]).replace("\0", "a"));
+ // resource_Name.add("123456789012345678901234567890123456789012345678901");
+ updatedResourceDetails.setTags(resource_Name);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, uniqueId, "");
+ // validate response
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), resourceList, updatedRestResponse.getResponse());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncAdminModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ // delete resource
+ RestResponse response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, updatedResourceDetails.getName(), "0.1");
+ BaseRestUtils.checkDeleteResponse(response);
+ }
+
+ @Test
+ public void UpdateResourceInformation_NotCheckedOut() throws Exception {
+
+ String resourceBaseVersion = "0.1";
+ List<String> resourceList = new ArrayList<String>();
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // CheckIn Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN); // NOT_CERTIFIED_CHECKIN
+ assertNotNull("check response object is not null after checkout resource", checkoutResource);
+ assertNotNull("check error code exists in response after checkIn resource", checkoutResource.getErrorCode());
+ assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue());
+
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource icon", 409, updatedRestResponse.getErrorCode().intValue());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResourceInformation_resourceVersion_11() throws Exception {
+
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), resourceList, updatedRestResponse.getResponse());
+ // assertEquals("Check response code after updating resource icon", 409,
+ // updatedRestResponse.getErrorCode().intValue());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResourceInformation_resourceVersion_02() throws Exception {
+
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // String resourceCertifyVersion = "0.1";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after updating resource icon", 200, updatedRestResponse.getErrorCode().intValue());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(updatedResourceDetails, getResourceRespJavaObject);
+
+ // delete resource
+ RestResponse response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.1");
+ BaseRestUtils.checkDeleteResponse(response);
+ response = ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.2");
+ BaseRestUtils.checkDeleteResponse(response);
+
+ }
+
+ @Test
+ public void UpdateResourceIcon_resourceVersion_11() throws Exception {
+ // Can be changed only if major version is 0.
+
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // ResourceReqDetails updatedResourceDetails =
+ // defineUpdatedResourse(resourceName);
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+ // updatedResourceDetails.setVendorName("updatedVandorName");
+ updatedResourceDetails.setIcon("updatedIcon");
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_ICON_CANNOT_BE_CHANGED.name(), resourceList, updatedRestResponse.getResponse());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResourceVandorName_resourceVersion_11() throws Exception {
+ // Can be changed only if the major resource version is 0.
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // ResourceReqDetails updatedResourceDetails =
+ // defineUpdatedResourse(resourceName);
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+
+ updatedResourceDetails.setVendorName("updatedVandorName");
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_VENDOR_NAME_CANNOT_BE_CHANGED.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource icon", 400, updatedRestResponse.getErrorCode().intValue());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResourceName_resourceVersion_11() throws Exception {
+ // Can be changed only if the major resource version is 0.
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("create resource failed", 201, restResponse.getErrorCode().intValue());
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ /*
+ * //ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName); ResourceReqDetails updatedResourceDetails = defineResourse();
+ *
+ * updatedResourceDetails.setResourceName("updatedResourceName"); updatedResourceDetails.setIcon("updatedResourceName");
+ */
+ resourceDetails.setName("updatedResourceName");
+ List<String> tagList = new ArrayList<String>();
+ tagList.add(0, "updatedResourceName");
+ resourceDetails.setTags(tagList);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NAME_CANNOT_BE_CHANGED.name(), resourceList, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResourceTag_resourceVersion_11() throws Exception {
+ // Tag Can be updated when major version is 0.
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // ResourceReqDetails updatedResourceDetails =
+ // defineUpdatedResourse(resourceName);
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+ // updatedResourceDetails.setVendorName("updatedVandorName");
+
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("NewTag");
+ resourceTags.add(resourceDetails.getName());
+
+ updatedResourceDetails.setTags(resourceTags);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(updatedResourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateAllowedParames_resourceVersion_11() throws Exception {
+
+ // Tag, contactId, vendorRelease,tags And description - Can be also
+ // updated when major version is NOT 0.
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // ResourceReqDetails updatedResourceDetails =
+ // defineUpdatedResourse(resourceName);
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+ // updatedResourceDetails.setVendorName("updatedVandorName");
+
+ // updated allowed parameters when major resource version is NOT "0"
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add("NewTag");
+ resourceTags.add(resourceDetails.getName());
+ updatedResourceDetails.setTags(resourceTags);
+ updatedResourceDetails.setDescription("UpdatedDescription");
+ updatedResourceDetails.setVendorRelease("5.1");
+ updatedResourceDetails.setContactId("bt750h");
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(updatedResourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateResourceDerivedFrom_resourceVersion_11() throws Exception {
+ // DerivedFrom parameter - Can be updated when major version is 0.
+ User adminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ String resourceBaseVersion = "0.1";
+
+ // create resource
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String resourceName = resourceDetails.getName();
+
+ // resourceUtils.addResourceMandatoryArtifacts(sdncModifierDetails,
+ // restResponse);
+
+ // Certify Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, adminModifierDetails, resourceBaseVersion, LifeCycleStatesEnum.CERTIFY);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ String resourceCertifyVersion = "1.0";
+ logger.debug("Changing resource life cycle ");
+ checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceCertifyVersion, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after checkout resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // ResourceReqDetails updatedResourceDetails =
+ // defineUpdatedResourse(resourceName);
+ ResourceReqDetails updatedResourceDetails = defineResourse();
+ ArrayList<String> drivenFrom = new ArrayList<String>();
+ drivenFrom.add(0, "tosca.nodes.Container.Application");
+ updatedResourceDetails.setDerivedFrom(drivenFrom);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_DERIVED_FROM_CANNOT_BE_CHANGED.name(), resourceList, updatedRestResponse.getResponse());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ }
+
+ @Test
+ public void UpdateResource_vendorNameValidation() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ String updatedVendorName = "";
+ String uniqueId = resourceDetails.getUniqueId();
+ resourceDetails.setVendorName(updatedVendorName);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ // update resource vendorName metadata: 1 characters
+ updatedVendorName = " ";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ // update resource vendorName metadata: 25 characters
+ updatedVendorName = "Verification and validati";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // update resource vendorName metadata: 26 characters
+ updatedVendorName = "Verification and validatii";
+ // set vendorName
+ List<String> myList = new ArrayList<String>();
+ myList.add(0, "25");
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VENDOR_NAME_EXCEEDS_LIMIT.name(), myList, updatedRestResponse.getResponse());
+
+ // update resource VendorRelease metadata: forbidden characters
+ updatedVendorName = "A1<";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1>";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1:";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1\"";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1/";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1\\";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1|";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1?";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorName = "A1*";
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ // update resource vendorName metadata: null
+ updatedVendorName = null;
+ // set vendorName
+ resourceDetails.setVendorName(updatedVendorName);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_NAME.name(), Empty_List, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResource_vendorReleaseValidation() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ RestResponse updatedRestResponse;
+ String uniqueId = resourceDetails.getUniqueId();
+ String updatedVendorRelease;
+ // set VendorRelease
+
+ // update resource VendorRelease metadata: 1 characters
+ updatedVendorRelease = "1";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // update resource VendorRelease metadata: 25 characters
+ updatedVendorRelease = "(!#1.00000000000000000000";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // update resource VendorRelease metadata: 26 characters
+ updatedVendorRelease = "(!#1.000000000000000000005";// set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT.name(), Arrays.asList("" + ValidationUtils.VENDOR_RELEASE_MAX_LENGTH), updatedRestResponse.getResponse());
+
+ // UpdateAndValidate(sdncModifierDetails, resourceDetails,
+ // ActionStatus.VENDOR_RELEASE_EXCEEDS_LIMIT.name(),
+ // Arrays.asList(""+ValidationUtils.VENDOR_RELEASE_MAX_LENGTH));
+
+ // update resource VendorRelease metadata: forbidden characters
+ updatedVendorRelease = "A1<";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1>";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1:";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1\"";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1/";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1\\";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1|";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1?";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ updatedVendorRelease = "A1*";
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ // update resource VendorRelease metadata: null
+ updatedVendorRelease = null;
+ // set VendorRelease
+ resourceDetails.setVendorRelease(updatedVendorRelease);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_VENDOR_RELEASE.name(), Empty_List, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResource_contactIdValidation() throws Exception { // [a-zA-Z]{2}[0-9]{3}[a-zA-Z0-9]{1}
+ // (6
+ // characters
+ // now,
+ // may
+ // be
+ // expanded
+ // up
+ // to
+ // 8
+ // characters
+ // in
+ // the
+ // future).
+ // Convert
+ // Upper
+ // case
+ // character
+ // to
+ // lower
+ // case
+ RestResponse updatedRestResponse;
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ String uniqueId = resourceDetails.getUniqueId();
+
+ List<String> myList = new ArrayList<String>();
+ myList.add(0, "Resource");
+ String updatedContactId = "";
+ resourceDetails.setContactId(updatedContactId);
+
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "ab12345";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = " ";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "ab 50h";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "ab123c";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ updatedContactId = "cd789E";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ // contactId norm
+ resourceDetails.setContactId(updatedContactId.toLowerCase());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ updatedContactId = "ef4567";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ updatedContactId = "AA012A";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ // contactId norm
+ resourceDetails.setContactId(updatedContactId.toLowerCase());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ updatedContactId = "CD012c";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ // contactId norm
+ resourceDetails.setContactId(updatedContactId.toLowerCase());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ updatedContactId = "EF0123";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ // contactId norm
+ resourceDetails.setContactId(updatedContactId.toLowerCase());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ ////////////////////////////// **************//////////////////////////////
+ List<String> resource = Arrays.asList("Resource");
+ updatedContactId = "01345a";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "0y000B";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "Y1000b";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "abxyzC";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "cdXYZc";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "efXY1D";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "EFabcD";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "EFABCD";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "EFABC1";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "efui1D";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "efui1!";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "ef555!";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = ",f555";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ updatedContactId = "EF55.5";
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ // update resource contactId metadata: extended character set (128–255)
+ resourceDetails.setContactId(extendedCharsStringBuilder());
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ // update resource contactId metadata: null
+ updatedContactId = null;
+ resourceDetails.setContactId(updatedContactId);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CONTACT.name(), myList, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResource_TagsFieldValidation() throws Exception {
+ RestResponse updatedRestResponse;
+ // define and create resource
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ String uniqueId = resourceDetails.getUniqueId();
+
+ String updatedTagField = "";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(updatedTagField);
+ // set description
+ resourceDetails.setTags(resourceTags);
+ List<String> variables = Arrays.asList("Resource", "tag");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, updatedRestResponse.getResponse());
+
+ // update resource tags metadata: empty
+ resourceTags = new ArrayList<String>();
+ // set Tags
+ resourceDetails.setTags(resourceTags);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_TAGS.name(), Empty_List, updatedRestResponse.getResponse());
+
+ // update resource description metadata: 1 characters
+ updatedTagField = "A";
+ resourceTags = new ArrayList<String>();
+ resourceTags.add(updatedTagField);
+ resourceTags.add(resourceDetails.getName());
+ // set description
+ resourceDetails.setTags(resourceTags);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // OK - tag up to 50 chars
+ updatedTagField = "The Indian-crested.porcupine_The Indian cresteddds";
+ resourceTags.add(updatedTagField);
+ resourceDetails.setTags(resourceTags);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // OK - sum is 1024, 50x20+48+20(commas)+6(cisco4 - resource name)
+ String updatedTagField1 = "The Indian-crested.porcupine_The Indian crestedd01";
+ String updatedTagField2 = "The Indian-crested.porcupine_The Indian crestedd02";
+ String updatedTagField3 = "The Indian-crested.porcupine_The Indian crestedd03";
+ String updatedTagField4 = "The Indian-crested.porcupine_The Indian crestedd04";
+ String updatedTagField5 = "The Indian-crested.porcupine_The Indian crestedd05";
+ String updatedTagField6 = "The Indian-crested.porcupine_The Indian crestedd06";
+ String updatedTagField7 = "The Indian-crested.porcupine_The Indian crestedd07";
+ String updatedTagField8 = "The Indian-crested.porcupine_The Indian crestedd08";
+ String updatedTagField9 = "The Indian-crested.porcupine_The Indian crestedd09";
+ String updatedTagField10 = "The Indian-crested.porcupine_The Indian crestedd10";
+ String updatedTagField11 = "The Indian-crested.porcupine_The Indian crestedd11";
+ String updatedTagField12 = "The Indian-crested.porcupine_The Indian crestedd12";
+ String updatedTagField13 = "The Indian-crested.porcupine_The Indian crestedd13";
+ String updatedTagField14 = "The Indian-crested.porcupine_The Indian crestedd14";
+ String updatedTagField15 = "The Indian-crested.porcupine_The Indian crestedd15";
+ String updatedTagField16 = "The Indian-crested.porcupine_The Indian crestedd16";
+ String updatedTagField17 = "The Indian-crested.porcupine_The Indian crestedd17";
+ String updatedTagField18 = "The Indian-crested.porcupine_The Indian crestedd18";
+ String updatedTagField19 = "The Indian-crested.porcupine_The Indian crestaa";
+
+ resourceTags = new ArrayList<String>();
+ resourceTags.add(updatedTagField);
+ resourceTags.add(updatedTagField1);
+ resourceTags.add(updatedTagField2);
+ resourceTags.add(updatedTagField3);
+ resourceTags.add(updatedTagField4);
+ resourceTags.add(updatedTagField5);
+ resourceTags.add(updatedTagField6);
+ resourceTags.add(updatedTagField7);
+ resourceTags.add(updatedTagField8);
+ resourceTags.add(updatedTagField9);
+ resourceTags.add(updatedTagField10);
+ resourceTags.add(updatedTagField11);
+ resourceTags.add(updatedTagField12);
+ resourceTags.add(updatedTagField13);
+ resourceTags.add(updatedTagField14);
+ resourceTags.add(updatedTagField15);
+ resourceTags.add(updatedTagField16);
+ resourceTags.add(updatedTagField17);
+ resourceTags.add(updatedTagField18);
+ resourceTags.add(updatedTagField19);
+ resourceTags.add(resourceDetails.getName());
+ // set description
+ resourceDetails.setTags(resourceTags);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // Add another tag-exceeds limit
+ resourceTags.add("d");
+ resourceDetails.setTags(resourceTags);
+ ArrayList<String> myArray = new ArrayList<String>();
+ myArray.add(0, "1024");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_TAGS_EXCEED_LIMIT.name(), myArray, updatedRestResponse.getResponse());
+
+ // Tag exceeds limit - 51
+ resourceTags = new ArrayList<String>();
+ updatedTagField = "The Indian-crested.porcupine_The Indian crestedddsw";
+ resourceTags.add(updatedTagField);
+ resourceTags.add(resourceDetails.getName());
+ // set description
+ resourceDetails.setTags(resourceTags);
+ myArray.remove(0);
+ myArray.add(0, "50");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), myArray, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResource_DesriptionFieldValidation() throws Exception {
+ // define and create resource
+ RestResponse updatedRestResponse;
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ String uniqueId = resourceDetails.getUniqueId();
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ List<String> resource = new ArrayList<>();
+ resource.add("Resource");
+ // update resource description metadata: 0 characters
+ String updatedDescription = "";
+ // set description
+ resourceDetails.setDescription(updatedDescription);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource, updatedRestResponse.getResponse());
+
+ // update resource description metadata: null
+ updatedDescription = null;
+ // set description
+ resourceDetails.setDescription(updatedDescription);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), resource, updatedRestResponse.getResponse());
+
+ // update resource description metadata: 1 characters
+ updatedDescription = "A";
+ // set description
+ resourceDetails.setDescription(updatedDescription);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // update resource description metadata: 1024 characters
+ updatedDescription = "The Indian crested porcupine *{Hystrix indica}*, or Indian porcupine is a member of the Old World porcupines." + "It is quite an adaptable rodent, found throughout southern Asia and the Middle East."
+ + "It is tolerant of several different habitats: mountains, tropical and subtropical grasslands, scrublands, and forests."
+ + "It is a large rodent, growing more than 0.9 m = (3 ft) long and weighing 14.5 kg = (32 lb)! [citation needed] It is covered in multiple layers of quills."
+ + "The longest quills grow from its shoulders to about a third of the animal's length." + "Its tail is covered in short, hollow quills that can rattle when threatened."
+ + "It has broad feet and long claws for digging. When attacked, the Indian crested porcupine raises its quills and rattles the hollow quills on its tail."
+ + "If the predator persists past these threats, the porcupine launches a backwards assault, hoping to stab its attacker with its quills."
+ + "It does this so effectively that most brushes between predators and the Indian porcupine end in death or severe injury";
+ // set description
+ resourceDetails.setDescription(updatedDescription);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ parseResponseAndValidate(resourceDetails, updatedRestResponse);
+
+ // update resource description metadata: 1025 characters
+ updatedDescription = "The Indian crested porcupine *{Hystrix indica}*, or Indian porcupine is a member of the Old World porcupines." + "It is quite an adaptable rodent, found throughout southern Asia and the Middle East."
+ + "It is tolerant of several different habitats: mountains, tropical and subtropical grasslands, scrublands, and forests."
+ + "It is a large rodent, growing more than 0.9 m = (3 ft) long and weighing 14.5 kg = (32 lb)! [citation needed] It is covered in multiple layers of quills."
+ + "The longest quills grow from its shoulders to about a third of the animal's length." + "Its tail is covered in short, hollow quills that can rattle when threatened."
+ + "It has broad feet and long claws for digging. When attacked, the Indian crested porcupine raises its quills and rattles the hollow quills on its tail."
+ + "If the predator persists past these threats, the porcupine launches a backwards assault, hoping to stab its attacker with its quills."
+ + "It does this so effectively that most brushes between predators and the Indian porcupine end in death or severe injury.";
+ // set description
+ resourceDetails.setDescription(updatedDescription);
+ resource.add(1, "1024");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, uniqueId, "");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT.name(), resource, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResource_TagsFormatValidation() throws Exception {
+ char[] notValidCharsArray = getTagInValidFormatChars();
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check recourse created ", 201, restResponse.getErrorCode().intValue());
+ String resourceName = resourceDetails.getName();
+
+ // update tag details
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ ArrayList<String> resourceTags = new ArrayList<String>();
+
+ String updatedTagField;
+ RestResponse updatedRestResponse;
+ List<String> variables = Arrays.asList("Resource", "tag");
+
+ for (int i = 0; i < notValidCharsArray.length; i++) {
+ updatedTagField = "UpdatedTag" + notValidCharsArray[i];
+ resourceTags = new ArrayList<String>();
+ resourceTags.add(updatedTagField);
+ resourceTags.add(resourceDetails.getName());
+ // set description
+ updatedResourceDetails.setTags(resourceTags);
+
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource icon", 400, updatedRestResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating resource icon", "Bad Request", updatedRestResponse.getResponseMessage().toString());
+
+ }
+
+ }
+
+ @Test
+ public void UpdateResourceCategory_negativeFlow() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after update resource", 201, restResponse.getErrorCode().intValue());
+ Resource resourceBeforeUpdate = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ String uniqueID = resourceDetails.getUniqueId();
+
+ // Update resource Category Successfully
+ ResourceReqDetails updatedResourceDetails = resourceDetails;
+
+ updatedResourceDetails.removeAllCategories();
+ updatedResourceDetails.addCategoryChain(ServiceCategoriesEnum.MOBILITY.getValue(), ResourceCategoryEnum.APPLICATION_L4_DATABASE.getSubCategory());
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+
+ // validate response
+ List<String> resourceList = new ArrayList<String>();
+ resourceList.add(0, "Resource");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CATEGORY.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue());
+
+ // Updating resource category
+ updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate);
+ updatedResourceDetails.addCategory("");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ resourceList = new ArrayList<String>();
+ resourceList.add(0, "Resource");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue());
+
+ // Updating resource category
+ updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate);
+ updatedResourceDetails.addCategory("XXXXXX");
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // validate response
+ resourceList = new ArrayList<String>();
+ resourceList.add(0, "Resource");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_CATEGORY.name(), resourceList, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource", 400, updatedRestResponse.getErrorCode().intValue());
+
+ // CheckIn Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkoutResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN); // NOT_CERTIFIED_CHECKIN
+ assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue());
+
+ // Update resource Category
+ updatedResourceDetails = defineUpdateResourceWithNonUpdatableFields(resourceBeforeUpdate);
+ updatedResourceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue());
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+ // verify response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), Empty_List, updatedRestResponse.getResponse());
+ assertEquals("Check response code after updating resource", 409, updatedRestResponse.getErrorCode().intValue());
+
+ // CheckIn Resource
+ logger.debug("Changing resource life cycle ");
+ RestResponse checkinResource = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT); // NOT_CERTIFIED_CHECKIN
+ assertNotNull("check response object is not null after checkout resource", checkoutResource);
+ assertNotNull("check error code exists in response after checkIn resource", checkoutResource.getErrorCode());
+ assertEquals("Check response code after checkin resource", 200, checkoutResource.getErrorCode().intValue());
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, uniqueID);
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(resourceDetails, getRestResponse);
+
+ }
+
+ @Test
+ public void UpdateResourceCategorySuccessfully() throws Exception {
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after update resource", 201, restResponse.getErrorCode().intValue());
+ Resource resourceBeforeUpdate = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ // Update resource Category Successfully
+ ResourceReqDetails updatedResourceDetails = resourceDetails;
+
+ updatedResourceDetails.removeAllCategories();
+ updatedResourceDetails.addCategoryChain(ResourceCategoryEnum.APPLICATION_L4_DATABASE.getCategory(), ResourceCategoryEnum.APPLICATION_L4_DATABASE.getSubCategory());
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, resourceDetails.getUniqueId(), "");
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, updatedRestResponse.getErrorCode().intValue());
+ // parseResponseAndValidateNonUpdatable(updatedResourceDetails,
+ // updatedRestResponse);
+ parseResponseAndValidate(updatedResourceDetails, updatedRestResponse);
+
+ // validate category updated
+ assertTrue(updatedResourceDetails.getCategories().get(0).getName().equals(ResourceCategoryEnum.APPLICATION_L4_DATABASE.getCategory()));
+
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceDetails.getUniqueId());
+ assertNotNull("check response object is not null after update resource", getRestResponse);
+ parseResponseAndValidate(updatedResourceDetails, getRestResponse);
+
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncModifierDetails, updatedResourceDetails.getName(), "0.1");
+ }
+
+ // Benny
+
+ @Test
+ public void Validation_UpdateIcon() throws Exception {
+ // Fields to update (Forbidden)
+ String _updatedIcon = "mySecondIcon.Jpg";
+
+ // administrator permissions
+ User sdncAdminModifierDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // define and create resource
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, resourceDetails.getName(), "0.1");
+
+ RestResponse restResponse = createResource(sdncAdminModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ String resourceName = resourceDetails.getName();
+
+ // update metadata details
+ ResourceReqDetails updatedResourceDetails = defineUpdatedResourse(resourceName);
+ // change icon of metadata
+ updatedResourceDetails.setIcon(_updatedIcon);
+ // PUT request
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, resourceDetails.getUniqueId(), "");
+
+ // validate response
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_INVALID_ICON.name(), Arrays.asList("Resource"), updatedRestResponse.getResponse());
+
+ // empty icon
+ _updatedIcon = "";
+ updatedResourceDetails.setIcon(_updatedIcon);
+ updatedRestResponse = ResourceRestUtils.updateResourceMetadata(updatedResourceDetails, sdncAdminModifierDetails, resourceDetails.getUniqueId(), "");
+ assertNotNull("check response object is not null after update resource", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_ICON.name(), Arrays.asList("Resource"), updatedRestResponse.getResponse());
+
+ // get resource with original name. original metadata should be returned
+ RestResponse getRestResponse = ResourceRestUtils.getResource(sdncAdminModifierDetails, resourceDetails.getUniqueId());
+ // validate response
+ assertNotNull("check response object is not null after get resource", getRestResponse);
+ assertNotNull("check error code exists in response after get resource", getRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", 200, getRestResponse.getErrorCode().intValue());
+
+ // parse updated response to javaObject
+ Resource getResourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(getRestResponse.getResponse());
+ // validate that metadata was not changed
+ ResourceValidationUtils.validateResourceReqVsResp(resourceDetails, getResourceRespJavaObject);
+
+ ResourceRestUtils.deleteResourceByNameAndVersion(sdncAdminModifierDetails, updatedResourceDetails.getName(), "0.1");
+
+ }
+
+ @Test
+ public void UpdateResourceTypeSuccess() throws Exception {
+ // LCS is CheckOut
+ String newResourceType = ResourceTypeEnum.VL.toString();
+ String currentResourceType = resourceDetails.getResourceType();
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ resourceDetails.setResourceType(newResourceType);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+ assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue());
+ Resource updatedResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(updatedRestResponse.getResponse());
+ // assertTrue("Check resource type after update resource",
+ // updatedResourceJavaObject.getResourceType().toString().equals(resourceType));
+ assertTrue("Check resource type after update resource", updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType));
+
+ }
+
+ @Test
+ public void UpdateResourceTypeAndNameSuccess() throws Exception {
+ // LCS is CheckOut
+ String newResourceType = ResourceTypeEnum.VL.toString();
+ String currentResourceType = resourceDetails.getResourceType();
+ String newResourceName = "new Name";
+
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ resourceDetails.setResourceType(newResourceType);
+ resourceDetails.setName(newResourceName);
+ List<String> tags = resourceDetails.getTags();
+ tags.add(newResourceName);
+ resourceDetails.setTags(tags);
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+ assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue());
+ Resource updatedResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(updatedRestResponse.getResponse());
+ assertTrue("Check resource type after update resource", updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType));
+ assertTrue("Check resource name after update resource", updatedResourceJavaObject.getName().equals(newResourceName));
+
+ }
+
+ @Test
+ public void UpdateResourceTypeAfterResourceCertification() throws Exception {
+
+ String newResourceType = ResourceTypeEnum.VF.toString();
+ String currentResourceType = resourceDetails.getResourceType();
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ resourceDetails.setResourceType(newResourceType);
+ restResponse = LifecycleRestUtils.certifyResource(resourceDetails);
+ assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue());
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue());
+ currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+ assertEquals("Check response code after create resource", 200, updatedRestResponse.getErrorCode().intValue());
+ Resource updatedResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(updatedRestResponse.getResponse());
+ // assertTrue("Check resource type after update resource",
+ // updatedResourceJavaObject.getResourceType().toString().equals(newResourceType));
+ assertTrue("Check resource type after update resource", updatedResourceJavaObject.getResourceType().toString().equals(currentResourceType));
+
+ }
+
+ @Test
+ public void UpdateResourceTypeCheckInLCS() throws Exception {
+
+ String resourceType = ResourceTypeEnum.VL.toString();
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ resourceDetails.setResourceType(resourceType);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum.CHECKIN);
+ assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue());
+
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+
+ assertNotNull("check response object is not null after create resouce", updatedRestResponse);
+ assertNotNull("check error code exists in response after create resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), updatedRestResponse.getErrorCode());
+
+ List<String> variables = new ArrayList<>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResourceTypeCertifiedLCS() throws Exception {
+
+ String resourceType = ResourceTypeEnum.VL.toString();
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ restResponse = LifecycleRestUtils.certifyResource(resourceDetails);
+ assertEquals("Check response code after resource CheckIn", 200, restResponse.getErrorCode().intValue());
+
+ resourceDetails.setResourceType(resourceType);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+
+ assertNotNull("check response object is not null after create resouce", updatedRestResponse);
+ assertNotNull("check error code exists in response after create resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), updatedRestResponse.getErrorCode());
+
+ List<String> variables = new ArrayList<>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables, updatedRestResponse.getResponse());
+
+ }
+
+ @Test
+ public void UpdateResourceTypeInvalidType() throws Exception {
+
+ String resourceType = "INVALID TYPE";
+ RestResponse restResponse = createResource(sdncModifierDetails, resourceDetails);
+ assertEquals("Check response code after create resource", 201, restResponse.getErrorCode().intValue());
+ Resource currentResourceJavaObject = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ resourceDetails.setResourceType(resourceType);
+ RestResponse updatedRestResponse = ResourceRestUtils.updateResourceMetadata(resourceDetails, sdncModifierDetails, currentResourceJavaObject.getUniqueId(), "");
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_CONTENT.name());
+
+ assertNotNull("check response object is not null after update resouce", updatedRestResponse);
+ assertNotNull("check error code exists in response after update resource", updatedRestResponse.getErrorCode());
+ assertEquals("Check response code after update resource", errorInfo.getCode(), updatedRestResponse.getErrorCode());
+
+ List<String> variables = new ArrayList<>();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), variables, updatedRestResponse.getResponse());
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java
new file mode 100644
index 0000000000..895390f764
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VFResourceInstanceNameCRUD.java
@@ -0,0 +1,480 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+import fj.data.Either;
+
+public class VFResourceInstanceNameCRUD extends ComponentBaseTest {
+
+ protected static ServiceReqDetails serviceDetails;
+ protected static ResourceReqDetails resourceDetailsVFC;
+ protected static ResourceReqDetails resourceDetailsVL;
+ protected static ResourceReqDetails resourceDetailsVF;
+ protected static ResourceReqDetails resourceDetailsCP;
+ protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVF;
+ protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVFC;
+ protected static ComponentInstanceReqDetails resourceInstanceReqDetailsVL;
+ protected static ComponentInstanceReqDetails resourceInstanceReqDetailsCP;
+ protected static User sdncDesignerDetails1;
+ protected static User sdncTesterDeatails1;
+ protected static User sdncAdminDetails1;
+ protected static ArtifactReqDetails heatArtifactDetails;
+ protected static ArtifactReqDetails defaultArtifactDetails;
+ protected static int maxLength = 50;
+ protected static Resource resourceVF = null;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public VFResourceInstanceNameCRUD() {
+ super(name, VFResourceInstanceNameCRUD.class.getName());
+ }
+
+ @BeforeMethod
+
+ public void init() throws Exception {
+
+ // serviceDetails = ElementFactory.getDefaultService();
+ // resourceDetailsVFC =
+ // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC.toString(),
+ // "resourceVFC");
+ // resourceDetailsVF =
+ // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF.toString(),
+ // "resourceVF3");
+ // resourceDetailsVL =
+ // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VL.toString(),
+ // "resourceVL");
+ // resourceDetailsCP =
+ // ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CP.toString(),
+ // "resourceCP");
+ sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // heatArtifactDetails =
+ // ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+
+ Either<Resource, RestResponse> resourceDetailsCP_01e = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsCP_01e.left().value(), UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CHECKIN, true);
+ resourceDetailsCP = new ResourceReqDetails(resourceDetailsCP_01e.left().value());
+ Either<Resource, RestResponse> resourceDetailsVL_01e = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VL, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVL_01e.left().value(), UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CHECKIN, true);
+ resourceDetailsVL = new ResourceReqDetails(resourceDetailsVL_01e.left().value());
+ Either<Resource, RestResponse> resourceDetailsVF_01e = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF = new ResourceReqDetails(resourceDetailsVF_01e.left().value());
+ Either<Resource, RestResponse> resourceDetailsVFC_01e = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFC_01e.left().value(), UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CHECKIN, true);
+ resourceDetailsVFC = new ResourceReqDetails(resourceDetailsVFC_01e.left().value());
+
+ resourceInstanceReqDetailsVFC = ElementFactory.getDefaultComponentInstance("VFC", resourceDetailsVFC);
+ resourceInstanceReqDetailsVF = ElementFactory.getDefaultComponentInstance("VF", resourceDetailsVF);
+ resourceInstanceReqDetailsVL = ElementFactory.getDefaultComponentInstance("VL", resourceDetailsVL);
+ resourceInstanceReqDetailsCP = ElementFactory.getDefaultComponentInstance("CP", resourceDetailsCP);
+ sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ }
+
+ @Test
+ public void addResourceInstanceToVF() throws Exception {
+
+ createVFWithCertifiedResourceInstance(resourceDetailsCP, resourceInstanceReqDetailsCP);
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 1");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void updateResourceInstanceName() throws Exception {
+
+ // update resource instance name
+ String resourceInstanceUpdatedName = "resource New 2";
+
+ ResourceReqDetails updatedResourceDetailsVLC = changeResouceName(resourceDetailsVFC,
+ resourceInstanceUpdatedName);
+ createVFWithCertifiedResourceInstance(updatedResourceDetailsVLC, resourceInstanceReqDetailsVFC);
+
+ resourceInstanceReqDetailsVFC.setName(resourceInstanceUpdatedName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetailsVFC, sdncDesignerDetails1, resourceVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertTrue(updateResourceInstanceResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceUpdatedName);
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void updateResourceInstanceNameToNextGeneratedName() throws Exception {
+
+ // update resource instance name
+ String resourceInstanceUpdatedName = resourceInstanceReqDetailsCP.getName() + " 2";
+
+ ResourceReqDetails updatedResourceDetailsVL = changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName);
+ createVFWithCertifiedResourceInstance(updatedResourceDetailsVL, resourceInstanceReqDetailsVL);
+ resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName);
+
+ // add second resource instance
+ RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP,
+ sdncDesignerDetails1, resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1");
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void normolizeUpdatedResourceInstanceName() throws Exception {
+
+ String resourceInstanceUpdatedName = "resource new - .2";
+ String normalizedName = "resourcenew2";
+
+ ResourceReqDetails updatedResourceDetailsVL = changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName);
+
+ createVFWithCertifiedResourceInstance(updatedResourceDetailsVL, resourceInstanceReqDetailsVL);
+ // update resource instance name
+ resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName);
+
+ // add second resource instance
+ RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP,
+ sdncDesignerDetails1, resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1");
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void updatedResourceInstanceNameToEmpty() throws Exception {
+
+ createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL);
+ String resourceInstanceUpdatedName = "";
+ String resourceInstancePreviousName = resourceDetailsCP.getName();
+
+ // add second resource instance
+ RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP,
+ sdncDesignerDetails1, resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code after RI update request", 200,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ // change request
+ // ErrorInfo errorInfo =
+ // Utils.parseYaml(ActionStatus.MISSING_COMPONENT_NAME.name());
+ // utils.validateResponseCode(updateResourceInstanceResponse,
+ // errorInfo.getCode(), "update resource instance");
+ //
+ // List<String> variables = Arrays.asList("Resource Instance");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_COMPONENT_NAME.name(),
+ // variables, updateResourceInstanceResponse.getResponse());
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1");
+ resourceInstanceExpectedListName.add(resourceInstancePreviousName + " 3");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void updatedResourceNameLengthExceedMaximumCharacters() throws Exception {
+
+ String resourceInstancePreviousName = resourceDetailsCP.getName();
+ // update resource instance name
+ String resourceInstanceUpdatedName = "a";
+ for (int i = 0; i < maxLength; i++) {
+ resourceInstanceUpdatedName += "b";
+ }
+ // ResourceReqDetails updatedResourceDetailsVL =
+ // changeResouceName(resourceDetailsVL, resourceInstanceUpdatedName);
+
+ createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL);
+ // add second resource instance
+ RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP,
+ sdncDesignerDetails1, resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ String prevName = resourceInstanceReqDetailsCP.getName();
+ resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name());
+ // utils.validateResponseCode(updateResourceInstanceResponse,
+ // errorInfo.getCode(), "update resource instance");
+
+ List<String> variables = Arrays.asList("Resource Instance", "50");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT.name(), variables,
+ updateResourceInstanceResponse.getResponse());
+
+ resourceInstanceReqDetailsCP.setName(prevName);
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1");
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ @Test
+ public void updatedResourceNameWithUnSupportedCharacters() throws Exception {
+
+ createVFWithCertifiedResourceInstance(resourceDetailsVL, resourceInstanceReqDetailsVL);
+ String resourceInstancePreviousName = resourceDetailsCP.getName();
+ // update resource instance name
+ String resourceInstanceUpdatedName = "a???<>";
+
+ // add second resource instance
+ RestResponse response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetailsCP,
+ sdncDesignerDetails1, resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ String prevValue = resourceInstanceReqDetailsCP.getName();
+ resourceInstanceReqDetailsCP.setName(resourceInstanceUpdatedName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails1, resourceVF.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_COMPONENT_NAME.name());
+ // ResourceRestUtils.validateResponseCode(updateResourceInstanceResponse,
+ // errorInfo.getCode(), "update resource instance");
+
+ List<String> variables = Arrays.asList("Resource Instance");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_COMPONENT_NAME.name(), variables,
+ updateResourceInstanceResponse.getResponse());
+
+ resourceInstanceReqDetailsCP.setName(prevValue);
+
+ // validate RI name
+ List<ComponentInstance> resourceInstances = resourceVF.getComponentInstances();
+ List<String> resourceInstanceListName = new ArrayList<String>();
+ for (int i = 0; i < resourceInstances.size(); i++) {
+ resourceInstanceListName.add(resourceInstances.get(i).getName());
+ }
+ List<String> resourceInstanceExpectedListName = new ArrayList<String>();
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsVL.getName() + " 1");
+ resourceInstanceExpectedListName.add(resourceInstanceReqDetailsCP.getName() + " 2");
+ String message = "resource instance name";
+ Utils.compareArrayLists(resourceInstanceListName, resourceInstanceExpectedListName, message);
+
+ }
+
+ private static ResourceReqDetails changeResouceName(ResourceReqDetails resourceDet,
+ String resourceInstanceUpdatedName) throws Exception {
+
+ ResourceReqDetails updatedResourceDetails = new ResourceReqDetails();
+ updatedResourceDetails = resourceDet;
+ updatedResourceDetails.setName(resourceInstanceUpdatedName);
+ List<String> tags = new ArrayList<String>();
+ tags.add(resourceInstanceUpdatedName);
+ updatedResourceDetails.setTags(tags);
+ Gson gson = new Gson();
+ String updatedResourceBodyJson = gson.toJson(updatedResourceDetails);
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDet, sdncDesignerDetails1,
+ resourceDet.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertTrue("change LS state to CHECKOUT, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ response = ResourceRestUtils.updateResourceMetadata(updatedResourceBodyJson, sdncDesignerDetails1,
+ updatedResourceDetails.getUniqueId());
+ assertEquals("Check response code after updateresource name", 200, response.getErrorCode().intValue());
+ response = LifecycleRestUtils.changeResourceState(updatedResourceDetails, sdncDesignerDetails1,
+ resourceDet.getVersion(), LifeCycleStatesEnum.CHECKIN);
+
+ return updatedResourceDetails;
+
+ }
+
+ // private Component changeResouceName(Resource resourceDet, String
+ // resourceInstanceUpdatedName) throws Exception{
+ //
+ // User defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // Resource updatedResourceDetails = resourceDet;
+ // RestResponse response =
+ // LifecycleRestUtils.changeComponentState(updatedResourceDetails,
+ // defaultUser, LifeCycleStatesEnum.CHECKOUT, "state changed");
+ // assertTrue("change LS state to CHECKOUT, returned status:" +
+ // response.getErrorCode(),response.getErrorCode() == 200);
+ // updatedResourceDetails.setName(resourceInstanceUpdatedName);
+ // List<String> tags = new ArrayList<String>();
+ // tags.add(resourceInstanceUpdatedName);
+ // updatedResourceDetails.setTags(tags);
+ // Gson gson = new Gson();
+ // ResourceReqDetails resourceReqDetails = new
+ // ResourceReqDetails(updatedResourceDetails);
+ // String updatedResourceBodyJson = gson.toJson(resourceReqDetails);
+ // response = ResourceRestUtils.updateResource(updatedResourceBodyJson,
+ // defaultUser, updatedResourceDetails.getUniqueId());
+ // assertEquals("Check response code after updateresource name", 200,
+ // response.getErrorCode().intValue());
+ // response =
+ // LifecycleRestUtils.changeComponentState(updatedResourceDetails,
+ // defaultUser, LifeCycleStatesEnum.CHECKIN, "state changed");
+ // assertEquals("Check response code after updateresource name", 200,
+ // response.getErrorCode().intValue());
+ //
+ // return updatedResourceDetails;
+ //
+ // }
+
+ private void createVFWithCertifiedResourceInstance(ResourceReqDetails resourceDetails,
+ ComponentInstanceReqDetails resourceInstanceReqDetails) throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after CHECKOUT", 200, response.getErrorCode().intValue());
+
+ // add heat artifact to resource and certify
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1,
+ resourceDetails.getUniqueId());
+ assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ response = LifecycleRestUtils.certifyResource(resourceDetails);
+ assertEquals("Check response code after CERTIFY request", 200, response.getErrorCode().intValue());
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerDetails1,
+ resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+ }
+
+ protected Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException {
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1);
+ assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue());
+ return ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java
new file mode 100644
index 0000000000..37e7539fd9
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/ValidateExtendedVfData.java
@@ -0,0 +1,315 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.List;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import fj.data.Either;
+
+public class ValidateExtendedVfData extends ComponentBaseTest {
+
+ protected Resource resourceDetailsVF;
+ protected Resource resourceDetailsCP_01;
+ protected Resource resourceDetailsVL_01;
+ protected Resource resourceDetailsVFCcomp;
+
+ protected User sdncUserDetails;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ValidateExtendedVfData() {
+ super(name, ValidateExtendedVfData.class.getName());
+ }
+
+ @BeforeMethod
+ public void create() throws Exception {
+
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ Either<Resource, RestResponse> resourceDetailsVFe = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF = resourceDetailsVFe.left().value();
+ Either<Resource, RestResponse> resourceDetailsCP_01e = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT,
+ ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsCP_01 = resourceDetailsCP_01e.left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsCP_01, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsCP_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsCP_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsCP_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsCP_01, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+ Either<Resource, RestResponse> resourceDetailsVL_01e = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK,
+ ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVL_01 = resourceDetailsVL_01e.left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVL_01, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVL_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVL_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsVL_01,
+ UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVL_01, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVL_01, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+
+ Either<Resource, RestResponse> resourceDetailsVFCcompE = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVFCcomp = resourceDetailsVFCcompE.left().value();
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+
+ ComponentInstance resourceDetailsCP_01ins = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceDetailsCP_01, resourceDetailsVF,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+ ComponentInstance resourceDetailsVL_01ins = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceDetailsVL_01, resourceDetailsVF,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+ ComponentInstance resourceDetailsVFCcomp_ins = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, resourceDetailsVF,
+ UserRoleEnum.DESIGNER, true)
+ .left().value();
+
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF, resourceDetailsCP_01ins,
+ resourceDetailsVL_01ins, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF, resourceDetailsCP_01ins,
+ resourceDetailsVFCcomp_ins, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+
+ }
+
+ @Test
+ public void getResourceLatestVersion() throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ // resourceDetailsVF =
+ // AtomicOperationUtils.getResourceObject(resourceDetailsVF,
+ // UserRoleEnum.DESIGNER);
+ RestResponse getResourceLatestVersionResponse = ResourceRestUtils.getResourceLatestVersionList(sdncUserDetails);
+ assertTrue("response code is not 200, returned :" + getResourceLatestVersionResponse.getErrorCode(),
+ getResourceLatestVersionResponse.getErrorCode() == 200);
+
+ List<Resource> resourceList = ResourceRestUtils
+ .restResponseToResourceObjectList(getResourceLatestVersionResponse.getResponse());
+ Resource resource = ResourceRestUtils.getResourceObjectFromResourceListByUid(resourceList,
+ resourceDetailsVF.getUniqueId());
+
+ callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void getFollowedResources() throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ // resourceDetailsVF =
+ // AtomicOperationUtils.getResourceObject(resourceDetailsVF,
+ // UserRoleEnum.DESIGNER);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ RestResponse getFollowedResourcesResponse = ResourceRestUtils.getFollowedList(sdncUserDetails);
+ String json = getFollowedResourcesResponse.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get("resources");
+
+ List<Resource> resourceList = ResourceRestUtils.restResponseToResourceObjectList(resources.toString());
+ Resource resource = ResourceRestUtils.getResourceObjectFromResourceListByUid(resourceList,
+ resourceDetailsVF.getUniqueId());
+ // TODO if get followed list Api should return full object data?
+ // callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void lifeCycleChekInRequest() throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ // resourceDetailsVF =
+ // AtomicOperationUtils.getResourceObject(resourceDetailsVF,
+ // UserRoleEnum.DESIGNER);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void lifeCycleChekOutRequest() throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertTrue("change LC state to CHECKOUT, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void lifeCycleRequestForCertification() throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LC state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ response = LifecycleRestUtils.changeComponentState(resourceDetailsVF, sdncUserDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertTrue("change LC state to CERTIFICATIONREQUEST, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void lifeCycleCertificationRequest() throws Exception {
+
+ RestResponse response = AtomicOperationUtils
+ .changeComponentState(resourceDetailsVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, false)
+ .getRight();
+ assertTrue("change LC state to CERTIFY, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ callAllCheckMethods(resource);
+ }
+
+ @Test
+ public void checkGetResourceAfterCertificationRequest() throws Exception {
+
+ RestResponse response = AtomicOperationUtils
+ .changeComponentState(resourceDetailsVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, false)
+ .getRight();
+ assertTrue("change LC state to CERTIFY, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ resourceDetailsVF = AtomicOperationUtils.getResourceObject(resourceDetailsVF, UserRoleEnum.DESIGNER);
+
+ callAllCheckMethods(resourceDetailsVF);
+ }
+
+ @Test
+ public void updateResourceMetadata() throws Exception {
+
+ resourceDetailsVF.setDescription("stamStam");
+ ResourceReqDetails resourceDetailsVFreqD = new ResourceReqDetails(resourceDetailsVF);
+ RestResponse updateResourceResponse = ResourceRestUtils.updateResourceMetadata(resourceDetailsVFreqD,
+ sdncUserDetails, resourceDetailsVF.getUniqueId());
+ assertTrue("response code is not 200, returned :" + updateResourceResponse.getErrorCode(),
+ updateResourceResponse.getErrorCode() == 200);
+
+ Resource resource = ResponseParser.convertResourceResponseToJavaObject(updateResourceResponse.getResponse());
+
+ callAllCheckMethods(resource);
+ }
+
+ private void checkResourceInstances(Resource resource) {
+ assertNotNull("resource component Instances list is null ", resource.getComponentInstances());
+ assertTrue("resource component Instances list is empty ", !resource.getComponentInstances().equals(""));
+ }
+
+ private void checkResourceInstancesProperties(Resource resource) {
+ assertNotNull("component Instances properies list is null ", resource.getComponentInstancesProperties());
+ assertTrue("component Instances properies list is empty ",
+ !resource.getComponentInstancesProperties().equals(""));
+ }
+
+ private void checkResourceInstancesRelations(Resource resource) {
+ assertNotNull("component Instances Relations list is null ", resource.getComponentInstancesRelations());
+ assertTrue("component Instances Relations list is empty ",
+ !resource.getComponentInstancesRelations().equals(""));
+ }
+
+ private void checkResourceCapabilities(Resource resource) {
+ assertNotNull("component Instances Capabilities list is null ", resource.getCapabilities());
+ assertTrue("component Instances Capabilities list is empty ", !resource.getCapabilities().equals(""));
+ }
+
+ private void checkResourceRequirements(Resource resource) {
+ assertNotNull("component Instances Requirements list is null ", resource.getRequirements());
+ assertTrue("component Instances Requirements list is empty ", !resource.getRequirements().equals(""));
+ }
+
+ private void callAllCheckMethods(Resource resource) {
+
+ checkResourceInstances(resource);
+ checkResourceInstancesProperties(resource);
+ checkResourceInstancesRelations(resource);
+ checkResourceCapabilities(resource);
+ checkResourceRequirements(resource);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java
new file mode 100644
index 0000000000..ea8b89200e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/resource/VfComponentInstanceCRUDTest.java
@@ -0,0 +1,1792 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.resource;
+
+import static org.junit.Assert.assertTrue;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_ALREADY_EXISTS;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_DELETE;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_INVALID_CONTENT;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_NOT_FOUND;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class VfComponentInstanceCRUDTest extends ComponentInstanceBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public VfComponentInstanceCRUDTest() {
+ super(name, VfComponentInstanceCRUDTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+ init();
+ createComponents();
+ }
+
+ // CREATE Resource
+ private void createComponents() throws Exception {
+ createAtomicResource(resourceDetailsVFC_01);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVFC_01, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsVFC_02);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVFC_02, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsCP_01);
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsCP_02);
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_02, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsVL_01);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVL_01, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsVL_02);
+ LifecycleRestUtils.changeResourceState(resourceDetailsVL_02, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createVF(resourceDetailsVF_02);
+ }
+
+ @Test
+ public void createVfcInstanceByDesigner() throws Exception {
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVFC_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test(enabled = false) // DE189419
+ public void createInstanceOfVfToItself() throws Exception {
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVF_02);
+ createAtomicResourceInstance = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertTrue(createAtomicResourceInstance.getErrorCode() == STATUS_CODE_NOT_FOUND);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createVfcInstanceByAdmin() throws Exception {
+ User user = sdncAdminDetails;
+ createVF(resourceDetailsVF_01, user);
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_01,
+ resourceDetailsVFC_01, user);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0);
+ }
+
+ @Test
+ public void createCpInstance() throws Exception {
+ // Create CP instance
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createVlInstance() throws Exception {
+ // Create VL instance
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void updateResourceInstanceNameLessMaxLegth() throws Exception {
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx49XcharcatersXlengthXxxxxxxxx");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+
+ }
+
+ @Test
+ public void updateInstanceNameExceedMaxLegth() throws Exception {
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx51XcharcatersXlengthXxxxxxxxxxx");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void updateResourceInstanceNameHasMaxLegth() throws Exception {
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("xxxxXthisXstringxisx50XcharcatersXlengthXxxxxxxxxx");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ }
+
+ @Test
+ public void resourceInstanceNameIsEmpty() throws Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ resourceInstanceReqDetails.setName("");
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "name");
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"),
+ instanceName);
+ }
+
+ @Test
+ public void resourceInstanceNameIsNull() throws Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ resourceInstanceReqDetails.setName(null);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "name");
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"),
+ instanceName);
+ }
+
+ @Test
+ public void resourceInstanceNameValidation01() throws Exception {
+ // 2 Instances
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "name");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"),
+ instanceName);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name");
+ componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(),
+ ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"),
+ instanceName);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void resourceInstanceNameValidation02() throws Exception {
+
+ // 2 Instances
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "name");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"),
+ instanceName);
+ resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(resourceDetailsCP_01);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name");
+ componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(),
+ ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsCP_01.getName() + "2").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsCP_01.getName() + " 2"),
+ instanceName);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createVfcInstanceByTester() throws Exception { // Response 409
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncTesterDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void createVfcInstance_UserIdIsEmpty() throws Exception {
+
+ User sdncUserDetails = new User();
+ sdncUserDetails.setUserId("");
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncUserDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void createVfcInstance_UserIdIsNonAsdcUser() throws Exception {
+
+ User sdncUserDetails = new User();
+ sdncUserDetails.setUserId("bt4567");
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncUserDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void createAllAtomicInstances() throws Exception {
+
+ // Add to VF resource VFC, CP and VL instances
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 3, 0);
+ }
+
+ @Test
+ public void createDefferentVfcInstances() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVFC_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createDefferentCpInstances() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createDefferentVLInstances() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createSeveralInstanceOfSameVFC() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVFC_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createSeveralInstanceOfSameVL() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createSeveralInstanceOfSameCP() throws Exception {
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void createInstanceOfCpToVfc() throws Exception { // Add to CP to VFC
+ // (not allowed)
+
+ ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceInstanceReqDetailsVFC.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createInstanceVfcToCp() throws Exception { // (not allowed)
+
+ ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsVFC, sdncDesignerDetails, resourceInstanceReqDetailsCP.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createInstanceVlToVfc() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetailsVL = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ ComponentInstanceReqDetails resourceInstanceReqDetailsVFC = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsVFC, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsVL, sdncDesignerDetails, resourceInstanceReqDetailsVFC.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createInstanceToNonSupportedComponentType() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetailsCP = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetailsCP, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE_INSTANCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ // ("Create instance without position is allowed")
+ @Test
+ public void createInstanceOfVlWithoutPosXAndPosY() throws Exception { // instance
+ // does
+ // not
+ // have
+ // position
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ resourceInstanceReqDetails.setPosX("");
+ resourceInstanceReqDetails.setPosY("");
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ // Create instance without position is allowed")
+ @Test
+ public void createInstanceOfVlWithPositionNull() throws Exception { // instance
+ // does
+ // not
+ // have
+ // position
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ resourceInstanceReqDetails.setPosX(null);
+ resourceInstanceReqDetails.setPosY(null);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void createResourceInstanceForNonCheckedOutVF() throws Exception {
+
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncAdminDetails,
+ "0.1", LifeCycleStatesEnum.CHECKIN);
+ resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ AssertJUnit.assertEquals("Check response code after create user", STATUS_CODE_SUCCESS,
+ checkInResponse.getErrorCode().intValue());
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createResourceInstanceVfCheckedOutByOtherUser() throws Exception {
+
+ // Admin try to add RI to VF which is checked-Out By Designer
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void createResourceInstanceForNonExistingVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, "blablabla", ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ createResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ // Delete
+ @Test
+ public void deleteVfcInstanceByDesigner() throws Exception {
+
+ // Create RI
+ RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVFC_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void deleteVfcInstanceByAdmin() throws Exception {
+ createVF(resourceDetailsVF_01, sdncAdminDetails);
+ RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_01,
+ resourceDetailsVL_01, sdncAdminDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_01,
+ sdncAdminDetails);
+ ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_01, 0, 0);
+ }
+
+ @Test
+ public void deleteCpInstance() throws Exception {
+
+ RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void deleteVlInstance() throws Exception {
+
+ RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ }
+
+ @Test
+ public void deleteOneVlInstance() throws Exception {
+
+ // RI-1
+ RestResponse createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // RI-2
+ createResourceInstanceResponse = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ // Delete Resource instance RI-1
+ RestResponse deleteResourceInstanceResponse = deleteAtomicInstanceForVF(compInstId, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(deleteResourceInstanceResponse);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteVfcInstanceCheckedByOtherUser() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncTesterDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteInstanceNonSupportedComponentType() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE_INSTANCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteInstanceFromNonVF() throws Exception {
+ // RI-1
+
+ ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ // RI-2
+ ComponentInstanceReqDetails resourceInstanceCplReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceCplReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance2 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance2, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ // Delete VL instance from CP instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceInstanceCplReqDetails.getUniqueId(),
+ resourceInstanceVlReqDetails.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ }
+
+ @Test
+ public void deleteNonExistingInstanceFromVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ resourceInstanceVlReqDetails.setUniqueId("1234567890");
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVlReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteCpInstanceFromNonCheckOutVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceCpReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceCpReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
+ "0.1", LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ checkInResponse.getErrorCode().intValue());
+ resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceCpReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteVlInstanceFromNonCheckOutVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
+ "0.1", LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ checkInResponse.getErrorCode().intValue());
+ resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVlReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteVfcInstanceFromNonCheckOutVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceVfcReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceVfcReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ RestResponse checkInResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
+ "0.1", LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ checkInResponse.getErrorCode().intValue());
+ resourceDetailsVF_02.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ // Delete Resource instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceVfcReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteVlInstance_UserIdIsNonAsdcUser() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ // Delete Resource instance by non-ASDC User
+ User sdncUserDetails = new User();
+ sdncUserDetails.setUserId("bt4567");
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncUserDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void deleteAlreadyDeletedInstance() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_DELETE,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ deleteCompInstReqCapFromExpected(componentInstance.getUniqueId());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 0, 0);
+ deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncDesignerDetails,
+ resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void reCreateDeletedInstance() throws Exception {
+
+ // 2 Instances
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "name");
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "1").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 1"),
+ instanceName);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name");
+ componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(),
+ ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"),
+ instanceName);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ // Delete one instance
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), resourceInstanceReqDetails.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_DELETE,
+ deleteResourceInstanceResponse.getErrorCode().intValue());
+ deleteCompInstReqCapFromExpected(componentInstance.getUniqueId());
+ // Create same instance again
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ instanceNormalizedName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ instanceName = ResponseParser.getValueFromJsonResponse(createResourceInstanceResponse.getResponse(), "name");
+ componentInstance = ResponseParser.parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(),
+ ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "3").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance Name ", (resourceDetailsVFC_01.getName() + " 3"),
+ instanceName);
+
+ }
+
+ // Update
+ @Test
+ public void updateVfcInstanceNameByDesigner() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("abcd");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "abcd");
+ }
+
+ @Test
+ public void updateVfcInstanceNameByAdmin() throws Exception {
+ User user = sdncAdminDetails;
+ createVF(resourceDetailsVF_01, user);
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_01.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_01, 1, 0);
+ vfcResourceInstanceReqDetails.setName("ABCD E");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_01.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcde");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "ABCD E");
+ }
+
+ @Test
+ public void updateInstanceNameAllowedCharacters() throws Exception {
+ // Allowed characters: Alphanumeric (a-zA-Z0-9), space (' '), underscore
+ // ('_'), dash ('-'), dot ('.'))
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("Abcd_1234567890-qwert-yuiop.zxcvb");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ // assertEquals("Check if RI normalizedName is correct ",
+ // riNormalizedName, "abcd_1234567890-qwert-yuiop.zxcv" );
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "Abcd_1234567890-qwert-yuiop.zxcvb");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName,
+ "abcd1234567890qwertyuiopzxcvb");
+
+ }
+
+ @Test
+ public void updateVfcInstanceNameEmpty() throws Exception {
+ // see US534663 In case a designer removes the current resource instance
+ // name then BE has to generate again the "default" resource instance
+ // name
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "";
+ vfcResourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String instanceNormalizedName = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "name");
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"),
+ instanceName);
+ }
+
+ @Test
+ public void updateVfcInstanceNameNull() throws Exception {
+ // see US534663 In case a designer removes the current resource instance
+ // name then BE has to generate again the "default" resource instance
+ // name
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = null;
+ vfcResourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ final String updateResponse = updateResourceInstanceResponse.getResponse();
+ String instanceNormalizedName = ResponseParser.getValueFromJsonResponse(updateResponse, "normalizedName");
+ String instanceName = ResponseParser.getValueFromJsonResponse(updateResponse, "name");
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ",
+ (resourceDetailsVFC_01.getName() + "2").toLowerCase(), instanceNormalizedName);
+ AssertJUnit.assertEquals("check Resource Instance normalizedName ", (resourceDetailsVFC_01.getName() + " 2"),
+ instanceName);
+ }
+
+ @Test
+ public void updateCpInstanceName() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("AbcD");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "AbcD");
+ }
+
+ @Test
+ public void updateVlInstanceName() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName("ABCD");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, "abcd");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, "ABCD");
+ }
+
+ @Test
+ public void updateInstanceNameToArleadyExistInstanceName02() throws Exception {
+
+ // Create VFC instance
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance vfcComponentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(vfcComponentInstance, ComponentTypeEnum.RESOURCE);
+ // Create CP instance
+ ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance cpComponentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(cpComponentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 2, 0);
+ cpResourceInstanceReqDetails.setName(vfcComponentInstance.getName());
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_ALREADY_EXISTS,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void updateInstanceNameMaxLength() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl12345";
+ vfcResourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName, newName.toLowerCase());
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, newName);
+ }
+
+ @Test
+ public void updateInstanceNameExceedMaxLength() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "Qwertyuiop1234567890asdfAhjklzxcvbnmasdfghjkl123456";
+ vfcResourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void updateCpInstanceCheckedByOtherUser() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "Qwertyuiop1234567890";
+ resourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetails, sdncAdminDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void UpdateVfcInstance_UserIdIsNonAsdcUser() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "Qwertyuiop1234567890";
+ resourceInstanceReqDetails.setName(newName);
+ User nonSdncUserDetails = new User();
+ nonSdncUserDetails.setUserId("bt4567");
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetails, nonSdncUserDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_RESTRICTED_OPERATION,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ }
+
+ @Test
+ public void UpdateResourceInstanceFormNonExistingVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ // LifecycleRestUtils.changeResourceState(resourceDetailsVL_01,
+ // sdncAdminDetails, "0.1", LifeCycleStatesEnum.CHECKIN);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String newName = "Qwertyuiop1234567890";
+ resourceInstanceReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, "blablabla", ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void updateNonExistingInstanceFromVF() throws Exception {
+
+ ComponentInstanceReqDetails resourceInstanceVlReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance1 = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance1, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ resourceInstanceVlReqDetails.setUniqueId("1234567890");
+ // String newName= "Qwertyuiop1234567890";
+ // resourceInstanceVlReqDetails.setName(newName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ resourceInstanceVlReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ }
+
+ // Update
+ @Test
+ public void updateVfcInstanceNameAsVfName() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ vfcResourceInstanceReqDetails.setName(resourceDetailsVF_02.getName());
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String resourceNameFromJsonResponse = ResponseParser.getNameFromResponse(updateResourceInstanceResponse);
+ AssertJUnit.assertEquals(resourceNameFromJsonResponse, vfcResourceInstanceReqDetails.getName());
+ String riNormalizedName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "normalizedName");
+ String riName = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "name");
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riNormalizedName,
+ resourceDetailsVF_02.getName().toLowerCase());
+ AssertJUnit.assertEquals("Check if RI normalizedName is correct ", riName, resourceDetailsVF_02.getName());
+ }
+
+ @Test
+ public void updateInstanceNameInvalidCharacters() throws Exception {
+ char invalidChars[] = { '~', '!', '$', '%', '^', '*', '(', ')', '"', '{', '}', '[', ']', '?', '>', '<', '/',
+ '|', '\\', ',' };
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String newName = "Abcd1";
+ String updateName;
+ for (int i = 0; i < invalidChars.length; i++) {
+ updateName = newName + invalidChars[i];
+ vfcResourceInstanceReqDetails.setName(updateName);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_INVALID_CONTENT,
+ updateResourceInstanceResponse.getErrorCode().intValue());
+ }
+ }
+
+ // Update Position
+ @Test
+ public void updateVfcInstancePosition() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String updatePosX = "130";
+ String updatePosY = "180";
+ vfcResourceInstanceReqDetails.setPosX(updatePosX);
+ vfcResourceInstanceReqDetails.setPosY(updatePosY);
+ vfcResourceInstanceReqDetails.setName(null);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String posXFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX");
+ String posYFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ }
+
+ @Test
+ public void updateVlInstancePosition() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVL_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String updatePosX = "130";
+ String updatePosY = "180";
+ vfcResourceInstanceReqDetails.setPosX(updatePosX);
+ vfcResourceInstanceReqDetails.setPosY(updatePosY);
+ vfcResourceInstanceReqDetails.setName(null);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String posXFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX");
+ String posYFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ }
+
+ @Test
+ public void updateCpInstancePosition() throws Exception {
+
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String updatePosX = "130";
+ String updatePosY = "180";
+ vfcResourceInstanceReqDetails.setPosX(updatePosX);
+ vfcResourceInstanceReqDetails.setPosY(updatePosY);
+ vfcResourceInstanceReqDetails.setName(null);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String posXFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX");
+ String posYFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ }
+
+ @Test
+ public void updateInstancePositionNegativePosition() throws Exception {
+
+ ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, ComponentTypeEnum.RESOURCE);
+ getComponentAndValidateRIs(resourceDetailsVF_02, 1, 0);
+ String updatePosX = "-100";
+ String updatePosY = "-100";
+ cpResourceInstanceReqDetails.setPosX(updatePosX);
+ cpResourceInstanceReqDetails.setPosY(updatePosY);
+ cpResourceInstanceReqDetails.setName(null);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String posXFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX");
+ String posYFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ }
+
+ @Test
+ public void updateInstancesPositionSameLocationForBothInstances() throws Exception {
+
+ ComponentInstanceReqDetails cpResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ ComponentInstanceReqDetails vfcResourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsVFC_01);
+ createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ String updatePosX = "100";
+ String updatePosY = "500";
+ vfcResourceInstanceReqDetails.setPosX(updatePosX);
+ vfcResourceInstanceReqDetails.setPosY(updatePosY);
+ vfcResourceInstanceReqDetails.setName(null);
+ cpResourceInstanceReqDetails.setPosX(updatePosX);
+ cpResourceInstanceReqDetails.setPosY(updatePosY);
+ cpResourceInstanceReqDetails.setName(null);
+ RestResponse updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ vfcResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ String posXFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posX");
+ String posYFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(), "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ updateResourceInstanceResponse = ComponentInstanceRestUtils.updateComponentInstance(
+ cpResourceInstanceReqDetails, sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(),
+ ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(updateResourceInstanceResponse);
+ posXFromJsonResponse = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "posX");
+ posYFromJsonResponse = ResponseParser.getValueFromJsonResponse(updateResourceInstanceResponse.getResponse(),
+ "posY");
+ AssertJUnit.assertEquals(posXFromJsonResponse, updatePosX);
+ AssertJUnit.assertEquals(posYFromJsonResponse, updatePosY);
+ }
+
+ @Test
+ public void createAllAtomicInstancesTestGetReqCapAPI_suc() throws Exception {
+
+ // Add to VF resource VFC, CP and VL instances
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+
+ getVfResourceReqCapUsingAPI(3, 0, sdncDesignerDetails);
+
+ }
+
+ // END of Update
+
+ @Test
+ public void createAllAtomicInstancesTestGetReqCapAPIfailed() throws Exception {
+
+ // Add to VF resource VFC, CP and VL instances
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsVL_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ resourceDetailsVF_02.setUniqueId("dummy");
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncAdminDetails,
+ resourceDetailsVF_02);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_NOT_FOUND,
+ getResourceResponse.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void associateInVF() throws Exception {
+
+ ResourceReqDetails resourceDetailsReq = ElementFactory.getDefaultResourceByType("SoftCompRouter",
+ NormativeTypesEnum.SOFTWARE_COMPONENT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS,
+ sdncDesignerDetails.getUserId(), ResourceTypeEnum.VFC); // resourceType
+ // = VFC
+ ResourceReqDetails resourceDetailsCap = ElementFactory.getDefaultResourceByType("MyComput",
+ NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VFC); // resourceType = VFC
+ createAtomicResource(resourceDetailsReq);
+ LifecycleRestUtils.changeResourceState(resourceDetailsReq, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createAtomicResource(resourceDetailsCap);
+ LifecycleRestUtils.changeResourceState(resourceDetailsCap, sdncAdminDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+
+ RestResponse riReqR = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsReq, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(riReqR);
+ RestResponse riCapR = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsCap, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(riCapR);
+
+ ComponentInstance riReq = ResponseParser.parseToObject(riReqR.getResponse(), ComponentInstance.class);
+ ComponentInstance riCap = ResponseParser.parseToObject(riCapR.getResponse(), ComponentInstance.class);
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ resourceDetailsVF_02);
+
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get("tosca.capabilities.Container");
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get("tosca.capabilities.Container");
+
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(riReq.getUniqueId());
+ requirementDef.setToNode(riCap.getUniqueId());
+
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(riReq.getUniqueId());
+ pair.setCapabilityOwnerId(riCap.getUniqueId());
+ pair.setRequirement("host");
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("tosca.capabilities.Container");
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capList.get(0).getUniqueId());
+ pair.setRequirementUid(reqList.get(0).getUniqueId());
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ associateInstances.getErrorCode().intValue());
+
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ resourceDetailsVF_02);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+
+ List<RequirementDefinition> list = capReqDef.getRequirements().get("tosca.capabilities.Container");
+ AssertJUnit.assertEquals("Check requirement", null, list);
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF_02.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ dissociateInstances.getErrorCode().intValue());
+
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ resourceDetailsVF_02);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+
+ list = capReqDef.getRequirements().get("tosca.capabilities.Container");
+ AssertJUnit.assertEquals("Check requirement", 1, list.size());
+
+ }
+
+ @Test
+ public void testUnsatisfiedCpReqInVF() throws Exception {
+
+ // Certify all the needed atomic resources
+ RestResponse response = LifecycleRestUtils.certifyResource(resourceDetailsVFC_02);
+ ResourceRestUtils.checkSuccess(response);
+ response = LifecycleRestUtils.certifyResource(resourceDetailsCP_01);
+ ResourceRestUtils.checkSuccess(response);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails,
+ resourceDetailsVF_02.getUniqueId());
+ ResourceRestUtils.checkSuccess(response);
+
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String compInstName = ResponseParser.getNameFromResponse(createAtomicResourceInstance);
+ String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ RestResponse submitForTesting = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02,
+ sdncDesignerDetails, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ String[] variables = new String[] { resourceDetailsVF_02.getName(), "VF", "CP (Connection Point)", compInstName,
+ "requirement", "tosca.capabilities.network.Bindable", "fulfilled" };
+ BaseValidationUtils.checkErrorResponse(submitForTesting,
+ ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, variables);
+
+ createAtomicResourceInstance = createAtomicInstanceForVF(resourceDetailsVF_02, resourceDetailsVFC_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+ fulfillCpRequirement(resourceDetailsVF_02, cpCompInstId, computeCompInstId, computeCompInstId,
+ sdncDesignerDetails, ComponentTypeEnum.RESOURCE);
+
+ submitForTesting = LifecycleRestUtils.changeResourceState(resourceDetailsVF_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ BaseValidationUtils.checkSuccess(submitForTesting);
+ }
+
+ private void getVfResourceReqCapUsingAPI(int numberOfRIs, int numberOfRelations, User user)
+ throws IOException, Exception {
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncAdminDetails,
+ resourceDetailsVF_02);
+ AssertJUnit.assertEquals("Check response code ", STATUS_CODE_SUCCESS,
+ getResourceResponse.getErrorCode().intValue());
+ // ResourceValidationUtils.validateResp(getResourceResponse,
+ // resourceRespJavaObject);
+ // int numberOfActualRIs = resource.getComponentInstances()!=null ?
+ // resource.getComponentInstances().size() : 0;
+ // int numberOfActualRelations =
+ // resource.getComponentInstancesRelations()!=null ?
+ // resource.getComponentInstancesRelations().size() : 0;
+ // assertEquals("Check number of RIs meet the expected number",
+ // numberOfRIs ,numberOfActualRIs);
+ // assertEquals("Check number of RI relations meet the expected number",
+ // numberOfRelations ,numberOfActualRelations);
+
+ //// get VF actual Capabilities and Requirements and validate according
+ //// to expected
+ Resource vfResource = ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(),
+ Resource.class);
+ verifyReqCap(vfResource);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java
new file mode 100644
index 0000000000..c8a20cf44a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ChangeServiceDistributionStatusApiTest.java
@@ -0,0 +1,1008 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ChangeServiceDistributionStatusApiTest extends ComponentBaseTest {
+
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected User sdncDesignerDetails;
+ protected User sdncAdminDetails;
+ protected User sdncGovernorDeatails;
+ protected User sdncTesterDetails;
+ protected User sdncOpsDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected Component resourceDetailsVFCcomp;
+ protected Component serviceDetailsCompp;
+
+ private String userRemarks = "commentTest";
+
+ private List<String> variablesAsList;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ChangeServiceDistributionStatusApiTest() throws Exception {
+ super(name, ChangeServiceDistributionStatusApiTest.class.getName());
+
+ }
+
+ @BeforeMethod
+ public void init() throws Exception {
+
+ variablesAsList = new ArrayList<String>();
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ resourceDetailsVFCcomp = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ true, true);
+
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+ Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ,
+ UserRoleEnum.DESIGNER, true);
+
+ serviceDetails = new ServiceReqDetails(serviceServ);
+
+ }
+
+ // -----------------------------------------------T E S T
+ // S--------------------------------------------//
+
+ @Test
+ public void approveNotCertifiedService_checkout() throws Exception {
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void approveNotCertifiedService_checkedin() throws Exception {
+ RestResponse checkinResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals(200, checkinResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void approveNotCertifiedService_inProgress() throws Exception {
+ RestResponse certReqResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(200, certReqResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DApprove";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DApprove", LifecycleStateEnum.READY_FOR_CERTIFICATION,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+
+ }
+
+ @Test
+ public void approveNotCertifiedService_readyForCer() throws Exception {
+ approveNotCertifiedService_inProgress();
+ DbUtils.deleteFromEsDbByPattern("_all");
+
+ RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(200, startCertResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DApprove";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setDprevStatus("");
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void rejectNotCertifiedService_checkeout() throws Exception {
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setDprevStatus("");
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void rejectNotCertifiedService_checkedin() throws Exception {
+ RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertEquals(200, startCertResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKIN.name());
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setDprevStatus("");
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.NOT_CERTIFIED_CHECKIN,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void rejectNotCertifiedService_inProgress() throws Exception {
+ RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(200, startCertResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.READY_FOR_CERTIFICATION.name());
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setDprevStatus("");
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.READY_FOR_CERTIFICATION,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+ }
+
+ @Test
+ public void rejectNotCertifiedService_readyForCer() throws Exception {
+ rejectNotCertifiedService_inProgress();
+ DbUtils.deleteFromEsDbByPattern("_all");
+
+ RestResponse startCertResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(200, startCertResp.getErrorCode().intValue());
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 403, serviceDetails.getVersion());
+
+ variablesAsList = Arrays.asList(serviceDetails.getVersion(), serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name(),
+ variablesAsList, changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // version, sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setDprevStatus("");
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setStatus("403");
+ // expectedResourceAuditJavaObject.setDesc(String.format(errorInfo.getMessageId()
+ // + ": " + errorInfo.getMessage(), version,
+ // serviceDetails.getServiceName()));
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFICATION_IN_PROGRESS,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ "403", ActionStatus.SERVICE_NOT_AVAILABLE_FOR_DISTRIBUTION, sdncAdminDetails);
+
+ }
+
+ @Test
+ public void approveCertifiedService_bysdncGovernorDeatails() throws Exception {
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncGovernorDeatails);
+ }
+
+ @Test
+ public void approveCertifiedService_bysdncAdminDetails() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails);
+ }
+
+ @Test
+ public void approveCertifiedService_byDesigner() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncDesignerDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ // String auditAction="DApprove";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncDesignerDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setStatus("409");
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ":
+ // " + errorInfo.getMessage());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncDesignerDetails);
+ }
+
+ @Test
+ public void approveCertifiedService_byTester() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncTesterDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ // String auditAction="DApprove";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncTesterDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setStatus("409");
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ":
+ // " + errorInfo.getMessage());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncTesterDetails);
+ }
+
+ @Test
+ public void approveCertifiedService_byOps() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncOpsDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncOpsDetails);
+
+ }
+
+ @Test
+ public void rejectCertifiedService_bysdncGovernorDeatails() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncGovernorDeatails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails);
+
+ }
+
+ @Test
+ public void rejectCertifiedService_bysdncAdminDetails() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(changeDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncAdminDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_REJECTED.name());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncAdminDetails);
+ }
+
+ @Test
+ public void rejectCertifiedService_byDesigner() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncDesignerDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncDesignerDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setStatus("409");
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ":
+ // " + errorInfo.getMessage());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncDesignerDetails);
+ }
+
+ @Test
+ public void rejectCertifiedService_byTester() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncTesterDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncTesterDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setStatus("409");
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ":
+ // " + errorInfo.getMessage());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncTesterDetails);
+ }
+
+ @Test
+ public void rejectCertifiedService_byOps() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncOpsDetails, 409, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ // ErrorInfo errorInfo =
+ // utils.parseYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ // String auditAction="DReject";
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(certifyService,
+ // certifyService.getVersion(), sdncOpsDetails);
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setResourceType("Service");
+ // expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.CERTIFIED.name());
+ // expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.CERTIFICATION_IN_PROGRESS.name());
+ // expectedResourceAuditJavaObject.setDprevStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setDcurrStatus(DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED.name());
+ // expectedResourceAuditJavaObject.setStatus("409");
+ // expectedResourceAuditJavaObject.setDesc(errorInfo.getMessageId() + ":
+ // " + errorInfo.getMessage());
+ // expectedResourceAuditJavaObject.setComment(userRemarks);
+ // expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ //
+ // AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, "409", ActionStatus.RESTRICTED_OPERATION,
+ sdncOpsDetails);
+ }
+
+ @Test
+ public void approveServiceNotFound() throws Exception {
+ String previuosId = serviceDetails.getUniqueId();
+ serviceDetails.setUniqueId("dummyId");
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 404, serviceDetails.getVersion());
+ serviceDetails.setUniqueId(previuosId);
+
+ variablesAsList = Arrays.asList("dummyId");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList,
+ changeDistStatusAndValidate.getResponse());
+
+ }
+
+ @Test
+ public void rejectServiceNotFound() throws Exception {
+ String previuosId = serviceDetails.getUniqueId();
+ serviceDetails.setUniqueId("dummyId");
+
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 404, serviceDetails.getVersion());
+ serviceDetails.setUniqueId(previuosId);
+
+ variablesAsList = Arrays.asList("dummyId");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variablesAsList,
+ changeDistStatusAndValidate.getResponse());
+
+ }
+
+ @Test
+ public void rejectService_emptyComment() throws Exception {
+ userRemarks = "";
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ }
+
+ @Test
+ public void rejectService_nullComment() throws Exception {
+ userRemarks = null;
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+ }
+
+ @Test
+ public void rejectService_spaceComment() throws Exception {
+ userRemarks = " ";
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ }
+
+ @Test
+ public void approveService_emptyComment() throws Exception {
+ userRemarks = "";
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ }
+
+ @Test
+ public void approveService_nullComment() throws Exception {
+ userRemarks = null;
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ }
+
+ @Test
+ public void approveService_spaceComment() throws Exception {
+ userRemarks = " ";
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse changeDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 400, certifyService.getVersion());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_CONTENT.name(), new ArrayList<String>(),
+ changeDistStatusAndValidate.getResponse());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED);
+
+ }
+
+ @Test
+ public void distributionStatusChange_approve_Reject_AprroveBysdncAdminDetails() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+
+ RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse rejectDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, sdncGovernorDeatails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(rejectDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+
+ validateAudit("DReject", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_APPROVED,
+ DistributionStatusEnum.DISTRIBUTION_REJECTED, null, null, sdncGovernorDeatails);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse secondApproveDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncAdminDetails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(secondApproveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ validateAudit("DApprove", LifecycleStateEnum.CERTIFIED, DistributionStatusEnum.DISTRIBUTION_REJECTED,
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, null, null, sdncAdminDetails);
+
+ }
+
+ @Test
+ public void distributeNotCertifiedServiceTest() throws Exception {
+ RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED,
+ sdncGovernorDeatails, 200, serviceDetails.getVersion());
+
+ RestResponse getService = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED);
+
+ }
+
+ @Test
+ public void distributeCertifiedServiceTest() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(DistributionStatusEnum.DISTRIBUTED,
+ sdncGovernorDeatails, 200, certifyService.getVersion());
+
+ RestResponse getService = ServiceRestUtils.getService(certifyService, sdncDesignerDetails);
+ getDistrubtionStatusValue(getService, DistributionStatusEnum.DISTRIBUTED);
+
+ }
+
+ @Test
+ public void approveCheckedoutCertifiedServiceTest() throws Exception {
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser
+ .convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ RestResponse approveDistStatusAndValidate = changeDistStatusAndValidate(
+ DistributionStatusEnum.DISTRIBUTION_APPROVED, sdncGovernorDeatails, 200, certifyService.getVersion());
+ getDistrubtionStatusValue(approveDistStatusAndValidate, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+
+ RestResponse checkoutResp = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(200, checkoutResp.getErrorCode().intValue());
+ // Utils r = new Utils();
+
+ String distributionStatus = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(),
+ "distributionStatus");
+ // Utils r1 = new Utils();
+ String lifecycleState = ResponseParser.getValueFromJsonResponse(checkoutResp.getResponse(), "lifecycleState");
+
+ assertTrue("NOT_CERTIFIED_CHECKOUT".equals(lifecycleState));
+ assertTrue("DISTRIBUTION_NOT_APPROVED".equals(distributionStatus));
+ }
+
+ private RestResponse changeDistStatusAndValidate(DistributionStatusEnum distStatus, User user, int errorCode,
+ String serviceVersion) throws Exception {
+ RestResponse distributionResponse = LifecycleRestUtils.changeDistributionStatus(serviceDetails, serviceVersion,
+ user, userRemarks, distStatus);
+ assertNotNull(distributionResponse);
+ assertNotNull(distributionResponse.getErrorCode());
+ assertEquals(errorCode, distributionResponse.getErrorCode().intValue());
+
+ if (userRemarks == " " || userRemarks == null) {
+ userRemarks = "";
+ }
+
+ return distributionResponse;
+ }
+
+ private void getDistrubtionStatusValue(RestResponse response, DistributionStatusEnum expectedDistributionValue)
+ throws Exception {
+ String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(),
+ "distributionStatus");
+ assertEquals(expectedDistributionValue.name(), actualDistributionValue);
+ }
+
+ private void validateAudit(String Action, LifecycleStateEnum currState, DistributionStatusEnum dPrevStatus,
+ DistributionStatusEnum dCurrStatus, String status, ActionStatus errorInfoFromFile, User user)
+ throws Exception {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceDetails.getVersion(), user);
+ expectedResourceAuditJavaObject.setAction(Action);
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ expectedResourceAuditJavaObject.setCurrState(currState.name());
+ expectedResourceAuditJavaObject.setDprevStatus(dPrevStatus.name());
+ expectedResourceAuditJavaObject.setDcurrStatus(dCurrStatus.name());
+ expectedResourceAuditJavaObject.setComment(userRemarks);
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ if (errorInfoFromFile != null) {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorInfoFromFile.name());
+ expectedResourceAuditJavaObject
+ .setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variablesAsList));
+ }
+
+ if (status != null)
+ expectedResourceAuditJavaObject.setStatus(status);
+
+ if (currState != LifecycleStateEnum.CERTIFIED) {
+ expectedResourceAuditJavaObject.setModifierName("");
+ }
+
+ AuditValidationUtils.validateAuditDistribution(expectedResourceAuditJavaObject, Action);
+ }
+
+ // private ServiceReqDetails certifyService() throws Exception
+ // {
+ // ServiceReqDetails certifyService =
+ // LifecycleRestUtils.certifyService(serviceDetails,
+ // serviceDetails.getVersion(), sdncAdminDetails);
+ //// version = certifyService.getVersion();
+ //
+ // return certifyService;
+ // }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java
new file mode 100644
index 0000000000..56cfeb54ea
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/CreateServiceMetadataApiTest.java
@@ -0,0 +1,1300 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import org.json.JSONObject;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+
+public class CreateServiceMetadataApiTest extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(CreateServiceMetadataApiTest.class.getName());
+
+ String serviceBaseVersion = "0.1";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CreateServiceMetadataApiTest() {
+ super(name, CreateServiceMetadataApiTest.class.getName());
+ }
+
+ @Test
+ public void createDefaultService() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // String creator =
+ // ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId();
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue());
+
+ // validate create service response vs actual
+
+ Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails,
+ (LifecycleStateEnum) null);
+
+ // validate get service response vs actual
+ restResponse = ServiceRestUtils.getService(serviceDetails, sdncUserDetails);
+ service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails,
+ (LifecycleStateEnum) null);
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createDefaultServiceUserDesigner() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue());
+
+ // validate create service response vs actual
+
+ Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails,
+ (LifecycleStateEnum) null);
+
+ // validate get service response vs actual
+ restResponse = ServiceRestUtils.getService(serviceDetails, sdncUserDetails);
+ service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceUserNotFound() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncUserDetails.setUserId("no1234");
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ sdncUserDetails.setFirstName("");
+ sdncUserDetails.setLastName("");
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setModifierName("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceUserNotAllowed() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceEmptyName() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ String serviceName = "";
+ serviceDetails.setName(serviceName);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_COMPONENT_NAME.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_COMPONENT_NAME.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceEmptyCategory() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ String category = "";
+
+ serviceDetails.setCategories(null);
+ // serviceDetails.addCategory(category);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_CATEGORY.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_CATEGORY.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceEmptyTag() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add("");
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setTags(tags);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service", "tag");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceEmptyDescription() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ String description = "";
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setDescription(description);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_MISSING_DESCRIPTION.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceEmptyTags() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add("");
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setTags(tags);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FIELD_FORMAT.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service", "tag");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FIELD_FORMAT.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceByPutHttpMethod() throws Exception {
+
+ String method = "PUT";
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+
+ RestResponse restResponse = ServiceRestUtils.createServiceByHttpMethod(serviceDetails, sdncUserDetails, method,
+ Urls.CREATE_SERVICE);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ restResponse.getResponse());
+
+ // //validate audit
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // resourceUtils.constructFieldsForAuditValidation(serviceDetails,
+ // serviceBaseVersion, sdncUserDetails);
+ //
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ //
+ // String auditDesc =
+ // AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ // expectedResourceAuditJavaObject.setDesc(auditDesc);
+ //
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ }
+
+ @Test
+ public void createServiceByDeleteHttpMethod() throws Exception {
+
+ String method = "DELETE";
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+
+ RestResponse restResponse = ServiceRestUtils.createServiceByHttpMethod(serviceDetails, sdncUserDetails, method,
+ Urls.CREATE_SERVICE);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.NOT_ALLOWED.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.NOT_ALLOWED.name(), variables,
+ restResponse.getResponse());
+
+ // //validate audit
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // resourceUtils.constructFieldsForAuditValidation(serviceDetails,
+ // serviceBaseVersion, sdncUserDetails);
+ //
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ //
+ // String auditDesc =
+ // AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ // expectedResourceAuditJavaObject.setDesc(auditDesc);
+ //
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction);
+
+ }
+
+ @Test
+ public void createServiceTagLengthExceedLimit() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ StringBuffer tagBuffer = new StringBuffer();
+ for (int i = 0; i < 1025; i++) {
+ tagBuffer.append("a");
+ }
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add(tagBuffer.toString());
+ serviceDetails.setTags(tags);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("50");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SINGLE_TAG_EXCEED_LIMIT.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("50"));
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ /*
+ * ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ * ServiceValidationUtils.constructFieldsForAuditValidation(
+ * serviceDetails, serviceBaseVersion, sdncUserDetails);
+ *
+ * String auditAction="Create";
+ * expectedResourceAuditJavaObject.setAction(auditAction);
+ * expectedResourceAuditJavaObject.setPrevState("");
+ * expectedResourceAuditJavaObject.setPrevVersion("");
+ * expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.
+ * NOT_CERTIFIED_CHECKOUT).toString());
+ * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().
+ * toString()); expectedResourceAuditJavaObject.setDesc(auditDesc);
+ *
+ * AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ * auditAction, null);
+ */
+
+ }
+
+ @Test
+ public void createServiceAlreadyExistException() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // create service with the same name
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+
+ List<String> variables = Arrays.asList("Service", serviceDetails.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_NAME_ALREADY_EXIST.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void createServiceWrongContactId() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setContactId("123as");
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.COMPONENT_INVALID_CONTACT.name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+ }
+
+ @Test
+ public void createServiceProjectName() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setProjectCode("12345");
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ Integer expectedCode = 201;
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", expectedCode, restResponse.getErrorCode());
+ Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+
+ assertEquals("12345", service.getProjectCode());
+ }
+
+ @Test
+ public void createAndGetByNameAndVersion() throws Exception {
+
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ // create
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ assertEquals("Check response code after create service", 201, restResponse.getErrorCode().intValue());
+
+ // get
+ restResponse = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, serviceDetails.getName(),
+ serviceBaseVersion);
+ assertEquals("Check response code after get service", 200, restResponse.getErrorCode().intValue());
+
+ Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse());
+ String uniqueId = service.getUniqueId();
+ serviceDetails.setUniqueId(uniqueId);
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails,
+ (LifecycleStateEnum) null);
+ }
+
+ //// US553874
+
+ @JsonIgnore
+ @Test
+ public void createServiceIsVNF_isFalse() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after updating Interface Artifact", 201,
+ restResponse.getErrorCode().intValue());
+
+ // get service and verify that service created with isVNF defined in
+ // serviceDetails
+ RestResponse serviceByNameAndVersion = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ serviceDetails.getName(), serviceBaseVersion);
+ Service serviceObject = ResponseParser
+ .convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, serviceObject, sdncUserDetails,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @JsonIgnore
+ @Test
+ public void createServiceIsVNF_isTrue() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after updating Interface Artifact", 201,
+ restResponse.getErrorCode().intValue());
+
+ // get service and verify that service created with isVNF defined in
+ // serviceDetails
+ RestResponse serviceByNameAndVersion = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ serviceDetails.getName(), serviceBaseVersion);
+ Service serviceObject = ResponseParser
+ .convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, serviceObject, sdncUserDetails,
+ LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ // validate audit
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @JsonIgnore
+ @Test(enabled = false)
+ public void createServiceIsVNF_isNull() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ // clean audit DB before service creation
+ DbUtils.cleanAllAudits();
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertEquals("Check response code after updating Interface Artifact", 400,
+ restResponse.getErrorCode().intValue());
+ List<String> variables = Arrays.asList("VNF Service Indicator");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("VNF Service Indicator"));
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+ }
+
+ @JsonIgnore
+ @Test(enabled = false)
+ public void createServiceEmptyIsVNF() throws Exception {
+
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+
+ DbUtils.cleanAllAudits();
+
+ // send create service toward BE
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", restResponse.getErrorCode(),
+ restResponse.getErrorCode());
+
+ // validate create service response vs actual
+ List<String> variables = Arrays.asList("VNF Service Indicator");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, serviceBaseVersion, sdncUserDetails);
+
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setAction(auditAction);
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ private RestResponse createServiceWithMissingAttribute(String serviceDetails, User sdncModifierDetails)
+ throws Exception {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = ServiceRestUtils.prepareHeadersMap(sdncModifierDetails, false);
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache");
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
+ // TODO: ADD AUTHENTICATION IN REQUEST
+ logger.debug(url);
+ logger.debug("Send POST request to create service: {}", url);
+ logger.debug("Service body: {}", serviceDetails);
+ logger.debug("Service headers: {}", headersMap);
+ RestResponse sendCreateUserRequest = http.httpSendPost(url, serviceDetails, headersMap);
+
+ return sendCreateUserRequest;
+
+ }
+
+ @JsonIgnore
+ @Test(enabled = false)
+ public void createServiceVersion_isVNFDoesNotExistInJson() throws Exception {
+
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // clean audit DB before updating service
+ DbUtils.cleanAllAudits();
+
+ // remove isVNF from json sent to create service
+ JSONObject jObject = new JSONObject(serviceDetails);
+ jObject.remove("VNF");
+
+ // send create service toward BE
+ RestResponse restResponse = createServiceWithMissingAttribute(jObject.toString(), sdncUserDetails);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after updating Interface Artifact", 400,
+ restResponse.getErrorCode().intValue());
+ List<String> variables = new ArrayList<String>();
+ variables.add("VNF Service Indicator");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(), variables,
+ restResponse.getResponse());
+
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.MISSING_DATA.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = ServiceValidationUtils
+ .constructFieldsForAuditValidation(serviceDetails, "0.1", sdncUserDetails);
+ String auditAction = "Create";
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc("VNF Service Indicator"));
+ AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null, false);
+
+ }
+
+ @Test
+ public void checkInvariantUuidIsImmutable() throws Exception {
+ // choose the user to create service
+ User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ Component resourceDetailsVFCcomp = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.ADMIN, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.ADMIN,
+ true, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.ADMIN,
+ LifeCycleStatesEnum.CERTIFY, true);
+
+ // fill new service details
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ String invariantUuidDefinedByUser = "!!!!!!!!!!!!!!!!!!!!!!!!";
+ serviceDetails.setInvariantUUID(invariantUuidDefinedByUser);
+
+ // create service
+ RestResponse restResponseCreation = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ BaseRestUtils.checkStatusCode(restResponseCreation, "create request failed", false, 201);
+ Service service = ResponseParser.convertServiceResponseToJavaObject(restResponseCreation.getResponse());
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, service,
+ UserRoleEnum.ADMIN, true);
+
+ String invariantUUIDcreation = service.getInvariantUUID();
+
+ // validate get service response vs actual
+ RestResponse restResponseGetting = ServiceRestUtils.getService(serviceDetails, sdncUserDetails);
+ BaseRestUtils.checkSuccess(restResponseGetting);
+ service = ResponseParser.convertServiceResponseToJavaObject(restResponseGetting.getResponse());
+ String invariantUUIDgetting = service.getInvariantUUID();
+
+ assertEquals(invariantUUIDcreation, invariantUUIDgetting);
+
+ // Update service with new invariant UUID
+ RestResponse restResponseUpdate = ServiceRestUtils.updateService(serviceDetails, sdncUserDetails);
+ BaseRestUtils.checkSuccess(restResponseUpdate);
+ Service updatedService = ResponseParser.convertServiceResponseToJavaObject(restResponseUpdate.getResponse());
+ String invariantUUIDupdating = updatedService.getInvariantUUID();
+ assertEquals(invariantUUIDcreation, invariantUUIDupdating);
+
+ // Do checkin
+ RestResponse restResponseCheckin = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ BaseRestUtils.checkSuccess(restResponseCheckin);
+ Service checkinService = ResponseParser.convertServiceResponseToJavaObject(restResponseCheckin.getResponse());
+ String invariantUUIDcheckin = checkinService.getInvariantUUID();
+ String version = checkinService.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckin);
+ assertEquals(version, "0.1");
+
+ // Do checkout
+ RestResponse restResponseCheckout = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ BaseRestUtils.checkSuccess(restResponseCheckout);
+ Service checkoutService = ResponseParser.convertServiceResponseToJavaObject(restResponseCheckout.getResponse());
+ String invariantUUIDcheckout = checkoutService.getInvariantUUID();
+ version = checkoutService.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcheckout);
+ assertEquals(version, "0.2");
+
+ // do certification request
+ RestResponse restResponseCertificationRequest = LifecycleRestUtils.changeServiceState(serviceDetails,
+ sdncUserDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ BaseRestUtils.checkSuccess(restResponseCertificationRequest);
+ Service certificationRequestService = ResponseParser
+ .convertServiceResponseToJavaObject(restResponseCertificationRequest.getResponse());
+ String invariantUUIDcertificationRequest = certificationRequestService.getInvariantUUID();
+ version = certificationRequestService.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcertificationRequest);
+ assertEquals(version, "0.2");
+
+ // start certification
+ RestResponse restResponseStartCertification = LifecycleRestUtils.changeServiceState(serviceDetails,
+ sdncUserDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ BaseRestUtils.checkSuccess(restResponseStartCertification);
+ Service startCertificationRequestService = ResponseParser
+ .convertServiceResponseToJavaObject(restResponseStartCertification.getResponse());
+ String invariantUUIDStartCertification = startCertificationRequestService.getInvariantUUID();
+ version = startCertificationRequestService.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDStartCertification);
+ assertEquals(version, "0.2");
+
+ // certify
+ RestResponse restResponseCertify = LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails,
+ serviceDetails.getVersion(), LifeCycleStatesEnum.CERTIFY);
+ BaseRestUtils.checkSuccess(restResponseCertify);
+ Service certifyService = ResponseParser.convertServiceResponseToJavaObject(restResponseCertify.getResponse());
+ String invariantUUIDcertify = certifyService.getInvariantUUID();
+ version = certifyService.getVersion();
+ assertEquals(invariantUUIDcreation, invariantUUIDcertify);
+ assertEquals(version, "1.0");
+
+ }
+
+ // US672129 Benny
+ private void getServiceValidateInvariantUuid(String serviceUniqueId, String invariantUUIDcreation)
+ throws Exception {
+ RestResponse getService = ServiceRestUtils.getService(serviceUniqueId,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, getService.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(getService));
+ }
+
+ @Test // invariantUUID generated when the component is created and never
+ // changed
+ public void serviceInvariantUuid() throws Exception {
+ User designerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ User testerUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ User pmUser = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ Component resourceDetailsVFCcomp = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+ // create service
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setInvariantUUID("123456");
+ RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, designerUser);
+ assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_CREATED,
+ restResponse.getErrorCode().intValue());
+ Service service = ResponseParser.parseToObjectUsingMapper(restResponse.getResponse(), Service.class);
+ // invariantUUID generated when the component is created and never
+ // changed
+ String invariantUUIDcreation = ResponseParser.getInvariantUuid(restResponse);
+ // Add VF instance to service
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, service,
+ UserRoleEnum.DESIGNER, true);
+ // get resource and verify InvariantUuid is not changed
+ getServiceValidateInvariantUuid(service.getUniqueId(), invariantUUIDcreation);
+
+ // Update service with new invariant UUID
+ restResponse = ServiceRestUtils.updateService(serviceDetails, designerUser);
+ assertEquals("Check response code after create resource", BaseRestUtils.STATUS_CODE_SUCCESS,
+ restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // Checkin
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // Checkout
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certification request
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // start certification
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certify
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser, LifeCycleStatesEnum.CERTIFY);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // update resource
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ serviceDetails.setDescription("updatedDescription");
+ restResponse = ServiceRestUtils.updateService(serviceDetails, designerUser);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certification request
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // Checkout
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // certification request
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // start certification
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // cancel certification
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser,
+ LifeCycleStatesEnum.CANCELCERTIFICATION);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // start certification
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // failure
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, testerUser,
+ LifeCycleStatesEnum.FAILCERTIFICATION);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // Checkout
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser,
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // Checkin
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN);
+ assertEquals(BaseRestUtils.STATUS_CODE_SUCCESS, restResponse.getErrorCode().intValue());
+ assertEquals(invariantUUIDcreation, ResponseParser.getInvariantUuid(restResponse));
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ // create instance
+ ProductReqDetails productDetails = ElementFactory.getDefaultProduct();
+ RestResponse createProductResponse = ProductRestUtils.createProduct(productDetails, pmUser);
+ assertEquals(BaseRestUtils.STATUS_CODE_CREATED, createProductResponse.getErrorCode().intValue());
+ ComponentInstanceReqDetails serviceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(serviceDetails);
+ RestResponse createServiceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ serviceInstanceReqDetails, pmUser, productDetails.getUniqueId(), ComponentTypeEnum.PRODUCT);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_CREATED,
+ createServiceInstanceResponse.getErrorCode().intValue());
+ getServiceValidateInvariantUuid(serviceDetails.getUniqueId(), invariantUUIDcreation);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java
new file mode 100644
index 0000000000..760d002856
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetAllServiceVersions.java
@@ -0,0 +1,350 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GetAllServiceVersions extends ComponentBaseTest {
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected User sdncDesignerDetails;
+ protected User sdncDesignerDetails2;
+ protected User sdncAdminDetails;
+ protected User sdncGovernorDeatails;
+ protected User sdncTesterDetails;
+ protected User sdncOpsDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected Component resourceDetailsVFCcomp;
+ protected Service serviceServ;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetAllServiceVersions() {
+ super(name, GetAllServiceVersions.class.getName());
+ ;
+ }
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ resourceDetailsVFCcomp = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ true, true);
+
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER,
+ LifeCycleStatesEnum.CERTIFY, true);
+ serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ,
+ UserRoleEnum.DESIGNER, true);
+
+ serviceDetails = new ServiceReqDetails(serviceServ);
+
+ }
+
+ @Test
+ public void GetAllServiceVersions_Version05() throws Exception {
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ }
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+
+ }
+
+ @Test
+ public void GetAllServiceVersions_Version01() throws Exception {
+
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncDesignerDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_Version15() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ }
+
+ RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ // serviceServ.setUniqueId(serviceDetails.getUniqueId());
+ // RestResponse changeServiceState =
+ // AtomicOperationUtils.changeComponentState(serviceServ,
+ // UserRoleEnum.ADMIN, LifeCycleStatesEnum.CERTIFY, false).getRight();
+
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ for (int x = 0; x < 5; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ }
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_Version25() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ }
+
+ // getting to version 1.0
+ RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ // getting to version 1.5
+ for (int x = 0; x < 5; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ }
+
+ // getting to version 2.0
+ changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ // getting to version 2.5
+ for (int x = 0; x < 5; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ }
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_ReadyForCertification_version05() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ }
+
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_CertifactionInProgress_version05() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+ }
+
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncAdminDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_Certified_version10() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ // get to version 0.5
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+
+ }
+
+ // get version 1.0
+ RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_Certified_version20() throws Exception {
+ // addMandatoryArtifactsToService();
+ Map<String, String> origVersionsMap = new HashMap<String, String>();
+ // get to version 0.5
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ }
+
+ // get version 1.0
+ RestResponse changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ // get version 1.5
+ for (int x = 0; x < 4; x++) {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKIN);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(),
+ LifeCycleStatesEnum.CHECKOUT);
+ }
+
+ // get version 2.0
+ changeServiceState = LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ assertTrue("certify service request returned status:" + changeServiceState.getErrorCode(),
+ changeServiceState.getErrorCode() == 200);
+ origVersionsMap.put(serviceDetails.getVersion(), serviceDetails.getUniqueId());
+
+ // validate get response
+ RestResponse serviceGetResponse = ServiceRestUtils.getService(serviceDetails, sdncAdminDetails);
+ Service res = ResponseParser.convertServiceResponseToJavaObject(serviceGetResponse.getResponse());
+ Map<String, String> getVersionsMap = res.getAllVersions();
+ assertTrue(origVersionsMap.equals(getVersionsMap));
+ }
+
+ @Test
+ public void GetAllServiceVersions_ServiceNotFound() throws Exception {
+
+ RestResponse serviceGetResponse = ServiceRestUtils.getService("123456789", sdncAdminDetails);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name());
+ assertEquals("Check response code after get service without cache", errorInfo.getCode(),
+ serviceGetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList("123456789");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_NOT_FOUND.name(), variables,
+ serviceGetResponse.getResponse());
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java
new file mode 100644
index 0000000000..b84728a06c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetComponentAuditApiTest.java
@@ -0,0 +1,322 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.http.HttpStatus;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.Wrapper;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.JsonElement;
+
+import fj.data.Either;
+
+public class GetComponentAuditApiTest extends ComponentBaseTest {
+
+ public static final String SERVICES_API = "services";
+ public static final String RESOURCES_API = "resources";
+
+ protected User sdncAdminUser;
+ protected User sdncDesignerUser;
+ protected User sdncTesterUser;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetComponentAuditApiTest() {
+ super(name, GetComponentAuditApiTest.class.getName());
+ }
+
+ // in case tests fail, run this method as test to create mapping in ES
+ public void updateElasticSearchMapping() throws IOException {
+ Either<String, Exception> fileContentUTF8 = FileUtils.getFileContentUTF8("src\\test\\resources\\CI\\other\\mapping.json");
+ AssertJUnit.assertTrue(fileContentUTF8.isLeft());
+
+ final String ES_TEMPLATE_URL = "http://%s:%s/_template/audit_template";
+ String url = String.format(ES_TEMPLATE_URL, config.getEsHost(), config.getEsPort());
+
+ RestResponse sendHttpPost = new HttpRequest().sendHttpPost(url, fileContentUTF8.left().value(), null);
+ AssertJUnit.assertTrue(sendHttpPost.getErrorCode() == HttpStatus.SC_OK);
+ }
+
+ @BeforeMethod
+ public void init() {
+ sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncDesignerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ ;
+
+ }
+
+ @Test
+ public void testServiceAuditCertifiedVersion() throws Exception {
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+
+ createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, true);
+ // First Certification
+
+ LifecycleRestUtils.certifyService(serviceDetails);
+ // LCSbaseTest.certifyService(serviceDetails);
+ AssertJUnit.assertTrue(serviceDetails.getVersion().equals("1.0"));
+
+ // Second Certification
+ increaseServiceVersion(serviceDetails, "1.1");
+ increaseServiceVersion(serviceDetails, "1.2");
+ increaseServiceVersion(serviceDetails, "1.3");
+ increaseServiceVersion(serviceDetails, "1.4");
+ LifecycleRestUtils.certifyService(serviceDetails);
+ AssertJUnit.assertTrue(serviceDetails.getVersion().equals("2.0"));
+ String certifiedId = serviceDetails.getUniqueId();
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT);
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN);
+
+ JsonElement element = getAuditJson(SERVICES_API, certifiedId);
+ // audits kept: 5*check ins + 4*check outs + 2*artifact payload
+ // updates(tosca) + certification request + certification start +
+ // certification success
+ // + 3 A&AI(ArtifactDelete, ArtifactUpload, ArtifactUpdate)
+ AssertJUnit.assertTrue("expected: 17, actual: " + element.getAsJsonArray().size(), element.getAsJsonArray().size() == 17);
+
+ }
+
+ protected void certifyResource(ResourceReqDetails defaultResource) throws IOException {
+ RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncTesterUser, LifeCycleStatesEnum.STARTCERTIFICATION);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncTesterUser, LifeCycleStatesEnum.CERTIFY);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ }
+
+ protected JsonElement getAuditJson(String componentType, String componentId) throws IOException {
+ Map<String, String> headers = new HashMap<String, String>() {
+ {
+ put(Constants.USER_ID_HEADER, UserRoleEnum.ADMIN.getUserId());
+ }
+ };
+ String url = String.format(Urls.GET_COMPONENT_AUDIT_RECORDS, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId);
+
+ RestResponse httpSendGet = new HttpRequest().httpSendGet(url, headers);
+ AssertJUnit.assertTrue(httpSendGet.getErrorCode() == HttpStatus.SC_OK);
+ JsonElement element = ResponseParser.parseToObject(httpSendGet.getResponse(), JsonElement.class);
+ AssertJUnit.assertTrue(element.isJsonArray());
+ return element;
+ }
+
+ protected void createBasicServiceForAudit(Wrapper<String> versionZeroOneIDWrapper, Wrapper<String> versionZeroTwoIDWrapper, ServiceReqDetails serviceDetails, Boolean withResInst) throws Exception {
+
+ User designerUser = sdncDesignerUser;
+
+ RestResponse response = ServiceRestUtils.createService(serviceDetails, designerUser);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_CREATED);
+ versionZeroOneIDWrapper.setInnerElement(serviceDetails.getUniqueId());
+
+ if (withResInst) {
+ Resource resourceObj = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceObj, UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.changeComponentState(resourceObj, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ ResourceReqDetails resource = new ResourceReqDetails(resourceObj);
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+ resourceInstanceReqDetails.setComponentUid(resource.getUniqueId());
+ ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerUser, serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+
+ // ServiceUtils.createCertResourceWithDeploymentArt(serviceDetails,
+ // "myResource");
+ }
+
+ response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ AssertJUnit.assertTrue(serviceDetails.getVersion().equals("0.1"));
+
+ response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKOUT);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ // ServiceUtils.addServiceDeploymentArtifact(serviceDetails.getUniqueId(),
+ // designerUser);
+ versionZeroTwoIDWrapper.setInnerElement(serviceDetails.getUniqueId());
+ AssertJUnit.assertTrue(serviceDetails.getVersion().equals("0.2"));
+ response = LifecycleRestUtils.changeServiceState(serviceDetails, designerUser, LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+
+ increaseServiceVersion(serviceDetails, "0.3");
+
+ increaseServiceVersion(serviceDetails, "0.4");
+
+ increaseServiceVersion(serviceDetails, "0.5");
+
+ }
+
+ protected void increaseServiceVersion(ServiceReqDetails serviceDetails, String excpectedVersion) throws Exception {
+ RestResponse response = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ AssertJUnit.assertTrue(serviceDetails.getVersion().equals(excpectedVersion));
+ response = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ }
+
+ protected void createBasicResourceForAudit(Wrapper<String> versionOnePointTwoIDWrapper, ResourceReqDetails defaultResource) throws Exception {
+
+ RestResponse response = ResourceRestUtils.createResource(defaultResource, sdncDesignerUser);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_CREATED);
+
+ // ArtifactDefinition artifactDef = new
+ // ArtifactUtils().constructDefaultArtifactInfo();
+ // response = resourceUtils.add_artifact(defaultResource,
+ // sdncDesignerUser, defaultResource.getVersion(), artifactDef);
+ // assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerUser, defaultResource.getUniqueId());
+ AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(), response.getErrorCode() == 200);
+
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN);
+
+ increaseResourceVersion(defaultResource, "0.2");
+
+ increaseResourceVersion(defaultResource, "0.3");
+
+ increaseResourceVersion(defaultResource, "0.4");
+
+ increaseResourceVersion(defaultResource, "0.5");
+
+ certifyResource(defaultResource);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ AssertJUnit.assertTrue(defaultResource.getVersion().equals("1.0"));
+
+ increaseResourceVersion(defaultResource, "1.1");
+
+ increaseResourceVersion(defaultResource, "1.2");
+ versionOnePointTwoIDWrapper.setInnerElement(defaultResource.getUniqueId());
+
+ increaseResourceVersion(defaultResource, "1.3");
+
+ increaseResourceVersion(defaultResource, "1.4");
+
+ }
+
+ protected void increaseResourceVersion(ResourceReqDetails defaultResource, String expectedVersion) throws IOException {
+ RestResponse response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, LifeCycleStatesEnum.CHECKOUT);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ AssertJUnit.assertTrue(defaultResource.getVersion().equals(expectedVersion));
+ response = LifecycleRestUtils.changeResourceState(defaultResource, sdncDesignerUser, LifeCycleStatesEnum.CHECKIN);
+ AssertJUnit.assertTrue(response.getErrorCode() == HttpStatus.SC_OK);
+ }
+
+ @Test
+ public void testServiceAuditLastUncertifiedVersion() throws Exception {
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+
+ createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false);
+
+ JsonElement element = getAuditJson(SERVICES_API, versionZeroTwoIDWrapper.getInnerElement());
+
+ assertTrue(element.getAsJsonArray().size() == 3);
+
+ }
+
+ @Test
+ public void testServiceAuditFirstUncertifiedVersion() throws Exception {
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ Wrapper<String> versionZeroOneIDWrapper = new Wrapper<String>(), versionZeroTwoIDWrapper = new Wrapper<String>();
+
+ createBasicServiceForAudit(versionZeroOneIDWrapper, versionZeroTwoIDWrapper, serviceDetails, false);
+
+ JsonElement element = getAuditJson(SERVICES_API, versionZeroOneIDWrapper.getInnerElement());
+
+ assertTrue(element.getAsJsonArray().size() == 3);
+
+ }
+
+ @Test
+ public void testResourceAuditUncertifiedVersion() throws Exception {
+
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResource();
+ Wrapper<String> versionOnePointTwoIDWrapper = new Wrapper<String>();
+
+ createBasicResourceForAudit(versionOnePointTwoIDWrapper, defaultResource);
+
+ JsonElement element = getAuditJson(RESOURCES_API, versionOnePointTwoIDWrapper.getInnerElement());
+
+ assertTrue(element.getAsJsonArray().size() == 3);
+
+ }
+
+ @Test
+ public void testResourceAuditCertifiedVersion() throws Exception {
+
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResource();
+ Wrapper<String> versionOnePointTwoIDWrapper = new Wrapper<String>();
+
+ createBasicResourceForAudit(versionOnePointTwoIDWrapper, defaultResource);
+
+ certifyResource(defaultResource);
+ assertTrue(defaultResource.getVersion().equals("2.0"));
+ String certifiedId = defaultResource.getUniqueId();
+
+ increaseResourceVersion(defaultResource, "2.1");
+
+ increaseResourceVersion(defaultResource, "2.2");
+
+ JsonElement element = getAuditJson(RESOURCES_API, certifiedId);
+
+ assertTrue(element.getAsJsonArray().size() == 13);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java
new file mode 100644
index 0000000000..19bed4d380
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/GetServiceLatestVersionTest.java
@@ -0,0 +1,684 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_RESTRICTED_OPERATION;
+import static org.testng.AssertJUnit.assertNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+public class GetServiceLatestVersionTest extends ComponentInstanceBaseTest {
+
+ protected ArtifactReqDetails heatArtifactDetails;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetServiceLatestVersionTest() {
+ super(name, GetServiceLatestVersionTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+ initMembers();
+ createAtomicResource(resourceDetailsVFC_01);
+ changeResourceStateToCertified(resourceDetailsVFC_01);
+ createAtomicResource(resourceDetailsCP_01);
+ changeResourceStateToCertified(resourceDetailsCP_01);
+ createAtomicResource(resourceDetailsVL_01);
+ changeResourceStateToCertified(resourceDetailsVL_01);
+ createVF(resourceDetailsVF_01);
+ certifyVf(resourceDetailsVF_01);
+ createService(serviceDetails_01);
+ createService(serviceDetails_02);
+ createService(serviceDetails_03);
+ createProduct(productDetails_01);
+ createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails); // create
+ // certified
+ // VF
+ // instance
+ // in
+ // service
+ /*
+ * RestResponse restResponse =
+ * LifecycleRestUtils.changeServiceState(serviceDetails_01,
+ * sdncDesignerDetails, LifeCycleStates.CHECKIN);
+ * ResourceRestUtils.checkSuccess(restResponse);
+ */
+ }
+
+ public void initMembers() throws Exception {
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ sdncPsDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1);
+ sdncPmDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1);
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ resourceDetailsVFC_01 = ElementFactory.getDefaultResourceByType("VFC100", NormativeTypesEnum.COMPUTE,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VFC.toString()); // resourceType = VFC
+ resourceDetailsVF_01 = ElementFactory.getDefaultResourceByType("VF100", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VF.toString());
+ resourceDetailsCP_01 = ElementFactory.getDefaultResourceByType("CP100", NormativeTypesEnum.PORT,
+ ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.CP.toString());
+ resourceDetailsVL_01 = ElementFactory.getDefaultResourceByType("VL100", NormativeTypesEnum.NETWORK,
+ ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VL.toString());
+ serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY,
+ sdncDesignerDetails.getUserId());
+ serviceDetails_02 = ElementFactory.getDefaultService("newtestservice2", ServiceCategoriesEnum.MOBILITY,
+ sdncDesignerDetails.getUserId());
+ serviceDetails_03 = ElementFactory.getDefaultService("newtestservice3", ServiceCategoriesEnum.MOBILITY,
+ sdncDesignerDetails.getUserId());
+ productDetails_01 = ElementFactory.getDefaultProduct("product01");
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceInCheckOutState() throws Exception {
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPsDetails1);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertNull("No Service returned, one service in checkout state 0.1", servcieFromList);
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceInCheckInState() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPsDetails1);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ }
+
+ @Test
+ public void getServicesLatestVersionByPm() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncPmDetails1);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ }
+
+ @Test
+ public void getServicesLatestVersionByAdmin() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncAdminDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ }
+
+ @Test
+ public void getServicesLatestVersionService02CheckOutState() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ String serviceUniqueID = ResponseParser.getUniqueIdFromResponse(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueID);
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertNull(servcieFromList);
+ }
+
+ @Test
+ public void getServicesLatestVersionService02CheckInState() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.2"));
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceWaitingForCertification() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.2"));
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceCertificationInProgress() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.2"));
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceCertificationFail() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.FAILCERTIFICATION);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.2"));
+ }
+
+ @Test
+ public void getServicesLatestVersionServiceCertifed() throws Exception {
+ certifyService(serviceDetails_01);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("1.0"));
+ }
+
+ @Test
+ public void getLatestVersionServiceHasSeveralCertifedVersion_01() throws Exception {
+ RestResponse certifyServiceResponse;
+ String serviceUniqueIdFromResponse = null;
+ int numberOfCertifiedService = 3;
+ for (int i = 0; i < numberOfCertifiedService; i++) {
+ certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ if (i == (numberOfCertifiedService - 1)) {
+ serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(certifyServiceResponse);
+ }
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ }
+ // We have service with following versions : 1.0, 2.0 ,3.0 and
+ // 3.1(checkedOut)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse);
+ assertTrue(servcieFromList.getVersion().equals("3.0"));
+ }
+
+ @Test
+ public void getLatestVersionServiceHasSeveralCertifedVersions02() throws Exception {
+ RestResponse certifyServiceResponse;
+ certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ // We have service with following versions : 1.0, 2.0
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("2.0"));
+ }
+
+ @Test
+ public void getLatestVersionServiceCertifedWasCheckedOutAndCheckedin() throws Exception {
+ RestResponse certifyServiceResponse;
+ int numberOfCertifiedService = 3;
+ for (int i = 0; i < numberOfCertifiedService; i++) {
+ certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ }
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ // We have service with following versions : 1.0, 2.0 and 2.1(checkedIn)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("3.1"));
+ }
+
+ @Test
+ public void getLatestVersionServiceCheckOutCertifedService() throws Exception {
+ RestResponse restResponse;
+ String serviceUniqueIdFromResponse = null;
+ RestResponse certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ for (int i = 0; i < 11; i++) {
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ if (i == (10)) {
+ serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse);
+ }
+ }
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ // We have service with following versions : 1.0 and 1.11(Check-out)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse);
+ assertTrue(servcieFromList.getVersion().equals("1.11"));
+ }
+
+ @Test
+ public void getLatestVersionServiceCheckOutCheckInCertifedService() throws Exception {
+ RestResponse restResponse;
+ String serviceUniqueIdFromResponse = null;
+ RestResponse certifyServiceResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(certifyServiceResponse);
+ for (int i = 0; i < 12; i++) {
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ if (i == (11)) {
+ serviceUniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse);
+ }
+ }
+ // We have service with following versions : 1.0 and 1.11(Check-out)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceUniqueIdFromResponse);
+ assertTrue(servcieFromList.getVersion().equals("1.12"));
+ }
+
+ @Test
+ public void getLatestVersionServiceCertifedCheckedOutAndInWaitingForCertificationState() throws Exception {
+ certifyService(serviceDetails_01); // 1.0
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ServiceRestUtils.checkSuccess(restResponse);
+ // We have service with following versions : 1.0 and 1.1(Waiting For
+ // Certification)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("1.1"));
+ }
+
+ @Test
+ public void getLatestVersionServiceCertifedCheckedOutAndInCertificationInProgressState() throws Exception {
+ certifyService(serviceDetails_01); // 1.0
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ServiceRestUtils.checkSuccess(restResponse);
+ // We have service with following versions : 1.0 and 1.1(Certification
+ // In Progress)
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("1.1"));
+ }
+
+ // DE190818
+ @Test(enabled = false)
+ public void getLatestVersionByNonAsdcUser() throws Exception {
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ nonAsdcUser.setUserId("gg750g");
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(nonAsdcUser);
+ assertTrue(getServicesLatestVersion.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ getServicesLatestVersion.getResponse());
+ }
+
+ // DE190818
+ @Test(enabled = false)
+ public void getLatestVersionUserIdIsEmpty() throws Exception {
+ User nonAsdcUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ nonAsdcUser.setUserId("");
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(nonAsdcUser);
+ assertTrue(getServicesLatestVersion.getErrorCode() == STATUS_CODE_RESTRICTED_OPERATION);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_OPERATION.name(), new ArrayList<String>(),
+ getServicesLatestVersion.getResponse());
+ }
+
+ @Test
+ public void getServicesLatestVersionByTester() throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncTesterDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 1);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_01.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ }
+
+ @Test
+ public void getLatestVersionSeveralServicesInDifferentVersion() throws Exception {
+ RestResponse restResponse = certifyService(serviceDetails_01); // 1.0
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = certifyService(serviceDetails_01);
+ ServiceRestUtils.checkSuccess(restResponse);
+ String service1_UniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_01
+ // version is 2.1
+ // (check-out)
+
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_02, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_02
+ // version 0.2
+ // (Check-in)
+
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ String service3_UniqueIdFromResponse = ResponseParser.getUniqueIdFromResponse(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails_03, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse); // serviceDetails_03
+ // version 0.2
+ // (Check-out)
+
+ RestResponse getServicesLatestVersion = ServiceRestUtils.getServiceLatestVersionList(sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(getServicesLatestVersion);
+ List<Service> serviceList = restResponseToResourceObjectList(getServicesLatestVersion);
+ assertTrue(serviceList.size() == 3);
+ Service servcieFromList = getResourceObjectFromResourceListByUid(serviceList, service1_UniqueIdFromResponse);
+ assertTrue(servcieFromList.getVersion().equals("2.0"));
+ servcieFromList = getResourceObjectFromResourceListByUid(serviceList, serviceDetails_02.getUniqueId());
+ assertTrue(servcieFromList.getVersion().equals("0.2"));
+ servcieFromList = getResourceObjectFromResourceListByUid(serviceList, service3_UniqueIdFromResponse);
+ assertTrue(servcieFromList.getVersion().equals("0.1"));
+ }
+
+ ///////////////////////////////////////////////////////////////
+ private RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKOUT);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ ServiceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeServiceState(serviceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ ServiceRestUtils.checkSuccess(restResponse);
+ return restResponse;
+ }
+
+ protected List<Service> restResponseToResourceObjectList(RestResponse restResponse) {
+ JsonElement jelement = new JsonParser().parse(restResponse.getResponse());
+ JsonArray jsonArray = jelement.getAsJsonArray();
+ List<Service> restResponseArray = new ArrayList<>();
+ Service service = null;
+ for (int i = 0; i < jsonArray.size(); i++) {
+ String serviceString = (String) jsonArray.get(i).toString();
+ service = ResponseParser.convertServiceResponseToJavaObject(serviceString);
+ restResponseArray.add(service);
+ }
+ return restResponseArray;
+ }
+
+ protected Service getResourceObjectFromResourceListByUid(List<Service> serviceList, String uid) {
+ if (serviceList != null && serviceList.size() > 0) {
+ for (Service service : serviceList) {
+ if (service.getUniqueId().equals(uid))
+ return service;
+ }
+ } else
+ return null;
+ return null;
+ }
+
+ private RestResponse changeResourceStateToCertified(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponse;
+ if (restResponse.getErrorCode() == 200) {
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetails, sdncTesterDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponse.getErrorCode() == 200) {
+ String newVersion = ResponseParser.getVersionFromResponse(restResponse);
+ resourceDetails.setVersion(newVersion);
+ resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resourceDetails.setLastUpdaterUserId(sdncTesterDetails.getUserId());
+ resourceDetails.setLastUpdaterFullName(sdncTesterDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getValueFromJsonResponse(restResponse.getResponse(),
+ "uniqueId");
+ resourceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponse;
+ }
+
+ // private void certifyVf(ResourceReqDetails resource) throws Exception {
+ // RestResponse createAtomicResourceInstance =
+ // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_01,
+ // sdncDesignerDetails);
+ // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ // createAtomicResourceInstance =
+ // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01,
+ // sdncDesignerDetails);
+ // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ // createAtomicResourceInstance =
+ // createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01,
+ // sdncDesignerDetails);
+ // ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ // //createVFInstanceDuringSetup(service, resource, sdncDesignerDetails);
+ // RestResponse response =
+ // ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails,
+ // sdncDesignerDetails, resource.getUniqueId());
+ // ResourceRestUtils.checkSuccess(response);
+ // RestResponse changeResourceStateToCertified =
+ // changeResourceStateToCertified(resource);
+ // ResourceRestUtils.checkSuccess(changeResourceStateToCertified);
+ // }
+
+ private void certifyVf(ResourceReqDetails resource) throws Exception {
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVFC_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String computeCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resource, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String vlCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ // Fixing Vl/Cp req/cap
+ ComponentTypeEnum containerCompType = ComponentTypeEnum.RESOURCE;
+ User user = sdncDesignerDetails;
+ fulfillCpRequirement(resource, cpCompInstId, computeCompInstId, computeCompInstId, user, containerCompType);
+ consumeVlCapability(resource, cpCompInstId, vlCompInstId, cpCompInstId, user, containerCompType);
+
+ RestResponse response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails,
+ sdncDesignerDetails, resource.getUniqueId());
+ ResourceRestUtils.checkSuccess(response);
+ RestResponse changeResourceStateToCertified = changeResourceStateToCertified(resource);
+ ResourceRestUtils.checkSuccess(changeResourceStateToCertified);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java
new file mode 100644
index 0000000000..c21deafcd8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ReqCapOccurrencesTest.java
@@ -0,0 +1,1191 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+
+import org.apache.http.client.ClientProtocolException;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.general.ImportUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ReqCapOccurrencesTest extends ComponentInstanceBaseTest {
+
+ private ImportReqDetails importReqDetails1; // atomic resource
+ private ImportReqDetails importReqDetails2;
+ private ImportReqDetails importReqDetails3;
+ private ImportReqDetails importReqDetails4;
+ private Resource resourceVFC1;
+ private Resource resourceVFC2;
+ private Resource resourceVFC3;
+ private Resource resourceVFC4;
+ private ResourceReqDetails resourceDetailsVF100;
+ private ResourceReqDetails resourceDetailsVF200;
+ private Resource resourceVF100;
+ private Resource resourceVF200;
+ protected String testResourcesPath;
+
+ protected final String importYmlWithReq11 = "softwareComponentReq11.yml";
+ protected final String importYmlWithReq12 = "softwareComponentReq12.yml";
+ protected final String importYmlWithCap11 = "computeCap11.yml";
+ protected final String importYmlWithCap1Unbounded = "computeCap1UNBOUNDED.yml";
+ protected final String capabilitiesAndRequirementsType = "tosca.capabilities.Container";
+
+ public ReqCapOccurrencesTest() {
+ super(new TestName(), ReqCapOccurrencesTest.class.getSimpleName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+ // Do not use call init() from ComponentInstanceBaseTest
+ expectedContainerCapabilities = new LinkedHashMap<String, List<CapabilityDefinition>>();
+ expectedContainerRequirements = new LinkedHashMap<String, List<RequirementDefinition>>();
+ removedRequirements = new HashMap<>();
+ expectedContInstReqCap = new HashMap<>();
+
+ RestResponse importResourceResponse;
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // import yml file location
+ String sourceDir = config.getResourceConfigDir();
+ final String workDir = "importToscaResourceByCreateUrl";
+ testResourcesPath = sourceDir + File.separator + workDir;
+ ///// Create atomic resources /////////////////////////
+ // import VFC1 with Requirements : MIN=1 MAX=2
+ ///// (tosca.capabilities.Container)
+ importReqDetails1 = ElementFactory.getDefaultImportResource("VFC1");
+ importResourceResponse = importedResource(importReqDetails1, importYmlWithReq12);
+ // resourceVFC1 =
+ // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(importReqDetails1, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ resourceVFC1 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ // import VFC2 with Capabilities : MIN 1 MAX UNBOUNDED
+ // (tosca.capabilities.Container)
+ importReqDetails2 = ElementFactory.getDefaultImportResource("VFC2");
+ importResourceResponse = importedResource(importReqDetails2, importYmlWithCap1Unbounded);
+ // resourceVFC2 =
+ // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ restResponse = LifecycleRestUtils.changeResourceState(importReqDetails2, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ resourceVFC2 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ // import VFC3 with Capabilities : MIN 1 MAX 1
+ // (tosca.capabilities.Container)
+ importReqDetails3 = ElementFactory.getDefaultImportResource("VFC3");
+ importResourceResponse = importedResource(importReqDetails3, importYmlWithCap11);
+ // resourceVFC3 =
+ // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ restResponse = LifecycleRestUtils.changeResourceState(importReqDetails3, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ resourceVFC3 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ // import VFC4 with Requirements : MIN 1 MAX 1
+ // (tosca.capabilities.Container)
+ importReqDetails4 = ElementFactory.getDefaultImportResource("VFC4");
+ importResourceResponse = importedResource(importReqDetails4, importYmlWithReq11);
+ // resourceVFC4 =
+ // ResponseParser.convertResourceResponseToJavaObject(importResourceResponse.getResponse());
+ restResponse = LifecycleRestUtils.changeResourceState(importReqDetails4, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ resourceVFC4 = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+
+ // create VF100
+ resourceDetailsVF100 = ElementFactory.getDefaultResourceByType("VF1000", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VF.toString());
+ RestResponse createResourceVF100 = ResourceRestUtils.createResource(resourceDetailsVF100, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceVF100);
+ // create VF200
+ resourceDetailsVF200 = ElementFactory.getDefaultResourceByType("VF2000", NormativeTypesEnum.ROOT,
+ ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, sdncDesignerDetails.getUserId(),
+ ResourceTypeEnum.VF.toString());
+ RestResponse createResourceVF200 = ResourceRestUtils.createResource(resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createResourceVF200);
+ // Create Service
+ serviceDetails_01 = ElementFactory.getDefaultService("newtestservice1", ServiceCategoriesEnum.MOBILITY,
+ sdncDesignerDetails.getUserId());
+ RestResponse createServiceRestResponse = ServiceRestUtils.createService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createServiceRestResponse);
+
+ }
+
+ // US628514 Capability/Requirement "Occurrences" attribute in CREATE/DELETE
+ // Relation APIs
+ // Container = SERVICE , Container instance = VF
+ @Test
+ public void capAndReqOccurrencesInServiceAndHisInstancesNoAssociation() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC21 (Cap MIN=1 MAX=UNBOUNDED) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "1";
+ String containerMaxReq = "2";
+ String containerMinCap = "1";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test
+ public void serviceInstanceAssociationReqMaxOccurrencesNotReached() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test
+ public void serviceInstanceAssociationReqMaxOccurrencesIsReached() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test
+ public void associateServiceInstanceWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC2 (Cap MIN=1 MAX=UNBOUNDED) to VF2.00
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // associate same instances again - when requirement Max Occurrences
+ // reached
+ associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails,
+ serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND,
+ associateInstances.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(vf1Name);
+ varibales.add(vf2Name);
+ varibales.add("host");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(), varibales,
+ associateInstances.getResponse());
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test
+ public void serviceInstanceAssociationCapMaxOccurrencesIsReached() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test
+ public void associationServiceInstanceWhenCapMaxOccurrencesAlreadyReached() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ // RestResponse createVFInstResp = createVFInstance(serviceDetails_01,
+ // resourceDetailsVF100, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ // createVFInstResp = createVFInstance(serviceDetails_01,
+ // resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ // associate same instances again - when requirement Max Occurrences
+ // reached
+ associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails,
+ serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND,
+ associateInstances.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(vf1Name);
+ varibales.add(vf2Name);
+ varibales.add("host");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(),
+ varibales, associateInstances.getResponse());
+ }
+
+ @Test
+ public void associationAndDisassociateServiceInstancesWhenReqMaxOccurrencesAlreadyReached()
+ throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC4 (Req MIN=1 MAX=1) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ RestResponse createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ sdncDesignerDetails);
+ // RestResponse createVFInstResp = createVFInstance(serviceDetails_01,
+ // resourceDetailsVF100, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ // createVFInstResp = createVFInstance(serviceDetails_01,
+ // resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VF Instances
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ // Disassociate 2 VF Instances
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS,
+ dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF100.getUniqueId()).isEmpty());
+ // get service and verify Occurrences in container and container
+ // instance requirements and Capabilities
+ getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ containerMinReq = "1";
+ containerMaxReq = "1";
+ containerMinCap = "1";
+ containerMaxCap = "1";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ }
+
+ @Test(enabled = false)
+ public void aaaa() throws Exception, Exception {
+ RestResponse getResourseRestResponse;
+ // Add instance of VFC1 (Req MIN=1 MAX=2) to VF1000
+ ComponentInstance componentInstanceReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceReq);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Add instance of VFC3 (Cap MIN=1 MAX=1) to VF2000
+ ComponentInstance componentInstanceCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF200);
+ assertNotNull(componentInstanceCap);
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF200.getUniqueId());
+ resourceVF200 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Check-In both VFs
+ RestResponse restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF100, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ restResponse = LifecycleRestUtils.changeResourceState(resourceDetailsVF200, sdncDesignerDetails,
+ LifeCycleStatesEnum.CHECKIN);
+ ResourceRestUtils.checkSuccess(restResponse);
+ // Create VF instances
+ // RestResponse createVFInstResp =
+ // createVFInstanceDuringSetup(serviceDetails_01, resourceDetailsVF100,
+ // sdncDesignerDetails);
+ RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF100, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf1Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // createVFInstResp = createVFInstanceDuringSetup(serviceDetails_01,
+ // resourceDetailsVF200, sdncDesignerDetails);
+ createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF200, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String vf2Name = ResponseParser.getValueFromJsonResponse(createVFInstResp.getResponse(), "name");
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // associate 2 VFs
+ String capType = capabilitiesAndRequirementsType;
+ String reqName = "host";
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList, componentInstanceReq.getUniqueId(), componentInstanceCap.getUniqueId());
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+ // get service
+ RestResponse getServiceResponse = ServiceRestUtils.getService(serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getServiceResponse);
+ Service service = ResponseParser.parseToObjectUsingMapper(getServiceResponse.getResponse(), Service.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType, containerMinReq,
+ containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(service, capabilitiesAndRequirementsType,
+ resourceVF200, resourceVF100);
+ // associate same instances again - when requirement Max Occurrences
+ // reached
+ associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails,
+ serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND,
+ associateInstances.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(vf1Name);
+ varibales.add(vf2Name);
+ varibales.add("host");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(),
+ varibales, associateInstances.getResponse());
+ }
+
+ //////////////////////////////////////////////////////////////////////////////////////////////////
+ // US628514 Capability/Requirement "Occurrences" attribute in CREATE/DELETE
+ ////////////////////////////////////////////////////////////////////////////////////////////////// Relation
+ ////////////////////////////////////////////////////////////////////////////////////////////////// APIs
+ // Container = VF , Container instance = VFC
+ @Test
+ public void capAndReqOccurrencesInVfAndHisInstancesNoAssociation() throws Exception, Exception {
+ // Add VFC1 and VFC2 instances in VF
+ ComponentInstance createComponentInstance1 = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(createComponentInstance1);
+ ComponentInstance createComponentInstance2 = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(createComponentInstance2);
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "1";
+ String containerMaxReq = "2";
+ String containerMinCap = "1";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC2, resourceVFC1);
+ }
+
+ @Test
+ public void vfInstanceAssociationReqMaxOccurrencesNotReached() throws Exception, Exception {
+ // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=2) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1,
+ // MAX=UNBOUNDED ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC2, resourceVFC1);
+
+ }
+
+ @Test
+ public void vfInstanceAssociationReqMaxOccurrencesIsReached() throws Exception, Exception {
+ // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=1) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1,
+ // MAX=UNBOUNDED ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC2, resourceVFC4);
+ }
+
+ @Test
+ public void associateVfInstanceWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception {
+ // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=1) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC2 (with Capabilities: tosca.capabilities.Container, MIN=1,
+ // MAX=UNBOUNDED ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails2, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "UNBOUNDED";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC2, resourceVFC4);
+ // associate same instances again - when requirement Max Occurrences
+ // reached
+ associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND,
+ associateInstances.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(componentInstanceWithReq.getName());
+ varibales.add(componentInstanceWithCap.getName());
+ varibales.add("host");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND.name(), varibales,
+ associateInstances.getResponse());
+
+ }
+
+ @Test
+ public void vfInstanceAssociationCapMaxOccurrencesIsReached() throws Exception, Exception {
+ // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=2) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1
+ // MAX=1 ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC3, resourceVFC1);
+ }
+
+ @Test
+ public void associationVfInstanceWhenCapMaxOccurrencesAlreadyReached() throws Exception, Exception {
+ // Add VFC1 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=2) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails1, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1
+ // MAX=1 ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", STATUS_CODE_SUCCESS, associateInstances.getErrorCode().intValue());
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "1";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC3, resourceVFC1);
+ // associate same instances again - when requirement Max Occurrences
+ // reached
+ associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_NOT_FOUND,
+ associateInstances.getErrorCode().intValue());
+ ArrayList<String> varibales = new ArrayList<String>();
+ varibales.add(componentInstanceWithReq.getName());
+ varibales.add(componentInstanceWithCap.getName());
+ varibales.add("host");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND.name(),
+ varibales, associateInstances.getResponse());
+ }
+
+ @Test
+ public void associationAndDisassociateVfInstancesWhenReqMaxOccurrencesAlreadyReached() throws Exception, Exception {
+ // Add VFC4 (with Requirements: tosca.capabilities.Container, MIN=1
+ // MAX=1) instance to VF
+ ComponentInstance componentInstanceWithReq = createComponentInstance(importReqDetails4, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithReq);
+ // Add VFC3 (with Capabilities: tosca.capabilities.Container, MIN=1
+ // MAX=1 ) instance to VF
+ ComponentInstance componentInstanceWithCap = createComponentInstance(importReqDetails3, sdncDesignerDetails,
+ resourceDetailsVF100);
+ assertNotNull(componentInstanceWithCap);
+ // associate Instances
+ CapReqDef capReqDefBeforeAssociate = getResourceReqCap(resourceDetailsVF100);
+ RequirementCapabilityRelDef requirementDef = setRelationshipBetweenInstances(componentInstanceWithReq,
+ componentInstanceWithCap, capReqDefBeforeAssociate);
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ assertTrue(checkRealtionship(requirementDef.getFromNode(), requirementDef.getToNode(),
+ resourceDetailsVF100.getUniqueId()));
+ // GET resource
+ RestResponse getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ String containerMinReq = "0";
+ String containerMaxReq = "0";
+ String containerMinCap = "0";
+ String containerMaxCap = "0";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC3, resourceVFC4);
+ // Disassociate 2 Instances
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ sdncDesignerDetails, resourceDetailsVF100.getUniqueId(), ComponentTypeEnum.RESOURCE);
+ assertEquals("Check response code ", BaseRestUtils.STATUS_CODE_SUCCESS,
+ dissociateInstances.getErrorCode().intValue());
+ assertTrue(getComponentInstancesRelations(resourceDetailsVF100.getUniqueId()).isEmpty());
+ // GET resource
+ getResourseRestResponse = ResourceRestUtils.getResource(sdncDesignerDetails,
+ resourceDetailsVF100.getUniqueId());
+ resourceVF100 = ResponseParser.parseToObjectUsingMapper(getResourseRestResponse.getResponse(), Resource.class);
+ // Verify Container requirements and Capabilities
+ containerMinReq = "1";
+ containerMaxReq = "1";
+ containerMinCap = "1";
+ containerMaxCap = "1";
+ verifyContainerCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ containerMinReq, containerMaxReq, containerMinCap, containerMaxCap);
+ verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(resourceVF100, capabilitiesAndRequirementsType,
+ resourceVFC3, resourceVFC4);
+ }
+
+ ///////////////////////////////////////
+
+ private boolean checkRealtionship(String fromNode, String toNode, String resourceUniqueId) throws Exception {
+ List<RequirementCapabilityRelDef> componentInstancesRelations = getComponentInstancesRelations(
+ resourceUniqueId);
+ RequirementCapabilityRelDef requirementCapabilityRelDef = componentInstancesRelations.get(0);
+ boolean fromNodeCheck = requirementCapabilityRelDef.getFromNode().equals(fromNode);
+ boolean toNodeCheck = requirementCapabilityRelDef.getToNode().equals(toNode);
+
+ return fromNodeCheck && toNodeCheck;
+ }
+
+ private List<RequirementCapabilityRelDef> getComponentInstancesRelations(String resourceUniqueId)
+ throws ClientProtocolException, IOException {
+ Resource resource = getVfAsResourceObject(resourceUniqueId);
+ List<RequirementCapabilityRelDef> componenRelationInstances = resource.getComponentInstancesRelations();
+
+ return componenRelationInstances;
+ }
+
+ private Resource getVfAsResourceObject(String resourceUniqueId) throws ClientProtocolException, IOException {
+ RestResponse getResource = ResourceRestUtils.getResource(resourceUniqueId);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(getResource.getResponse(), Resource.class);
+ return resource;
+ }
+
+ private RequirementCapabilityRelDef setRelationshipBetweenInstances(ComponentInstance riReq,
+ ComponentInstance riCap, CapReqDef capReqDef) throws Exception {
+
+ String capbilityUid = capReqDef.getCapabilities().get("tosca.capabilities.Container").get(0).getUniqueId();
+ String requirementUid = capReqDef.getRequirements().get("tosca.capabilities.Container").get(0).getUniqueId();
+
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(riReq.getUniqueId());
+ requirementDef.setToNode(riCap.getUniqueId());
+
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(riReq.getUniqueId());
+ pair.setCapabilityOwnerId(riCap.getUniqueId());
+ pair.setRequirement("host");
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType("tosca.capabilities.Container");
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capbilityUid);
+ pair.setRequirementUid(requirementUid);
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+ return requirementDef;
+ }
+
+ private CapReqDef getResourceReqCap(ResourceReqDetails res) throws IOException {
+ RestResponse getResourceBeforeAssociate = ComponentRestUtils
+ .getComponentRequirmentsCapabilities(sdncDesignerDetails, resourceDetailsVF100);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceBeforeAssociate.getResponse(), CapReqDef.class);
+ return capReqDef;
+ }
+
+ private RestResponse importedResource(ImportReqDetails importReqDetails, String ymlFile) throws Exception {
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, testResourcesPath,
+ ymlFile);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails,
+ sdncDesignerDetails, null);
+ assertEquals("Check response code after importing resource", BaseRestUtils.STATUS_CODE_CREATED,
+ importResourceResponse.getErrorCode().intValue());
+ return importResourceResponse;
+ }
+
+ private ComponentInstance createComponentInstance(ResourceReqDetails res, User user, ResourceReqDetails vf)
+ throws Exception {
+ RestResponse response = ResourceRestUtils.createResourceInstance(res, user, vf.getUniqueId());
+ ResourceRestUtils.checkCreateResponse(response);
+ ComponentInstance compInstance = ResponseParser.parseToObject(response.getResponse(), ComponentInstance.class);
+ return compInstance;
+ }
+
+ private void verifyContainerCapabilitiesAndRequirementsOccurrences(Component component,
+ String CapabilitiesAndRequirementsType, String minReqOccurrences, String maxReqOccurrences,
+ String minCapabilities, String maxCapabilities) throws Exception {
+ boolean isRequirementAppear = false;
+ boolean isCapabilityAppear = false;
+ List<RequirementDefinition> requirements;
+ List<CapabilityDefinition> capabilities;
+ requirements = component.getRequirements().get(CapabilitiesAndRequirementsType);
+ if (maxReqOccurrences == "0") {
+ assertTrue(requirements == null);
+ } // if container MAX requirement = 0
+ if (maxReqOccurrences != "0") {
+ assertNotNull(requirements);
+ for (RequirementDefinition req : requirements) {
+ switch (req.getName()) {
+ case "host":
+ assertTrue("Check Min Requirement Occurrences ", req.getMinOccurrences().equals(minReqOccurrences));
+ assertTrue("Check Max Requirement Occurrences ", req.getMaxOccurrences().equals(maxReqOccurrences));
+ isRequirementAppear = true;
+ break;
+ }
+ assertTrue(isRequirementAppear);
+ isRequirementAppear = false;
+ }
+ }
+ // Container Capabilities
+ capabilities = component.getCapabilities().get(CapabilitiesAndRequirementsType);
+ if (maxCapabilities == "0") {// if container MAX capabilities = 0
+ assertTrue(capabilities == null);
+ }
+ if (maxCapabilities != "0") {
+ assertNotNull(capabilities);
+ for (CapabilityDefinition cap : capabilities) {
+ switch (cap.getName()) {
+ case "host":
+ assertTrue("Check Min capability Occurrences ", cap.getMinOccurrences().equals(minCapabilities));
+ assertTrue("Check Max capability Occurrences ", cap.getMaxOccurrences().equals(maxCapabilities));
+ isCapabilityAppear = true;
+ break;
+ }
+ assertTrue(isCapabilityAppear);
+ isCapabilityAppear = false;
+ }
+ }
+
+ }
+
+ private void verifyContainerInstanceCapabilitiesAndRequirementsOccurrences(Component component,
+ String CapabilitiesAndRequirementsType, Resource vfWithCapabilities, Resource vfWithRequirements)
+ throws Exception {
+ boolean isCapReqAppear = false;
+ List<ComponentInstance> listOfComponentInstances = component.getComponentInstances();
+
+ for (ComponentInstance instance : listOfComponentInstances) {
+ if (instance.getComponentUid().equals(vfWithCapabilities.getUniqueId())) {
+ List<CapabilityDefinition> capFromResource = vfWithCapabilities.getCapabilities()
+ .get(CapabilitiesAndRequirementsType);
+ List<CapabilityDefinition> capFromInstance = instance.getCapabilities()
+ .get(CapabilitiesAndRequirementsType);
+ for (CapabilityDefinition resourceCap : capFromResource)
+ for (CapabilityDefinition instanceReq : capFromInstance) {
+ if (resourceCap.getUniqueId().equals(instanceReq.getUniqueId())) {
+ assertTrue("Check Min capability Occurrences ",
+ resourceCap.getMinOccurrences().equals(instanceReq.getMinOccurrences()));
+ assertTrue("Check Max capability Occurrences ",
+ resourceCap.getMaxOccurrences().equals(instanceReq.getMaxOccurrences()));
+ isCapReqAppear = true;
+ break;
+ }
+
+ }
+ }
+
+ if (instance.getComponentUid().equals(vfWithRequirements.getUniqueId())) {
+ List<RequirementDefinition> reqFromAtomicResource = vfWithRequirements.getRequirements()
+ .get(CapabilitiesAndRequirementsType);
+ List<RequirementDefinition> reqFromInstance = instance.getRequirements()
+ .get(CapabilitiesAndRequirementsType);
+ for (RequirementDefinition resourceReq : reqFromAtomicResource)
+ for (RequirementDefinition instanceReq : reqFromInstance) {
+ if (resourceReq.getUniqueId().equals(instanceReq.getUniqueId())) {
+ assertTrue("Check Min Requirement Occurrences ",
+ resourceReq.getMinOccurrences().equals(instanceReq.getMinOccurrences()));
+ assertTrue("Check Max Requirement Occurrences ",
+ resourceReq.getMaxOccurrences().equals(instanceReq.getMaxOccurrences()));
+ isCapReqAppear = true;
+ break;
+ }
+ }
+ }
+ assertTrue(isCapReqAppear);
+ isCapReqAppear = false;
+ }
+
+ }
+
+ private RequirementCapabilityRelDef getReqCapRelation(String reqCompInstId, String capCompInstId, String capType,
+ String reqName, List<CapabilityDefinition> capList, List<RequirementDefinition> reqList,
+ String vfc1UniqueId, String vfc2UniqueId) {
+ return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, vfc1UniqueId, vfc2UniqueId, capType,
+ reqName, capList, reqList);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
new file mode 100644
index 0000000000..b2728ea0da
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/ServiceComponentInstanceCRUDTest.java
@@ -0,0 +1,1624 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.codehaus.jettison.json.JSONException;
+import org.json.JSONArray;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentInstanceBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class ServiceComponentInstanceCRUDTest extends ComponentInstanceBaseTest {
+ private static Logger log = LoggerFactory.getLogger(ServiceComponentInstanceCRUDTest.class.getName());
+ private static final String SPACE_STRING = " ";
+ private static String REQUIREMENT_NAME = "host";
+ private static String CAPABILITY_TYPE = "tosca.capabilities.Container";
+
+ private String reqOwnerId;
+ private String capOwnerId;
+
+ public ServiceComponentInstanceCRUDTest() {
+ super(new TestName(), ServiceComponentInstanceCRUDTest.class.getSimpleName());
+ }
+
+ @BeforeMethod(alwaysRun = true)
+ public void before() throws Exception {
+ init();
+ createComponents();
+ }
+
+ private void createComponents() throws Exception {
+ createAtomicResource(resourceDetailsVFC_01);
+ createAtomicResource(resourceDetailsVFC_02);
+ createAtomicResource(resourceDetailsCP_01);
+ createAtomicResource(resourceDetailsVL_01);
+ createAtomicResource(resourceDetailsVL_02);
+ createVF(resourceDetailsVF_01);
+ createVF(resourceDetailsVF_02);
+ createService(serviceDetails_01);
+ certifyResource(resourceDetailsVFC_01);
+ certifyResource(resourceDetailsVFC_02);
+ RestResponse createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_01,
+ resourceDetailsVFC_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ reqOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+ createAtomicResourceInstance = createAtomicInstanceForVFDuringSetup(resourceDetailsVF_02, resourceDetailsVFC_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ capOwnerId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);// should
+ // be
+ // updated
+ // to
+ // getUniqueIdOfFirstInstance
+ // in
+ // service
+ // context
+ }
+
+ private void certifyResource(ResourceReqDetails resource) throws Exception {
+ changeResourceLifecycleState(resource, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ changeResourceLifecycleState(resource, sdncTesterDetails.getUserId(), LifeCycleStatesEnum.STARTCERTIFICATION);
+ changeResourceLifecycleState(resource, sdncTesterDetails.getUserId(), LifeCycleStatesEnum.CERTIFY);
+ }
+
+ private void changeResourceLifecycleState(ResourceReqDetails resourceDetails, String userUserId,
+ LifeCycleStatesEnum lifeCycleStates) throws Exception {
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, userUserId, lifeCycleStates);
+ LifecycleRestUtils.checkLCS_Response(response);
+ }
+
+ private void changeServiceLifecycleState(ServiceReqDetails serviceDetails, User user,
+ LifeCycleStatesEnum lifeCycleStates) throws Exception {
+ RestResponse response = LifecycleRestUtils.changeServiceState(serviceDetails, user, lifeCycleStates);
+ LifecycleRestUtils.checkLCS_Response(response);
+ }
+
+ private void createVFInstanceFailWithoutChangeState(ActionStatus actionStatus, List<String> variables,
+ ResourceReqDetails vfResource, User user, int errorCode) throws Exception {
+ RestResponse createVFInstanceSuccessfullyWithoutChangeStateResp = createVFInstance(serviceDetails_01,
+ vfResource, user);
+ checkErrorMessage(actionStatus, variables, errorCode, createVFInstanceSuccessfullyWithoutChangeStateResp);
+ }
+
+ private void createVFInstanceFail(ActionStatus actionStatus, List<String> variables, ResourceReqDetails vfResource,
+ User user, int errorCode) throws Exception, FileNotFoundException, JSONException {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, vfResource, user);
+ checkErrorMessage(actionStatus, variables, errorCode, createVFInstResp);
+ }
+
+ private void deleteVFInstanceFail(ActionStatus actionStatus, List<String> variables, ResourceReqDetails vfResource,
+ User user, int errorCode) throws Exception, FileNotFoundException, JSONException {
+ RestResponse deleteVFInstResp = deleteVFInstance(vfResource.getUniqueId(), serviceDetails_01, user);
+ checkErrorMessage(actionStatus, variables, errorCode, deleteVFInstResp);
+ }
+
+ private void createAtomicResourceInstanceFailWithoutChangeState(ActionStatus actionStatus, List<String> variables,
+ ResourceReqDetails atomicResource, User user, int errorCode)
+ throws Exception, FileNotFoundException, JSONException {
+ RestResponse createAtomicInstResp = createAtomicInstanceForService(serviceDetails_01, atomicResource, user);
+ checkErrorMessage(actionStatus, variables, errorCode, createAtomicInstResp);
+ }
+
+ private void createAtomicResourceInstanceFail(ActionStatus actionStatus, List<String> variables,
+ ResourceReqDetails atomicResource, User user, int errorCode)
+ throws Exception, FileNotFoundException, JSONException {
+ RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, atomicResource,
+ user);
+ checkErrorMessage(actionStatus, variables, errorCode, createAtomicInstResp);
+ }
+
+ private void deleteAtomicResourceInstanceFail(ActionStatus actionStatus, List<String> variables,
+ ResourceReqDetails atomicResource, User user, int errorCode)
+ throws Exception, FileNotFoundException, JSONException {
+ RestResponse deleteAtomicInstResp = deleteAtomicInstanceForService(atomicResource.getUniqueId(),
+ serviceDetails_01, user);
+ checkErrorMessage(actionStatus, variables, errorCode, deleteAtomicInstResp);
+ }
+
+ private void checkErrorMessage(ActionStatus actionStatus, List<String> variables, int errorCode,
+ RestResponse response) throws Exception {
+
+ log.debug(response.getResponse());
+ AssertJUnit.assertEquals(errorCode, response.getErrorCode().intValue());
+ ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), variables, response.getResponse());
+ }
+
+ private RestResponse createCheckedinVFInstance(ServiceReqDetails containerDetails,
+ ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(),
+ LifeCycleStatesEnum.CHECKIN);
+ return createVFInstance(containerDetails, compInstOriginDetails, modifier);
+ }
+
+ private RestResponse createCheckedinAtomicInstanceForService(ServiceReqDetails containerDetails,
+ ResourceReqDetails compInstOriginDetails, User modifier) throws Exception {
+ changeResourceLifecycleState(compInstOriginDetails, compInstOriginDetails.getCreatorUserId(),
+ LifeCycleStatesEnum.CHECKIN);
+ return createAtomicInstanceForService(containerDetails, compInstOriginDetails, modifier);
+ }
+
+ private void createVFInstanceAndAtomicResourceInstanceWithoutCheckin(ResourceReqDetails vf,
+ ResourceReqDetails atomicResource, User user) throws Exception {
+ RestResponse createVFInstance = createVFInstance(serviceDetails_01, vf, user);
+ ResourceRestUtils.checkCreateResponse(createVFInstance);
+ RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, atomicResource, user);
+ ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
+ }
+
+ private void createVFInstanceAndAtomicResourceInstanceSuccessully(ResourceReqDetails vf,
+ ResourceReqDetails atomicResource) throws Exception, IOException {
+ createVFInstanceAndAtomicResourceInstanceSuccessully(vf, atomicResource, sdncDesignerDetails);
+ }
+
+ private void createVFInstanceAndAtomicResourceInstanceSuccessully(ResourceReqDetails vf,
+ ResourceReqDetails atomicResource, User user) throws Exception, IOException {
+ changeResourceLifecycleState(vf, vf.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
+ changeResourceLifecycleState(atomicResource, atomicResource.getCreatorUserId(), LifeCycleStatesEnum.CHECKIN);
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(vf, atomicResource, user);
+ }
+
+ @Test
+ public void createVFInstanceSuccessfullyTest() throws Exception {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void createVFAndAtomicInstanceTest() throws Exception {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 4, 0);
+ }
+
+ @Test
+ public void deleteAtomicInstanceTest() throws Exception {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ // 1 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ // 2 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_01,
+ sdncDesignerDetails);
+ // 3 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsVL_02,
+ sdncDesignerDetails);
+ // 4 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ // To delete
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // 3 rel
+ createVFInstResp = deleteAtomicInstanceForService(compInstId, serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(createVFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 3, 0);
+ }
+
+ @Test
+ public void deleteVFInstanceTest() throws Exception {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ // 1 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ String compInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ // 2 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ createVFInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ // 3 rel
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ // 2 rel
+ createVFInstResp = deleteVFInstance(compInstId, serviceDetails_01, sdncDesignerDetails);
+ ResourceRestUtils.checkDeleteResponse(createVFInstResp);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void associateDissociateTwoVFs() throws Exception {
+
+ RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String fromCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String toCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+
+ String capType = CAPABILITY_TYPE;
+ String reqName = REQUIREMENT_NAME;
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(fromCompInstId, toCompInstId, capType, reqName,
+ capList, reqList);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<RequirementDefinition> list = capReqDef.getRequirements().get(capType);
+ AssertJUnit.assertEquals("Check requirement", null, list);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ list = capReqDef.getRequirements().get(capType);
+ AssertJUnit.assertEquals("Check requirement", 1, list.size());
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ private RequirementCapabilityRelDef getReqCapRelation(String reqCompInstId, String capCompInstId, String capType,
+ String reqName, List<CapabilityDefinition> capList, List<RequirementDefinition> reqList) {
+ return ElementFactory.getReqCapRelation(reqCompInstId, capCompInstId, reqOwnerId, capOwnerId, capType, reqName,
+ capList, reqList);
+ }
+
+ @Test
+ public void createResourceInstanceByDifferentDesignerTest() throws Exception {
+ createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
+ createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void createResourceInstanceByDifferentDesignerTest_ServiceIsCheckedin() throws Exception {
+ User designer2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, designer2, LifeCycleStatesEnum.CHECKOUT);
+
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01, designer2);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ }
+
+ @Test
+ public void createResourceInstanceByTester() throws Exception {
+ createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
+ createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void createResourceInstanceWithNotASDCUserTest() throws Exception {
+ sdncDesignerDetails.setUserId("ab0001");
+ createVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ sdncDesignerDetails, 409);
+ createAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, sdncDesignerDetails, 409);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void createResourceInstanceWithEmptyUserIdTest() throws Exception {
+ sdncDesignerDetails.setUserId("");
+ createVFInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList<String>(), resourceDetailsVF_01,
+ sdncDesignerDetails, 403);
+ createAtomicResourceInstanceFail(ActionStatus.MISSING_INFORMATION, new ArrayList<String>(),
+ resourceDetailsCP_01, sdncDesignerDetails, 403);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void createResourceInstanceWithEmptyServiceUidTest() throws Exception {
+ serviceDetails_01.setUniqueId("");
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ assertEquals(404, createVFInstResp.getErrorCode().intValue());
+ RestResponse createAtomicInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ assertEquals(404, createAtomicInstResp.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createResourceInstanceWhileResourceNotExistTest() throws Exception {
+ String vfResourceUniqueId = "1234";
+ String atomicResourceUniqueId = "5678";
+
+ resourceDetailsVF_01.setUniqueId(vfResourceUniqueId);
+ resourceDetailsCP_01.setUniqueId(atomicResourceUniqueId);
+
+ createVFInstanceFailWithoutChangeState(ActionStatus.RESOURCE_NOT_FOUND,
+ new ArrayList<String>(Arrays.asList("")), resourceDetailsVF_01, sdncDesignerDetails, 404);
+ createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESOURCE_NOT_FOUND,
+ new ArrayList<String>(Arrays.asList("")), resourceDetailsCP_01, sdncDesignerDetails, 404);
+ }
+
+ @Test
+ public void createResourceInstanceInServiceNotExistsTest() throws Exception {
+ serviceDetails_01.setUniqueId("1234");
+ createVFInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsVF_01, sdncDesignerDetails, 404);
+ createAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsCP_01, sdncDesignerDetails, 404);
+ }
+
+ @Test
+ public void createResourceInstanceInCheckedinServiceTest() throws Exception {
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+
+ createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsVF_01, sdncDesignerDetails, 409);
+ createAtomicResourceInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, sdncDesignerDetails, 409);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test(enabled = false)
+ public void createResourceInstance_ResourceInCheckoutStateTest() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ RestResponse createVFInstanceWithoutChangeStateResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ComponentInstanceRestUtils.checkCreateResponse(createVFInstanceWithoutChangeStateResp);
+ RestResponse createAtomicInstWithoutCheangeStateResp = createAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ComponentInstanceRestUtils.checkCreateResponse(createAtomicInstWithoutCheangeStateResp);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void createResourceInstance_ResourceInCertificationRequestStateTest() throws Exception {
+ changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ changeResourceLifecycleState(resourceDetailsCP_01, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void createResourceInstance_startCertificationStateTest() throws Exception {
+ changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ changeResourceLifecycleState(resourceDetailsCP_01, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+
+ changeResourceLifecycleState(resourceDetailsVF_01, sdncTesterDetails.getUserId(),
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ changeResourceLifecycleState(resourceDetailsCP_01, sdncTesterDetails.getUserId(),
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ }
+
+ @Test
+ public void createResourceInstance_certifiedStateTest() throws Exception {
+ certifyResource(resourceDetailsVF_01);
+ certifyResource(resourceDetailsCP_01);
+
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ }
+
+ @Test
+ public void createResourceInstance_OneHasDifferentOwner() throws Exception {
+ User designer2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+
+ ResourceReqDetails vfResource = new ResourceReqDetails(resourceDetailsVF_01, "0.1");
+ vfResource.setUniqueId(null);
+ vfResource.setName("newVF");
+ vfResource.setTags(new ArrayList<String>(Arrays.asList(vfResource.getName())));
+ createVF(vfResource, designer2);
+
+ RestResponse atomicInstanceForService = createCheckedinAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
+ createVFInstanceFailWithoutChangeState(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), vfResource,
+ designer2, 409);
+
+ getComponentAndValidateRIs(serviceDetails_01, 1, 0);
+ }
+
+ @Test
+ public void indexesOfVFInstancesTest() throws Exception {
+ String firstInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "1";
+ String secondInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "2";
+ String thirdInstanceName = resourceDetailsVF_01.getName() + SPACE_STRING + "3";
+
+ LifecycleRestUtils.changeResourceState(resourceDetailsVF_01, sdncDesignerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+
+ RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createSecondVFInstResp);
+ RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createThirdVFInstResp);
+
+ Component service = getComponentAndValidateRIs(serviceDetails_01, 3, 0);
+ List<ComponentInstance> componentInstancesList = service.getComponentInstances();
+ for (ComponentInstance instance : componentInstancesList) {
+ String instanceName = instance.getName();
+ boolean isEqualToFirstInstanceName = instanceName.equals(firstInstanceName);
+ boolean isEqualToSecondInstanceName = instanceName.equals(secondInstanceName);
+ boolean isEqualToThirdInstanceName = instanceName.equals(thirdInstanceName);
+ assertTrue(isEqualToFirstInstanceName || isEqualToSecondInstanceName || isEqualToThirdInstanceName);
+ }
+ }
+
+ @Test
+ public void vfInstancesAmountInTwoServiceVersionsTest() throws Exception {
+ String oldServiceUniqueId = serviceDetails_01.getUniqueId();
+
+ createTwoCheckedinVFInstances();
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
+
+ String newSerivceUniqueIdAfterChangeLifecycleState = serviceDetails_01.getUniqueId();
+ getComponentAndValidateRIsAfterChangeLifecycleState(oldServiceUniqueId, serviceDetails_01, 2, 0);
+
+ // Check old version
+ checkServiceOldVersionRIs(oldServiceUniqueId, newSerivceUniqueIdAfterChangeLifecycleState, 2, 0);
+
+ // Add one more resource instance to second version of service
+ LifecycleRestUtils.changeResourceState(resourceDetailsVL_01, sdncDesignerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ RestResponse createAtomicResourceInstResp = createAtomicResourceInstanceToSecondServiceVersion(
+ newSerivceUniqueIdAfterChangeLifecycleState, resourceDetailsVL_01);
+ String atomicResourceUniqueId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstResp);
+ getComponentAndValidateRIsAfterAddingAtomicResourceInstance(oldServiceUniqueId, serviceDetails_01, 3, 0);
+
+ // Check that RIs are same as in the beginning - like in old version of
+ // service
+ deleteCompInstReqCapFromExpected(atomicResourceUniqueId);
+ checkServiceOldVersionRIs(oldServiceUniqueId, newSerivceUniqueIdAfterChangeLifecycleState, 2, 0);
+
+ }
+
+ private void createTwoCheckedinVFInstances() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createSecondVFInstResp);
+ }
+
+ private void getComponentAndValidateRIsAfterAddingAtomicResourceInstance(String oldComponentUniqueId,
+ ComponentReqDetails componentDetails, int numOfRIs, int numOfRelations) throws Exception {
+ getComponentAndValidateRIsAfterChangeLifecycleState(oldComponentUniqueId, componentDetails, numOfRIs,
+ numOfRelations);
+
+ }
+
+ private void checkServiceOldVersionRIs(String oldUniqueId, String newUniqueId, int numOfRIs, int numOfRelations)
+ throws IOException, Exception {
+ serviceDetails_01.setUniqueId(oldUniqueId);
+ getComponentAndValidateRIsAfterChangeLifecycleState(newUniqueId, serviceDetails_01, numOfRIs, numOfRelations);
+ }
+
+ private RestResponse createAtomicResourceInstanceToSecondServiceVersion(String secondServiceUniqueId,
+ ResourceReqDetails resourceToAdd) throws Exception {
+ serviceDetails_01.setUniqueId(secondServiceUniqueId);
+ RestResponse createAtomicResourceInstResp = createAtomicInstanceForService(serviceDetails_01, resourceToAdd,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstResp);
+ return createAtomicResourceInstResp;
+ }
+
+ @Test
+ public void createResourceInstanceToUnsupportedComponentTest() throws Exception {
+ String unsupportedType = "unsupported";
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentResourceInstance(resourceDetailsCP_01);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, sdncDesignerDetails, serviceDetails_01.getUniqueId(), unsupportedType);
+ checkErrorMessage(ActionStatus.UNSUPPORTED_ERROR, new ArrayList<String>(Arrays.asList(unsupportedType)), 400,
+ createResourceInstanceResponse);
+ }
+
+ @Test
+ public void deleteResourceInstanceByDifferentDesignerTest() throws Exception {
+
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
+
+ deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2), 409);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceByDifferentDesignerTest_ServiceIsCheckedin() throws Exception {
+
+ String oldServiceUniqueId = serviceDetails_01.getUniqueId();
+
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ RestResponse createAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstResp);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2),
+ LifeCycleStatesEnum.CHECKOUT);
+ String newServiceUniqueId = serviceDetails_01.getUniqueId();
+
+ String oldVFInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ String newVFInstanceUniqueId = oldVFInstanceUniqueId.replaceAll(oldServiceUniqueId,
+ serviceDetails_01.getUniqueId());
+ String oldAtomicResourceInstanceUniqueId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstResp);
+ String newAtomicResourceInstanceUniqueId = oldAtomicResourceInstanceUniqueId.replaceAll(oldServiceUniqueId,
+ serviceDetails_01.getUniqueId());
+
+ deleteVFInstanceAndAtomicResourceInstanceSuccessfully(newVFInstanceUniqueId, newAtomicResourceInstanceUniqueId,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2));
+
+ serviceDetails_01.setUniqueId(oldServiceUniqueId);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ serviceDetails_01.setUniqueId(newServiceUniqueId);
+ updateExpectedReqCapAfterChangeLifecycleState(oldServiceUniqueId, serviceDetails_01.getUniqueId());
+ deleteCompInstReqCapFromExpected(newVFInstanceUniqueId);
+ deleteCompInstReqCapFromExpected(newAtomicResourceInstanceUniqueId);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ private void deleteVFInstanceAndAtomicResourceInstanceSuccessfully(String vfInstanceUniqueId,
+ String atomicResourceInstanceUniqueId) throws IOException, Exception {
+ deleteVFInstanceAndAtomicResourceInstanceSuccessfully(vfInstanceUniqueId, atomicResourceInstanceUniqueId,
+ sdncDesignerDetails);
+ }
+
+ private void deleteVFInstanceAndAtomicResourceInstanceSuccessfully(String vfInstanceUniqueId,
+ String atomicResourceInstanceUniqueId, User user) throws IOException, Exception {
+ RestResponse deleteVFInstResp = deleteVFInstance(vfInstanceUniqueId, serviceDetails_01, user);
+ ResourceRestUtils.checkDeleteResponse(deleteVFInstResp);
+ RestResponse deleteAtomicResourceInsResp = deleteAtomicInstanceForService(atomicResourceInstanceUniqueId,
+ serviceDetails_01, user);
+ ResourceRestUtils.checkDeleteResponse(deleteAtomicResourceInsResp);
+ }
+
+ @Test
+ public void deleteResourceInstanceByTesterUserTest() throws Exception {
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
+ deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, ElementFactory.getDefaultUser(UserRoleEnum.TESTER), 409);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceByNotASDCUserTest() throws Exception {
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
+ User notASDCUser = new User();
+ notASDCUser.setUserId("ab0001");
+ deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ notASDCUser, 409);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, notASDCUser, 409);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceFromCheckedinServiceTest() throws Exception {
+ createVFInstanceAndAtomicResourceInstanceSuccessully(resourceDetailsVF_01, resourceDetailsCP_01);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ sdncDesignerDetails, 409);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, sdncDesignerDetails, 409);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceWhileResourceCertifiedStateTest() throws Exception {
+ certifyResource(resourceDetailsVF_01);
+ certifyResource(resourceDetailsCP_01);
+
+ RestResponse createVFInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstance);
+ String vfInstUniqueId = ResponseParser.getUniqueIdFromResponse(createVFInstance);
+ RestResponse atomicInstanceForService = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(atomicInstanceForService);
+ String atomicInstUniqueId = ResponseParser.getUniqueIdFromResponse(atomicInstanceForService);
+
+ deleteVFInstanceAndAtomicResourceInstanceSuccessfully(vfInstUniqueId, atomicInstUniqueId);
+
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ // fail - bug DE191849
+ @Test
+ public void deleteNotFoundResourceInstanceTest() throws Exception, Throwable {
+
+ resourceDetailsVF_01.setUniqueId("1234");
+ resourceDetailsCP_01.setUniqueId("5678");
+
+ deleteVFInstanceFail(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsVF_01, sdncDesignerDetails, 404);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESOURCE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsCP_01, sdncDesignerDetails, 404);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+
+ // {"requestError":{"serviceException":{"messageId":"SVC4503","text":"Error:
+ // Requested '%1' service was not found.","variables":["1234"]}}}>
+ }
+
+ @Test
+ public void deleteResourceInstanceFromServiceNotFoundTest() throws Exception, Throwable {
+ serviceDetails_01.setUniqueId("1234");
+ deleteVFInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsVF_01, sdncDesignerDetails, 404);
+ deleteAtomicResourceInstanceFail(ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")),
+ resourceDetailsCP_01, sdncDesignerDetails, 404);
+ }
+
+ @Test
+ public void deleteResourceInstanceFromUnsupportedTypeTest() throws Exception {
+ String unsupportedType = "unsupportedType";
+ RestResponse deleteVFInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(sdncDesignerDetails,
+ serviceDetails_01.getUniqueId(), resourceDetailsVF_01.getUniqueId(), unsupportedType);
+ checkErrorMessage(ActionStatus.UNSUPPORTED_ERROR, new ArrayList<String>(Arrays.asList(unsupportedType)), 400,
+ deleteVFInstanceResponse);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceWithEmptyServiceUidTest() throws Exception, Throwable {
+ serviceDetails_01.setUniqueId("");
+ RestResponse deleteVFInstResp = deleteVFInstance(resourceDetailsVF_01.getUniqueId(), serviceDetails_01,
+ sdncDesignerDetails);
+ assertEquals(404, deleteVFInstResp.getErrorCode().intValue());
+ }
+
+ @Test
+ public void deleteResourceInstanceWithEmptyResourceInstanceUidTest() throws Exception, Throwable {
+ RestResponse deleteVFInstResp = deleteVFInstance("", serviceDetails_01, sdncDesignerDetails);
+ assertEquals(405, deleteVFInstResp.getErrorCode().intValue());
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ @Test
+ public void deleteResourceInstanceWithEmptyUserIdTest() throws Exception {
+ sdncDesignerDetails.setUserId("");
+ deleteVFInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(), resourceDetailsVF_01,
+ sdncDesignerDetails, 409);
+ deleteAtomicResourceInstanceFail(ActionStatus.RESTRICTED_OPERATION, new ArrayList<String>(),
+ resourceDetailsCP_01, sdncDesignerDetails, 409);
+ getComponentAndValidateRIs(serviceDetails_01, 0, 0);
+ }
+
+ // fail - bug DE188994
+ @Test
+ public void associateResourceInstanceToResourceInstanceNotFoundTest() throws Exception, Throwable {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ String capCompInstId = "1234";
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ List<CapabilityDefinition> capListBeforeAssociate = new ArrayList<CapabilityDefinition>();
+ CapabilityDefinition cap = new CapabilityDefinition();
+ cap.setUniqueId(capCompInstId);
+ capListBeforeAssociate.add(cap);
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, 404,
+ new ArrayList<String>(Arrays.asList(capCompInstId)));
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate,
+ // requirementsAfterAssoicate);
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capabilitiesAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 1, 0);
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "VF100 1",
+ // "9ae76786-2a9c-4409-95cb-db32885ed07f.eece8aaf-eb9f-4aff-b9a5-a11ca11de9e5.vf1001",
+ // "host"
+ // ]
+ }
+
+ // this case is not relevant any more, it is tested as part of occurrences
+ // story
+ @Test(enabled = false)
+ public void associateOnceAgainExistingRelationTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ //////////////////////////////////////////////
+ // NO ERROR - RELATION ALREADY EXIST
+ // assocaiteInstancesFail(requirementDef, sdncDesignerDetails,
+ // ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, 404, new
+ // ArrayList<String>(Arrays.asList(capCompInstId)));
+ //////////////////////////////////////////////
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListAfterAssociate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ // AssertJUnit.assertEquals("Check requirement", null,
+ // reqListAfterAssociate);
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capListAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ // "messageId": "SVC4119",
+ // "text": "Error: No relation found between resource instances
+ // \u0027%1\u0027 and \u0027%2\u0027 for requirement \u0027%3\u0027.",
+ // "variables": [
+ // "VF100 1",
+ // "VF_admin 2",
+ // "host"
+
+ }
+
+ @Test
+ public void associateInstancesInMissingServiceTest() throws Exception {
+ serviceDetails_01.setUniqueId("1234");
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.SERVICE_NOT_FOUND, 404,
+ new ArrayList<String>(Arrays.asList("")));
+ }
+
+ @Test
+ public void associateAfterDeletingResourceTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ ResourceRestUtils.deleteResource(resourceDetailsVF_01.getUniqueId(), sdncDesignerDetails.getUserId());
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+
+ // for (CapabilityDefinition capabilityDefinition :
+ // capListBeforeAssociate) {
+ // if (capabilityDefinition.getType().equals(CAPABILITY_TYPE)){
+ // capabilityDefinition.setMinOccurrences("0");
+ // }
+ // }
+ //
+ // List<RequirementDefinition> reqListAfterAssociate =
+ // capReqDefAfterAssociate.getRequirements().get(CAPABILITY_TYPE);
+ //
+ // AssertJUnit.assertEquals("Check requirement", null,
+ // reqListAfterAssociate);
+ //
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capListAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+ }
+
+ @Test
+ public void associateInstancesInCheckedinServiceTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+
+ assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409,
+ new ArrayList<String>());
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, requirementsAfterAssoicate);
+ AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, capabilitiesAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ // fail - bug DE188994
+ @Test
+ public void associateAfterCheckoutAllInstancesTest() throws Exception {
+ String firstVFUniqueId = resourceDetailsVF_01.getUniqueId();
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ String secondVFUniqueId = resourceDetailsVF_02.getUniqueId();
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ changeResourceLifecycleState(resourceDetailsVF_01, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CHECKOUT);
+ changeResourceLifecycleState(resourceDetailsVF_02, sdncDesignerDetails.getUserId(),
+ LifeCycleStatesEnum.CHECKOUT);
+
+ requirementDef.setFromNode(
+ requirementDef.getFromNode().replaceAll(firstVFUniqueId, resourceDetailsVF_01.getUniqueId()));
+ requirementDef
+ .setToNode(requirementDef.getToNode().replaceAll(secondVFUniqueId, resourceDetailsVF_02.getUniqueId()));
+
+ assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409,
+ new ArrayList<String>());
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate,
+ // requirementsAfterAssoicate);
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capabilitiesAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ // "messageId": "SVC4116",
+ // "text": "Error: Invalid Content.",
+ // "variables": [
+ // "e9dcea15-ce27-4381-a554-4278973cefb1.d0b3affd-cf92-4626-adfe-961b44103924.vf1001",
+ // "e9dcea15-ce27-4381-a554-4278973cefb1.d0b3affd-cf92-4626-adfe-961b44103924.vf1001",
+ // "host"
+ // ]
+
+ }
+
+ @Test
+ public void associateInstancesByDifferentUsersTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2),
+ ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
+ assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.TESTER),
+ ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
+ assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR),
+ ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
+ assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.OPS),
+ ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
+ assocaiteInstancesFail(requirementDef, ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1),
+ ActionStatus.RESTRICTED_OPERATION, 409, new ArrayList<String>());
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, requirementsAfterAssoicate);
+ AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate, capabilitiesAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ private void assocaiteInstancesFail(RequirementCapabilityRelDef requirementDef, User user,
+ ActionStatus actionStatus, int errorCode, List<String> variables) throws IOException, Exception {
+ RestResponse associateInstancesResp = ComponentInstanceRestUtils.associateInstances(requirementDef, user,
+ serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ checkErrorMessage(actionStatus, variables, errorCode, associateInstancesResp);
+ }
+
+ private void dissoicateInstancesFail(RequirementCapabilityRelDef requirementDef, User user,
+ ActionStatus actionStatus, int errorCode, List<String> variables) throws IOException, Exception {
+ RestResponse dissoicateInstancesResp = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user,
+ serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ checkErrorMessage(actionStatus, variables, errorCode, dissoicateInstancesResp);
+ }
+
+ @Test
+ public void associateWithMissingServiceUidTest() throws Exception {
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ serviceDetails_01.setUniqueId("");
+ RestResponse associateInstancesResp = ComponentInstanceRestUtils.associateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals(404, associateInstancesResp.getErrorCode().intValue());
+ }
+
+ // fail - bug DE191824
+ @Test
+ public void associateNotCompitableReqCapTest() throws Exception {
+ RestResponse createFirstAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsCP_01, sdncDesignerDetails);
+ String reqCompInstName = ResponseParser.getNameFromResponse(createFirstAtomicResourceInstResp);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstAtomicResourceInstResp);
+ RestResponse createSecondAtomicResourceInstResp = createCheckedinAtomicInstanceForService(serviceDetails_01,
+ resourceDetailsVL_02, sdncDesignerDetails);
+ String capCompInstName = ResponseParser.getNameFromResponse(createSecondAtomicResourceInstResp);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondAtomicResourceInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ List<String> variables = new ArrayList<String>();
+ variables.add(reqCompInstName);
+ variables.add(capCompInstName);
+ variables.add(REQUIREMENT_NAME);
+
+ assocaiteInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_MATCH_NOT_FOUND, 404,
+ variables);
+
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capabilitiesAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> requirementsAfterAssoicate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate,
+ // requirementsAfterAssoicate);
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capabilitiesAfterAssociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ // {"requestError":{"serviceException":{"messageId":"SVC4119","text":"Error:
+ // No relation found between resource instances '%1' and '%2' for
+ // requirement '%3'.","variables":["CP100 1","VL200 2","host"]}}}>
+ }
+
+ @Test
+ public void associateInstancesInTwoServiceVersionsTest() throws Exception {
+ String oldServiceUniqueId = serviceDetails_01.getUniqueId();
+ RestResponse createFirstVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
+ String secondServiceUniqueId = serviceDetails_01.getUniqueId();
+
+ serviceDetails_01.setUniqueId(oldServiceUniqueId);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ updateCapabilitiesOwnerId(oldServiceUniqueId, capListBeforeAssociate, secondServiceUniqueId);
+ updateExpectedReqCapAfterChangeLifecycleState(oldServiceUniqueId, secondServiceUniqueId);
+ CapReqDef capReqDefAfterAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterAssociate = capReqDefAfterAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListAfterAssociate = capReqDefAfterAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", null,
+ // reqListAfterAssociate);
+ // AssertJUnit.assertEquals("Check capabilities",
+ // capListBeforeAssociate, capListAfterAssociate);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqSecondCompInstId = ResponseParser.getUniqueIdFromResponse(createThirdVFInstResp);
+
+ CapReqDef capReqDefBeforeSeconderyAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeSeconderyAssociate = capReqDefBeforeSeconderyAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeSeconderyAssociate = capReqDefBeforeSeconderyAssociate
+ .getRequirements().get(CAPABILITY_TYPE);
+
+ capCompInstId = capCompInstId.replaceAll(oldServiceUniqueId, secondServiceUniqueId);
+ RequirementCapabilityRelDef secondRequirementDef = getReqCapRelation(reqSecondCompInstId, capCompInstId,
+ CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeSeconderyAssociate, reqListBeforeSeconderyAssociate);
+ associateComponentInstancesForService(secondRequirementDef, serviceDetails_01, sdncDesignerDetails);
+
+ CapReqDef capReqDefAfterSeconderyAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterSeconderyAssociate = capReqDefAfterSeconderyAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListAfterSeconderyAssociate = capReqDefAfterSeconderyAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", null,
+ // reqListAfterSeconderyAssociate);
+ // AssertJUnit.assertEquals("Check capabilities",
+ // capListBeforeAssociate, capListAfterSeconderyAssociate);
+ getComponentAndValidateRIs(serviceDetails_01, 3, 2);
+ }
+
+ private void updateCapabilitiesOwnerId(String oldUniqueId, List<CapabilityDefinition> capList, String newUniqueId) {
+ serviceDetails_01.setUniqueId(newUniqueId);
+ for (CapabilityDefinition cap : capList) {
+ String oldOwnerId = cap.getOwnerId();
+ String newOwnerId = oldOwnerId.replaceAll(oldUniqueId, newUniqueId);
+ cap.setOwnerId(newOwnerId);
+ }
+ }
+
+ @Test
+ public void dissociateRelationNotFoundTest() throws Exception {
+ createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ String reqCompInstId = "1234";
+ createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ String capCompInstId = "4567";
+
+ CapReqDef capReqDef = ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capList, reqList);
+
+ List<String> variables = new ArrayList<String>();
+ variables.add(reqCompInstId);
+ variables.add(capCompInstId);
+ variables.add(REQUIREMENT_NAME);
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND,
+ 404, variables);
+
+ CapReqDef capReqDefAfterDissociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterDissociate = capReqDefAfterDissociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListAfterDissociate = capReqDefAfterDissociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ AssertJUnit.assertEquals("Check requirement", 1, reqListAfterDissociate.size());
+ AssertJUnit.assertEquals("Check requirement", reqList, reqListAfterDissociate);
+ AssertJUnit.assertEquals("Check capabilities", capList, capListAfterDissociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+
+ }
+
+ @Test
+ public void dissociateRelationInServiceNotFoundTest() throws Exception {
+ String uniqueId = "1234";
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ serviceDetails_01.setUniqueId(uniqueId);
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.SERVICE_NOT_FOUND, 404,
+ new ArrayList<String>(Arrays.asList("")));
+
+ }
+
+ @Test
+ public void dissoicateRelationWhileInstanceNotFound() throws Exception {
+ String capUniqueId = "1234";
+
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ String capCompInstId = capUniqueId;
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ List<String> variables = new ArrayList<String>();
+ variables.add(reqCompInstId);
+ variables.add(capCompInstId);
+ variables.add(REQUIREMENT_NAME);
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND,
+ 404, variables);
+
+ CapReqDef capReqDefAfterDissociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListAfterDissociate = capReqDefAfterDissociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListAfterDissociate = capReqDefAfterDissociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+ AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate, reqListAfterDissociate);
+ AssertJUnit.assertEquals("Check capabilities", capListBeforeAssociate, capListAfterDissociate);
+
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void dissociateWhileServiceCheckedinTest() throws Exception {
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409,
+ new ArrayList<String>());
+ }
+
+ @Test
+ public void dissoicateWithEmptyUserIdHeaderTest() throws Exception {
+ sdncDesignerDetails.setUserId("");
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESTRICTED_OPERATION, 409,
+ new ArrayList<String>());
+ }
+
+ @Test
+ public void dissociateWithMissingUidOfServiceTest() throws Exception {
+ serviceDetails_01.setUniqueId("");
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ RestResponse dissociateResp = ComponentInstanceRestUtils.dissociateInstances(requirementDef,
+ sdncDesignerDetails, serviceDetails_01.getUniqueId(), ComponentTypeEnum.SERVICE);
+ assertEquals(404, dissociateResp.getErrorCode().intValue());
+ }
+
+ @Test
+ public void relationDeletedAfterDeletingResourceInstanceTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+
+ RestResponse deleteVFInstance = deleteVFInstance(reqCompInstId, serviceDetails_01, sdncDesignerDetails);
+ ComponentInstanceRestUtils.checkDeleteResponse(deleteVFInstance);
+ getComponentAndValidateRIs(serviceDetails_01, 1, 0);
+ }
+
+ @Test
+ public void relationNotFoundInSecondVersionAfterDissociateTest() throws Exception {
+ String oldContainerUniqueIdToReplace = serviceDetails_01.getUniqueId();
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
+
+ updateExpectedReqCapAfterChangeLifecycleState(oldContainerUniqueIdToReplace, serviceDetails_01.getUniqueId());
+ getComponentAndValidateRIs(serviceDetails_01, 2, 0);
+ }
+
+ @Test
+ public void dissociateOnceAgainTest() throws Exception {
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ String reqCompInsName = ResponseParser
+ .convertComponentInstanceResponseToJavaObject(createFirstVFInstResp.getResponse()).getName();
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+ String capCompInstName = ResponseParser
+ .convertComponentInstanceResponseToJavaObject(createSecondVFInstResp.getResponse()).getName();
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, CAPABILITY_TYPE,
+ REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ dissociateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+
+ List<String> variables = new ArrayList<String>();
+ variables.add(reqCompInsName);
+ variables.add(capCompInstName);
+ variables.add(REQUIREMENT_NAME);
+
+ dissoicateInstancesFail(requirementDef, sdncDesignerDetails, ActionStatus.RESOURCE_INSTANCE_RELATION_NOT_FOUND,
+ 404, variables);
+ }
+
+ // fail - bug : DE191707
+ @Test
+ public void associateTwoRelations_CheckinCheckout_DissoicateOneRelationInSecondVersion() throws Exception {
+ String oldContainerUniqueIdToReplace = serviceDetails_01.getUniqueId();
+ RestResponse createFirstVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createFirstVFInstResp);
+ RestResponse createSecondVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createSecondVFInstResp);
+ RestResponse createThirdVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ String secondReqCompInstId = ResponseParser.getUniqueIdFromResponse(createThirdVFInstResp);
+
+ CapReqDef capReqDefBeforeAssociate = ComponentRestUtils
+ .getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails, serviceDetails_01);
+ List<CapabilityDefinition> capListBeforeAssociate = capReqDefBeforeAssociate.getCapabilities()
+ .get(CAPABILITY_TYPE);
+ List<RequirementDefinition> reqListBeforeAssociate = capReqDefBeforeAssociate.getRequirements()
+ .get(CAPABILITY_TYPE);
+
+ RequirementCapabilityRelDef requirementDefFirstRelation = getReqCapRelation(reqCompInstId, capCompInstId,
+ CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+ RequirementCapabilityRelDef requirementDefSecondRelation = getReqCapRelation(secondReqCompInstId, capCompInstId,
+ CAPABILITY_TYPE, REQUIREMENT_NAME, capListBeforeAssociate, reqListBeforeAssociate);
+
+ associateComponentInstancesForService(requirementDefFirstRelation, serviceDetails_01, sdncDesignerDetails);
+ associateComponentInstancesForService(requirementDefSecondRelation, serviceDetails_01, sdncDesignerDetails);
+ getComponentAndValidateRIs(serviceDetails_01, 3, 2);
+
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKOUT);
+ String newContainerUniqueId = serviceDetails_01.getUniqueId();
+
+ // check if dissoicate of old relation is possibile
+ // dissoicateInstancesFail(requirementDefFirstRelation,
+ // sdncDesignerDetails, actionStatus, errorCode, variables);
+ getComponentAndValidateRIs(serviceDetails_01, 3, 2);
+
+ requirementDefFirstRelation
+ .setFromNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ requirementDefFirstRelation
+ .setToNode(reqCompInstId.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+
+ dissociateComponentInstancesForService(requirementDefFirstRelation, serviceDetails_01, sdncDesignerDetails);
+
+ // updateCapabilitiesOwnerId(oldContainerUniqueIdToReplace,
+ // capListBeforeAssociate, newContainerUniqueId);
+ // CapReqDef capReqDefAfterAssociate =
+ // ComponentRestUtils.getAndParseComponentRequirmentsCapabilities(sdncDesignerDetails,
+ // serviceDetails_01);
+ // List<CapabilityDefinition> capListAfterAssociate =
+ // capReqDefAfterAssociate.getCapabilities().get(CAPABILITY_TYPE);
+ // List<RequirementDefinition> reqListAfterAssociate =
+ // capReqDefAfterAssociate.getRequirements().get(CAPABILITY_TYPE);
+ // AssertJUnit.assertEquals("Check requirement", reqListBeforeAssociate,
+ // reqListAfterAssociate);
+ // AssertJUnit.assertEquals("Check requirement", capListBeforeAssociate,
+ // capListAfterAssociate);
+ updateExpectedReqCapAfterChangeLifecycleState(oldContainerUniqueIdToReplace, serviceDetails_01.getUniqueId());
+ getComponentAndValidateRIs(serviceDetails_01, 3, 1);
+ }
+
+ @Test
+ public void createResourceInstancesAndUpdatedServiceMetadataTest() throws Exception, Exception {
+ serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId());
+ createTwoCheckedinVFInstances();
+ LifecycleRestUtils.changeResourceState(resourceDetailsCP_01, sdncDesignerDetails, "0.1",
+ LifeCycleStatesEnum.CHECKIN);
+ createVFInstanceAndAtomicResourceInstanceWithoutCheckin(resourceDetailsVF_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(updateServiceResp);
+ getComponentAndValidateRIs(serviceDetails_01, 4, 0);
+ }
+
+ @Test(enabled = false)
+ public void forAcceptanceUserStory() throws Exception {
+ RestResponse createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String reqCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+ createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_02, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ String capCompInstId = ResponseParser.getUniqueIdFromResponse(createVFInstResp);
+
+ String capType = CAPABILITY_TYPE;
+ String reqName = REQUIREMENT_NAME;
+
+ RestResponse getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ ResourceRestUtils.checkSuccess(getResourceResponse);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<CapabilityDefinition> capList = capReqDef.getCapabilities().get(capType);
+ List<RequirementDefinition> reqList = capReqDef.getRequirements().get(capType);
+
+ RequirementCapabilityRelDef requirementDef = getReqCapRelation(reqCompInstId, capCompInstId, capType, reqName,
+ capList, reqList);
+
+ associateComponentInstancesForService(requirementDef, serviceDetails_01, sdncDesignerDetails);
+ getResourceResponse = ComponentRestUtils.getComponentRequirmentsCapabilities(sdncDesignerDetails,
+ serviceDetails_01);
+ capReqDef = ResponseParser.parseToObject(getResourceResponse.getResponse(), CapReqDef.class);
+ List<RequirementDefinition> list = capReqDef.getRequirements().get(capType);
+ AssertJUnit.assertEquals("Check requirement", null, list);
+
+ serviceDetails_02.setUniqueId(serviceDetails_01.getUniqueId());
+ RestResponse updateServiceResp = ServiceRestUtils.updateService(serviceDetails_02, sdncDesignerDetails);
+ ServiceRestUtils.checkSuccess(updateServiceResp);
+ changeServiceLifecycleState(serviceDetails_01, sdncDesignerDetails, LifeCycleStatesEnum.CHECKIN);
+ getComponentAndValidateRIs(serviceDetails_01, 2, 1);
+ }
+
+ @Test
+ public void testUnsatisfiedCpReqInService() throws Exception {
+
+ // Certify all the needed atomic resources
+ RestResponse response = LifecycleRestUtils.certifyResource(resourceDetailsCP_01);
+ ResourceRestUtils.checkSuccess(response);
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails,
+ resourceDetailsVF_02.getUniqueId());
+ ResourceRestUtils.checkSuccess(response);
+ response = LifecycleRestUtils.certifyResource(resourceDetailsVF_02);
+ ResourceRestUtils.checkSuccess(response);
+ capOwnerId = getUniqueIdOfFirstInstanceFromResponse(response);
+
+ RestResponse createAtomicResourceInstance = createVFInstance(serviceDetails_01, resourceDetailsVF_02,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String vfCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ createAtomicResourceInstance = createAtomicInstanceForService(serviceDetails_01, resourceDetailsCP_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createAtomicResourceInstance);
+ String compInstName = ResponseParser.getNameFromResponse(createAtomicResourceInstance);
+ String cpCompInstId = ResponseParser.getUniqueIdFromResponse(createAtomicResourceInstance);
+
+ RestResponse submitForTesting = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ String[] variables = new String[] { serviceDetails_01.getName(), "service", "CP (Connection Point)",
+ compInstName, "requirement", "tosca.capabilities.network.Bindable", "fulfilled" };
+ BaseValidationUtils.checkErrorResponse(submitForTesting,
+ ActionStatus.REQ_CAP_NOT_SATISFIED_BEFORE_CERTIFICATION, variables);
+
+ fulfillCpRequirement(serviceDetails_01, cpCompInstId, vfCompInstId, capOwnerId, sdncDesignerDetails,
+ ComponentTypeEnum.SERVICE);
+
+ submitForTesting = LifecycleRestUtils.changeServiceState(serviceDetails_01, sdncDesignerDetails,
+ LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ BaseValidationUtils.checkSuccess(submitForTesting);
+ }
+
+ @Test
+ public void getVFInstanceSuccessfullyTest() throws Exception {
+ RestResponse createVFInstResp = createCheckedinVFInstance(serviceDetails_01, resourceDetailsVF_01,
+ sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ System.out.println("instance successfuly created");
+ RestResponse getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE,
+ serviceDetails_01.getUniqueId(), sdncDesignerDetails);
+
+ for (int i = 0; i < 1500; i++) {
+ createVFInstResp = createVFInstance(serviceDetails_01, resourceDetailsVF_01, sdncDesignerDetails);
+ ResourceRestUtils.checkCreateResponse(createVFInstResp);
+ System.out.println("instance " + i + "successfuly created");
+ }
+
+ getInstancesResponce = ComponentInstanceRestUtils.getComponentInstances(ComponentTypeEnum.SERVICE,
+ serviceDetails_01.getUniqueId(), sdncDesignerDetails);
+
+ BaseValidationUtils.checkSuccess(getInstancesResponce);
+
+ }
+
+ private String getUniqueIdOfFirstInstanceFromResponse(RestResponse response) {
+ try {
+ JSONArray value = ResponseParser.getListFromJson(response, "componentInstances");
+ return ResponseParser.getValueFromJsonResponse(value.get(0).toString(), "uniqueId");
+ } catch (Exception e) {
+ return null;
+ }
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java
new file mode 100644
index 0000000000..2f5b47452e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/service/UpdateServiceMetadataTest.java
@@ -0,0 +1,1984 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.service;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.lang3.StringUtils;
+import org.codehaus.jettison.json.JSONException;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class UpdateServiceMetadataTest extends ComponentBaseTest {
+
+ protected ArrayList<String> listForMessage = new ArrayList<String>();
+
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected User sdncDesignerDetails;
+ protected User sdncDesignerDetails2;
+ protected User sdncAdminDetails;
+ protected User sdncGovernorDeatails;
+ protected User sdncTesterDetails;
+ protected User sdncOpsDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected Component resourceDetailsVFCcomp;
+ protected Component serviceDetailsCompp;
+
+ @Rule
+ public static TestName name = new TestName();
+ protected ServiceReqDetails updatedServiceDetails;
+
+ public UpdateServiceMetadataTest() {
+ super(name, UpdateServiceMetadataTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void setUp() throws Exception {
+
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncDesignerDetails2 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER2);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncAdminDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN4);
+ sdncGovernorDeatails = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ sdncTesterDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncOpsDetails = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ resourceDetailsVFCcomp = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, true, true);
+
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true);
+ Service serviceServ = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp, serviceServ, UserRoleEnum.DESIGNER, true);
+
+ serviceDetails = new ServiceReqDetails(serviceServ);
+ updatedServiceDetails = updatedServiceDetails(serviceDetails);
+
+ }
+
+ protected void certifyService(ServiceReqDetails serviceDetails, String version) throws Exception {
+ LifecycleRestUtils.certifyService(serviceDetails);
+ }
+
+ protected ServiceReqDetails updatedServiceDetails(ServiceReqDetails service) {
+ ServiceReqDetails updatedServiceDetails = new ServiceReqDetails(service);
+
+ updatedServiceDetails.setDescription("updatedDescription");
+ updatedServiceDetails.setName(service.getName());
+ updatedServiceDetails.setProjectCode("987654654");
+ updatedServiceDetails.setIcon("icon-service-red3");
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("updateTag", updatedServiceDetails.getName())));
+ updatedServiceDetails.removeAllCategories();
+ updatedServiceDetails.setCategories(null);
+ updatedServiceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue());
+ updatedServiceDetails.setContactId("xy0123");
+
+ return updatedServiceDetails;
+ }
+
+ protected void addMandatoryArtifactsToService() throws Exception {
+ // TODO Andrey US575052
+ // ServiceRestUtils.addServiceMandatoryArtifacts(sdncDesignerDetails,
+ // createServiceResponse);
+ }
+
+ protected void getServiceAndValidate(ServiceReqDetails excpectedService, User creator, User updater, LifecycleStateEnum lifeCycleState) throws Exception {
+ RestResponse getServiceResponse = ServiceRestUtils.getService(excpectedService.getUniqueId(), sdncDesignerDetails);
+ AssertJUnit.assertNotNull("check response object is not null after updating service", getServiceResponse);
+ AssertJUnit.assertNotNull("check if error code exists in response after updating service", getServiceResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after updating service", 200, getServiceResponse.getErrorCode().intValue());
+ Service actualService = ResponseParser.convertServiceResponseToJavaObject(getServiceResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(excpectedService, actualService, creator, updater, lifeCycleState);
+ }
+
+ public void getServiceAndValidate(ServiceReqDetails excpectedService, LifecycleStateEnum lifecycleState) throws Exception {
+ getServiceAndValidate(excpectedService, sdncDesignerDetails, sdncDesignerDetails, lifecycleState);
+ }
+
+ protected void validateResponse(RestResponse response, int errorCode, ActionStatus actionResponse, List<String> listOfVariables) throws Exception {
+ AssertJUnit.assertNotNull("check response object is not null after updating service", response);
+ AssertJUnit.assertNotNull("check if error code exists in response after updating service", response.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after updating service", errorCode, response.getErrorCode().intValue());
+
+ if (actionResponse != null) {
+ ErrorValidationUtils.checkBodyResponseOnError(actionResponse.name(), listOfVariables, response.getResponse());
+ return;
+ }
+
+ Service actualService = ResponseParser.convertServiceResponseToJavaObject(response.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService, sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ protected void validateActualVsExpected(ServiceReqDetails expectedService, RestResponse actualServiceFromResponse) {
+ Service actualService = ResponseParser.convertServiceResponseToJavaObject(actualServiceFromResponse.getResponse());
+ ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails, actualService, sdncDesignerDetails, sdncDesignerDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ protected String multipleString(String ch, int repeat) {
+ return StringUtils.repeat(ch, repeat);
+ }
+
+ protected void correctUpdate() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 200, null, listForMessage);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ protected void updateWithInvalidValue(ActionStatus invalidValue, List<String> arr) throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, invalidValue, arr);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ protected void charactersInRangeChecking(int min, int max, String field) throws Exception {
+ if (field != null) {
+ if (field == "name") {
+ for (char ch = (char) min; ch <= (char) max; ch++) {
+ updatedServiceDetails.setName("testname" + String.valueOf(ch));
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ updateWithInvalidValue(ActionStatus.INVALID_COMPONENT_NAME, new ArrayList<>(Arrays.asList("Service")));
+ }
+ } else if (field == "icon") {
+ for (char ch = (char) min; ch <= (char) max; ch++) {
+ updatedServiceDetails.setIcon("testname" + String.valueOf(ch));
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service")));
+ }
+ } else if (field == "tags") {
+ List<String> variables = Arrays.asList("Service", "tag");
+ for (char ch = (char) min; ch <= (char) max; ch++) {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(String.valueOf(ch), updatedServiceDetails.getName())));
+ updateWithInvalidValue(ActionStatus.INVALID_FIELD_FORMAT, variables);
+ }
+ } else if (field == "category") {
+ for (char ch = (char) min; ch <= (char) max; ch++) {
+ updatedServiceDetails.addCategoryChain(multipleString("1", 5) + String.valueOf(ch), multipleString("1", 5) + String.valueOf(ch));
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service")));
+ }
+ }
+
+ else if (field == "projectCode") {
+ for (char ch = (char) min; ch <= (char) max; ch++) {
+ updatedServiceDetails.setProjectCode(multipleString("1", 5) + String.valueOf(ch));
+ updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage);
+ }
+ }
+
+ else
+ return;
+ }
+
+ }
+
+ protected void specialCharsChecking(String field) throws Exception {
+ charactersInRangeChecking(33, 44, field);
+ charactersInRangeChecking(47, 47, field);
+ charactersInRangeChecking(58, 64, field);
+ charactersInRangeChecking(91, 94, field);
+ charactersInRangeChecking(96, 96, field);
+ charactersInRangeChecking(123, 126, field);
+ }
+
+ @Test
+ public void updateServiceSuccessfully() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 200, null, listForMessage);
+
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ }
+
+ protected void checkErrorResponse(ActionStatus actionStatus, ArrayList<String> arrList, RestResponse response) throws Exception, JSONException {
+ ErrorValidationUtils.checkBodyResponseOnError(actionStatus.name(), arrList, response.getResponse());
+ }
+
+ protected List<String> addServiceNameToTagsList(String serviceName, List<String> tagsList) {
+ tagsList.add(serviceName);
+ return tagsList;
+
+ }
+
+ @Test
+ public void updateService_ByOtherDesigner() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails2);
+ validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void updateService_ByAdmin() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncAdminDetails);
+ validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void updateServiceNotExist() throws Exception {
+ updatedServiceDetails.setUniqueId("nnnnn");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 404, ActionStatus.SERVICE_NOT_FOUND, new ArrayList<String>(Arrays.asList("")));
+ }
+
+ @Test
+ public void updateCheckedinService() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ }
+
+ @Test
+ public void updateCertifiedService() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 409, ActionStatus.RESTRICTED_OPERATION, listForMessage);
+ getServiceAndValidate(serviceDetails, sdncDesignerDetails, sdncAdminDetails, LifecycleStateEnum.CERTIFIED);
+ }
+
+ // TODO Irrelevant
+ // @Test(enabled = false)
+ // public void updateService_NameCaseSensitiveTest() throws Exception {
+ // ServiceRestUtils.setServiceUniqueId(serviceDetails.getName().toUpperCase());
+ //
+ // RestResponse updateServiceResponse =
+ // ServiceRestUtils.updateService(updatedServiceDetails,
+ // sdncDesignerDetails);
+ // validateResponse(updateServiceResponse, 200, null, listForMessage);
+ //
+ // Service serviceFromJsonResponse =
+ // ResponseParser.convertServiceResponseToJavaObject(updateServiceResponse.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(updatedServiceDetails,
+ // serviceFromJsonResponse, sdncDesignerDetails, (LifecycleStateEnum)null);
+ //
+ // getServiceAndValidate(updatedServiceDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // }
+
+ // @Test
+ // public void updateApprovedDistributionServiceTest() throws Exception {
+ // // addMandatoryArtifactsToService();
+ // certifyService(serviceDetails, serviceDetails.getVersion());
+ //
+ // RestResponse approveResponse =
+ // ServiceRestUtils.sendApproveDistribution(sdncAdminDetails,
+ // serviceDetails.getUniqueId(), userRemarks);
+ // // validateResponse(approveResponse, 200, null, listForMessage);
+ //
+ // RestResponse updateServiceResponse =
+ // ServiceRestUtils.updateService(updatedServiceDetails,
+ // sdncDesignerDetails);
+ // validateResponse(updateServiceResponse, 409,
+ // ActionStatus.RESTRICTED_OPERATION, listForMessage);
+ //
+ // getServiceAndValidate(serviceDetails, sdncDesignerDetails,
+ // sdncAdminDetails,LifecycleStateEnum.CERTIFIED);
+ // }
+
+ @Test
+ public void updateServiceByMethod_delete() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "DELETE", Urls.UPDATE_SERVICE_METADATA);
+ validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void updateServiceByMethod_get() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "GET", Urls.UPDATE_SERVICE_METADATA);
+ validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void updateServiceByMethod_post() throws Exception {
+ RestResponse updateServiceResponse = ServiceRestUtils.createServiceByHttpMethod(updatedServiceDetails, sdncDesignerDetails, "POST", Urls.UPDATE_SERVICE_METADATA);
+ validateResponse(updateServiceResponse, 405, ActionStatus.NOT_ALLOWED, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void updateCheckoutCertifiedService() throws Exception // certify a
+ // service
+ // and
+ // checkout
+ // it
+ {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage);
+
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ // ---------------------------------------------------------Validation
+ // Tests---------------------------------------------------------
+
+ @Test
+ public void missingCategoryTest1() throws Exception {
+ List<CategoryDefinition> categories = updatedServiceDetails.getCategories();
+ CategoryDefinition categoryDefinition = categories.get(0);
+ CategoryDefinition categoryDefinition2 = categoryDefinition;
+ categoryDefinition2.setName("");
+ categories.set(0, categoryDefinition2);
+ updatedServiceDetails.setCategories(categories);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingCategoryTest2() throws Exception {
+ updatedServiceDetails.setCategories(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_CATEGORY, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingServiceNameTest1() throws Exception {
+ updatedServiceDetails.setName(StringUtils.EMPTY);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingServiceNameTest2() throws Exception {
+
+ updatedServiceDetails.setName(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ // TODO Irrelevant
+ @Test(enabled = false)
+ public void missingProjectCodeTest1() throws Exception {
+ updatedServiceDetails.setProjectCode(StringUtils.EMPTY);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_PROJECT_CODE, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ // TODO Irrelevant
+ @Test(enabled = false)
+ public void missingProjectCodeTest2() throws Exception {
+ updatedServiceDetails.setProjectCode(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_PROJECT_CODE, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingIconTest1() throws Exception {
+ updatedServiceDetails.setIcon(StringUtils.EMPTY);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingIconTest2() throws Exception {
+ updatedServiceDetails.setIcon(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_ICON, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingDescriptionTest1() throws Exception {
+ updatedServiceDetails.setDescription(StringUtils.EMPTY);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingDescriptionTest2() throws Exception {
+ updatedServiceDetails.setDescription(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_DESCRIPTION, Arrays.asList("Service"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingTagsTest1() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<String>());
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_TAGS, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingTagsTest2() throws Exception {
+ updatedServiceDetails.setTags(null);
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.COMPONENT_MISSING_TAGS, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingTagsTest3() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(StringUtils.EMPTY)));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Service", "tag"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void missingTagsTest4() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(StringUtils.EMPTY, updatedServiceDetails.getName())));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse, 400, ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Service", "tag"));
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ // update non-settable/"updatable" parameters tests
+
+ // ------------------------------------------correct
+ // values------------------------------------------
+ @Test
+ public void contactIdValidationTest1() throws Exception {
+ updatedServiceDetails.setContactId("ab3456");
+ correctUpdate();
+ }
+
+ @Test
+ public void contactIdValidationTest2() throws Exception {
+
+ updatedServiceDetails.setContactId("cd789E");
+ correctUpdate();
+ }
+
+ @Test
+ public void contactIdValidationTest3() throws Exception {
+
+ updatedServiceDetails.setContactId("ef4567");
+ correctUpdate();
+ }
+
+ @Test
+ public void contactIdValidationTest4() throws Exception {
+ updatedServiceDetails.setContactId("AA012A");
+ correctUpdate();
+ }
+
+ @Test
+ public void contactIdValidationTest5() throws Exception {
+ updatedServiceDetails.setContactId("CD012c");
+ correctUpdate();
+ }
+
+ @Test
+ public void contactIdValidationTest6() throws Exception {
+ updatedServiceDetails.setContactId("EF0123");
+ correctUpdate();
+ }
+
+ // ------------------------------------------invalid
+ // values------------------------------------------
+ @Test
+ public void contactIdValidationTest7() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ updatedServiceDetails.setContactId("ab0001");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void contactIdValidationTest8() throws Exception {
+ // addMandatoryArtifactsToService();
+
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser.convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ updatedServiceDetails = new ServiceReqDetails(certifyService);
+ updatedServiceDetails.setContactId("ab0001");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void contactIdValidationTest9() throws Exception {
+ updatedServiceDetails.setContactId("01345a");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service"));
+ }
+
+ @Test
+ public void contactIdValidationTest10() throws Exception {
+ updatedServiceDetails.setContactId("0y000B");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service"));
+ }
+
+ @Test
+ public void contactIdValidationTest11() throws Exception {
+ updatedServiceDetails.setContactId("Y1000b");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service"));
+ }
+
+ @Test
+ public void contactIdValidationTest12() throws Exception {
+ updatedServiceDetails.setContactId("abxyzC");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, Arrays.asList("Service"));
+ }
+
+ @Test
+ public void contactIdValidationTest13() throws Exception {
+ updatedServiceDetails.setContactId("cdXYZc");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest14() throws Exception {
+ updatedServiceDetails.setContactId("efXY1D");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest15() throws Exception {
+ updatedServiceDetails.setContactId("EFabcD");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest16() throws Exception {
+ updatedServiceDetails.setContactId("EFABCD");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest17() throws Exception {
+ updatedServiceDetails.setContactId("EFABC1");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest18() throws Exception {
+ updatedServiceDetails.setContactId("efui1D");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest19() throws Exception {
+ updatedServiceDetails.setContactId("efui1!");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest20() throws Exception {
+ updatedServiceDetails.setContactId("ef555!");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest21() throws Exception {
+ updatedServiceDetails.setContactId(",f555");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest22() throws Exception {
+ updatedServiceDetails.setContactId("EF55.5");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest23() throws Exception {
+ updatedServiceDetails.setContactId("ab000");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest24() throws Exception {
+ updatedServiceDetails.setContactId("ab000c0");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest25() throws Exception {
+ updatedServiceDetails.setContactId(" ab0001");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CONTACT, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void contactIdValidationTest26() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails.setContactId("xy0002");
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest1() throws Exception {
+ updatedServiceDetails.setName(multipleString("a", 49));
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest2() throws Exception {
+ updatedServiceDetails.setName(multipleString("b", 50));
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest3() throws Exception {
+ updatedServiceDetails.setName("testNamE");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest4() throws Exception {
+ updatedServiceDetails.setName("Testname");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest5() throws Exception {
+ updatedServiceDetails.setName("Test_name");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest6() throws Exception {
+ updatedServiceDetails.setName("Test name");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest7() throws Exception {
+ updatedServiceDetails.setName("Test-name");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest8() throws Exception {
+ updatedServiceDetails.setName("Test.name");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest9() throws Exception {
+ updatedServiceDetails.setName("...1...");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest10() throws Exception {
+ updatedServiceDetails.setName("-a_1. Arrrrrr");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest11() throws Exception {
+ updatedServiceDetails.setName("Testname1234567890");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ correctUpdate();
+ }
+
+ @Test
+ public void serviceNameValidationTest14() throws Exception {
+ updatedServiceDetails.setName(StringUtils.SPACE); // one space with
+ // nothing
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ // updateWithInvalidValue(ActionStatus.INVALID_COMPONENT_NAME, new
+ // ArrayList<>(Arrays.asList("Service")));
+ validateResponse(updateServiceResponse, 400, ActionStatus.MISSING_COMPONENT_NAME, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ // ------------------------------------------invalid
+ // values------------------------------------------
+ @Test
+ public void serviceNameValidationTest12() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ updatedServiceDetails.setName("TestNamE");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
+ }
+
+ @Test
+ public void serviceNameValidationTest13() throws Exception {
+ updatedServiceDetails.setName(multipleString("c", 51));
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ updateWithInvalidValue(ActionStatus.COMPONENT_NAME_EXCEEDS_LIMIT, new ArrayList<>(Arrays.asList("Service", "50")));
+ }
+
+ @Test
+ public void serviceNameValidationTest15() throws Exception {
+ specialCharsChecking("name");
+ }
+
+ @Test
+ public void serviceNameValidationTest16() throws Exception {
+ // addMandatoryArtifactsToService();
+ LifecycleRestUtils.certifyService(serviceDetails);
+ updatedServiceDetails.setName("testnamename");
+ updatedServiceDetails.setCategories(serviceDetails.getCategories());
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ getServiceAndValidate(serviceDetails, sdncDesignerDetails, sdncTesterDetails, LifecycleStateEnum.CERTIFIED);
+ }
+
+ @Test
+ public void serviceNameValidationTest17() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ updatedServiceDetails.setName("TestNamE");
+ updatedServiceDetails.setCategories(serviceDetails.getCategories());
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse2, 400, ActionStatus.SERVICE_NAME_CANNOT_BE_CHANGED, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void serviceNameValidationTest18() throws Exception {
+ updatedServiceDetails.setName(" testname ");
+ updatedServiceDetails.setTags(addServiceNameToTagsList(updatedServiceDetails.getName(), updatedServiceDetails.getTags()));
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse1);
+ assertNotNull(updateServiceResponse1.getErrorCode());
+ assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
+ updatedServiceDetails.setName(updatedServiceDetails.getName());
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse1);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void iconValidationTest1() throws Exception {
+ updatedServiceDetails.setIcon(multipleString("a", 24));
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest2() throws Exception {
+ updatedServiceDetails.setIcon(multipleString("b", 25));
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest3() throws Exception {
+ updatedServiceDetails.setIcon("testNamE");
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest4() throws Exception {
+ updatedServiceDetails.setIcon("Testname");
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest5() throws Exception {
+ updatedServiceDetails.setIcon("Test_name");
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest6() throws Exception {
+ updatedServiceDetails.setIcon("Test-name");
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest7() throws Exception {
+ updatedServiceDetails.setIcon("Testname1234567890");
+ correctUpdate();
+ }
+
+ @Test
+ public void iconValidationTest8() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ updatedServiceDetails.setIcon("TestNamE");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void iconValidationTest9() throws Exception {
+ // addMandatoryArtifactsToService();
+ LifecycleRestUtils.certifyService(serviceDetails);
+ updatedServiceDetails.setIcon("testnamename");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ // ------------------------------------------invalid
+ // values------------------------------------------
+ @Test
+ public void iconValidationTest10() throws Exception {
+ updatedServiceDetails.setIcon("Test name");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void iconValidationTest11() throws Exception {
+ updatedServiceDetails.setIcon(StringUtils.SPACE); // one space with
+ // nothing
+ updateWithInvalidValue(ActionStatus.COMPONENT_MISSING_ICON, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void iconValidationTest12() throws Exception {
+ updatedServiceDetails.setIcon("Test.name");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void iconValidationTest13() throws Exception {
+ specialCharsChecking("icon");
+ charactersInRangeChecking(46, 46, "icon");
+ }
+
+ @Test
+ public void iconValidationTest14() throws Exception {
+ updatedServiceDetails.setIcon(multipleString("c", 26));
+ updateWithInvalidValue(ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, new ArrayList<>(Arrays.asList("Service", "25")));
+ }
+
+ @Test
+ public void iconValidationTest15() throws Exception {
+ // addMandatoryArtifactsToService();
+ RestResponse certifyServiceResp = LifecycleRestUtils.certifyService(serviceDetails);
+ Service certifyServiceServ = ResponseParser.convertServiceResponseToJavaObject(certifyServiceResp.getResponse());
+ ServiceReqDetails certifyService = new ServiceReqDetails(certifyServiceServ);
+ updatedServiceDetails = new ServiceReqDetails(certifyService);
+ updatedServiceDetails.setIcon("testnamename");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void iconValidationTest16() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails.setIcon("TestNamE");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.SERVICE_ICON_CANNOT_BE_CHANGED, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void iconValidationTest17() throws Exception {
+ updatedServiceDetails.setIcon(" Icon ");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_ICON, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void categoryValidationTest1() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ updatedServiceDetails.addCategory(ServiceCategoriesEnum.VOIP.getValue());
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void categoryValidationTest2() throws Exception {
+ // updatedServiceDetails.addCategory("someCategory");
+ updatedServiceDetails.setCategories(null);
+ updatedServiceDetails.addCategoryChain("someCategory", null);
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void categoryValidationTest3() throws Exception {
+ updatedServiceDetails.setCategories(null);
+ updatedServiceDetails.addCategoryChain("SomeCategory10", null);
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void categoryValidationTest4() throws Exception {
+ updatedServiceDetails.setCategories(null);
+ updatedServiceDetails.addCategoryChain("some Category", null);
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_CATEGORY, new ArrayList<>(Arrays.asList("Service")));
+ }
+
+ @Test
+ public void categoryValidationTest5() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails.addCategory("Network L1-3");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void categoryValidationTest6() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails = serviceDetails;
+ List<CategoryDefinition> categories = updatedServiceDetails.getCategories();
+ CategoryDefinition categoryDefinition = categories.get(0);
+ CategoryDefinition categoryDefinition2 = categoryDefinition;
+ categoryDefinition2.setName("ccc");
+ categories.set(0, categoryDefinition2);
+ updatedServiceDetails.setCategories(categories);
+ RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ validateResponse(updateServiceResponse2, 400, ActionStatus.SERVICE_CATEGORY_CANNOT_BE_CHANGED, listForMessage);
+ getServiceAndValidate(serviceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void categoryValidationTest7() throws Exception {
+ updatedServiceDetails.removeAllCategories();
+ updatedServiceDetails.addCategory(ServiceCategoriesEnum.NETWORK_L3.getValue());
+ correctUpdate();
+ }
+
+ @Test
+ public void categoryValidationTest8() throws Exception {
+ updatedServiceDetails.setCategories(null);
+ updatedServiceDetails.addCategoryChain("Network L1-3", null);
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest1() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(multipleString("a", 49), updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest2() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(multipleString("B", 50), updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest3() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(multipleString("A", 50), multipleString("B", 50), updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest5() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("testTaG", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest6() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Testtag", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest7() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test_tag", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest8() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test tag", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest9() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test-tag", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest10() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Test.tag", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest11() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("...1...", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest12() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("-a_1. Arrrrrr", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest13() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("Testtag1234567890", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest14() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("1", "2", "2", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest15() throws Exception {
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("TestTaG", updatedServiceDetails.getName())));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void tagsValidationTest16() throws Exception {
+ // addMandatoryArtifactsToService();
+ LifecycleRestUtils.certifyService(serviceDetails);
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("testtagtag", updatedServiceDetails.getName())));
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ checkErrorResponse(ActionStatus.RESTRICTED_OPERATION, listForMessage, updateServiceResponse);
+ }
+
+ @Test
+ public void tagsValidationTest17() throws Exception {
+ // addMandatoryArtifactsToService();
+ certifyService(serviceDetails, serviceDetails.getVersion());
+ LifecycleRestUtils.changeServiceState(serviceDetails, sdncDesignerDetails, serviceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ updatedServiceDetails = new ServiceReqDetails(serviceDetails);
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList("TestTaG", updatedServiceDetails.getName())));
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest18() throws Exception {
+ int lengthOfServiceName = updatedServiceDetails.getName().length();
+ int maxLengthTag = 50;
+ int tagsCount = 1024 - lengthOfServiceName;
+ ArrayList<String> tagsList = new ArrayList<>();
+ tagsList.add(updatedServiceDetails.getName());
+ while (tagsCount > maxLengthTag) {
+ tagsList.add(multipleString("a", maxLengthTag));
+ tagsCount -= maxLengthTag + 1 + 1/* (50 and comma of each tag + one space, totally 52) */;
+ }
+ tagsList.add(multipleString("a", tagsCount));
+ updatedServiceDetails.setTags(tagsList);
+ correctUpdate();
+ }
+
+ @Test
+ public void tagsValidationTest19() throws Exception {
+ updatedServiceDetails.setTags(new ArrayList<>(Arrays.asList(" Tag ", updatedServiceDetails.getName())));
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse1);
+ assertNotNull(updateServiceResponse1.getErrorCode());
+ assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse1);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void tagsValidationTest20() throws Exception {
+ ArrayList<String> tagsList = new ArrayList<>();
+ tagsList.add(updatedServiceDetails.getName());
+ tagsList.add("");
+ updatedServiceDetails.setTags(tagsList);
+ updateWithInvalidValue(ActionStatus.INVALID_FIELD_FORMAT, Arrays.asList("Service", "tag"));
+ }
+
+ // ------------------------------------------invalid
+ // values------------------------------------------
+
+ @Test
+ public void tagsValidationTest21() throws Exception {
+ ArrayList<String> tagsList = new ArrayList<>();
+ tagsList.add("onetag");
+ updatedServiceDetails.setTags(tagsList);
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME, listForMessage);
+
+ }
+
+ @Test
+ public void tagsValidationTest22() throws Exception {
+ specialCharsChecking("tags");
+ }
+
+ @Test
+ public void descriptionValidationTest1() throws Exception {
+ updatedServiceDetails.setDescription(multipleString("a", 1023));
+ correctUpdate();
+ }
+
+ @Test
+ public void descriptionValidationTest2() throws Exception {
+ updatedServiceDetails.setDescription(multipleString("a", 1024));
+ correctUpdate();
+ }
+
+ @Test
+ public void descriptionValidationTest3() throws Exception {
+ updatedServiceDetails.setDescription(multipleString("aB", 1024 / 2));
+ correctUpdate();
+ }
+
+ @Test
+ public void descriptionValidationTest4() throws Exception {
+ updatedServiceDetails.setDescription("1234567890");
+ correctUpdate();
+ }
+
+ @Test
+ public void descriptionValidationTest5() throws Exception {
+ updatedServiceDetails.setDescription("desc ription");
+ correctUpdate();
+ }
+
+ @Test
+ public void descriptionValidationTest6() throws Exception {
+ updatedServiceDetails.setDescription("desc\tription");
+ RestResponse updateServiceResponse1 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse1);
+ assertNotNull(updateServiceResponse1.getErrorCode());
+ assertEquals(200, updateServiceResponse1.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("desc ription");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse1);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest7() throws Exception {
+ updatedServiceDetails.setDescription("desc ription ");
+ RestResponse updateServiceResponse2 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse2);
+ assertNotNull(updateServiceResponse2.getErrorCode());
+ assertEquals(200, updateServiceResponse2.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("desc ription");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse2);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest8() throws Exception {
+ updatedServiceDetails.setDescription("desc" + StringUtils.LF + "ription");
+ RestResponse updateServiceResponse3 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse3);
+ assertNotNull(updateServiceResponse3.getErrorCode());
+ assertEquals(200, updateServiceResponse3.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("desc ription");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse3);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest9() throws Exception {
+ updatedServiceDetails.setDescription("<html>Hello, <b>world!</b></html>");
+ RestResponse updateServiceResponse4 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse4);
+ assertNotNull(updateServiceResponse4.getErrorCode());
+ assertEquals(200, updateServiceResponse4.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("Hello, world!");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse4);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest10() throws Exception {
+ updatedServiceDetails.setDescription("\uC2B5");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_DESCRIPTION, new ArrayList<>(Arrays.asList("Service")));
+
+ }
+
+ @Test
+ public void descriptionValidationTest10_a() throws Exception {
+ updatedServiceDetails.setDescription("æ–‡");
+ updateWithInvalidValue(ActionStatus.COMPONENT_INVALID_DESCRIPTION, new ArrayList<>(Arrays.asList("Service")));
+
+ }
+
+ @Test
+ public void descriptionValidationTest10_b() throws Exception {
+ updatedServiceDetails.setDescription("\uC2B5");
+ RestResponse updateServiceResponse5 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse5);
+ assertNotNull(updateServiceResponse5.getErrorCode());
+ assertEquals(200, updateServiceResponse5.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("abc");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse5);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ }
+
+ @Test
+ public void descriptionValidationTest11() throws Exception {
+ updatedServiceDetails.setDescription("&<>");
+ RestResponse updateServiceResponse6 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse6);
+ assertNotNull(updateServiceResponse6.getErrorCode());
+ assertEquals(200, updateServiceResponse6.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("&amp;&lt;&gt;");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse6);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest12() throws Exception {
+ updatedServiceDetails.setDescription("æ–‡ test");
+ RestResponse updateServiceResponse7 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse7);
+ assertNotNull(updateServiceResponse7.getErrorCode());
+ assertEquals(200, updateServiceResponse7.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("test");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse7);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest13() throws Exception {
+ updatedServiceDetails.setDescription(" description");
+ RestResponse updateServiceResponse8 = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse8);
+ assertNotNull(updateServiceResponse8.getErrorCode());
+ assertEquals(200, updateServiceResponse8.getErrorCode().intValue());
+ updatedServiceDetails.setDescription("description");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse8);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ }
+
+ @Test
+ public void descriptionValidationTest14() throws Exception {
+ updatedServiceDetails.setDescription(multipleString("a", 1025));
+ updateWithInvalidValue(ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, new ArrayList<>(Arrays.asList("Service", "1024")));
+ }
+
+ @Test
+ public void projectCodeValidationTest1() throws Exception {
+ String desc = StringUtils.EMPTY;
+ for (int i = 0; i < 10; i++) {
+ desc += Integer.toString(i);
+ if (i >= 4) {
+ updatedServiceDetails.setProjectCode(desc);
+ correctUpdate();
+ }
+ }
+ }
+
+ @Test
+ public void projectCodeValidationTest2() throws Exception {
+ updatedServiceDetails.setProjectCode(multipleString("1", 6));
+ correctUpdate();
+ }
+
+ @Test
+ public void projectCodeValidationTest3() throws Exception {
+ this.specialCharsChecking("projectCode");
+ }
+
+ // TODO Irrelevant
+ @Test(enabled = false)
+ public void projectCodeValidationTest4() throws Exception {
+ updatedServiceDetails.setProjectCode(multipleString(" ", 5) + "99999");
+ RestResponse updateServiceResponse = ServiceRestUtils.updateService(updatedServiceDetails, sdncDesignerDetails);
+ assertNotNull(updateServiceResponse);
+ assertNotNull(updateServiceResponse.getErrorCode());
+ assertEquals(200, updateServiceResponse.getErrorCode().intValue());
+ updatedServiceDetails.setProjectCode("12345");
+ validateActualVsExpected(updatedServiceDetails, updateServiceResponse);
+ getServiceAndValidate(updatedServiceDetails, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+
+ }
+
+ @Test
+ public void projectCodeValidationTest5() throws Exception {
+ updatedServiceDetails.setProjectCode(multipleString("0", 11));
+ updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage);
+ }
+
+ @Test
+ public void projectCodeValidationTest6() throws Exception {
+ updatedServiceDetails.setProjectCode(multipleString("1", 4));
+ updateWithInvalidValue(ActionStatus.INVALID_PROJECT_CODE, listForMessage);
+ }
+
+ @Test
+ public void projectCodeValidationTest7() throws Exception {
+ updatedServiceDetails.setProjectCode("123456789");
+ correctUpdate();
+ }
+
+ // ////US553874
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion01_isVNF_toTrue() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to True
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 200, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion02_isVNF_toFalse() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to True
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 200, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion01_isVNF_TrueToNull() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to True
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 400, restResponse.getErrorCode().intValue());
+ // List<String> variables = Arrays.asList("VNF Service Indicator");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(),
+ // variables, restResponse.getResponse());
+ //
+ // //get service and verify that service created with isVNF is remained with
+ // isVNF = true
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion01_isVNF_FalseToNull() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to True
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 400, restResponse.getErrorCode().intValue());
+ // List<String> variables = Arrays.asList("VNF Service Indicator");
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.MISSING_DATA.name(),
+ // variables, restResponse.getResponse());
+ //
+ // //get service and verify that service created with isVNF is remained with
+ // isVNF = true
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion02_IsVNF_toTrue() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // LifecycleRestUtils.changeServiceState(serviceDetails,
+ // sdncDesignerDetails, serviceDetails.getVersion(),
+ // LifeCycleStatesEnum.CHECKIN);
+ // LifecycleRestUtils.changeServiceState(serviceDetails,
+ // sdncDesignerDetails, serviceDetails.getVersion(),
+ // LifeCycleStatesEnum.CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to True
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 200, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion02_IsVNF_toFalse() throws Exception{
+ //
+ // //choose the user to create service
+ // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // LifecycleRestUtils.changeServiceState(serviceDetails,
+ // sdncDesignerDetails, serviceDetails.getVersion(),
+ // LifeCycleStatesEnum.CHECKIN);
+ // LifecycleRestUtils.changeServiceState(serviceDetails,
+ // sdncDesignerDetails, serviceDetails.getVersion(),
+ // LifeCycleStatesEnum.CHECKOUT);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //
+ // //Update Service IsVNF to false
+ // restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // //restResponse =
+ // ServiceRestUtils.updateService(serviceDetails.getUniqueId(),
+ // serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 200, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion11_IsVNF_toFalse() throws Exception{
+ // // Can't update isVNF when service version is 1.X
+ // User sdncUserDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // //String serviceUniqueName =
+ // ServiceRestUtils.getServiceUniqueId(serviceByNameAndVersion);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails, "0.1",
+ // sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //// ServiceRestUtils.addServiceMandatoryArtifacts(sdncUserDetails,
+ // restResponse);
+ // RestResponse response =
+ // ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ // sdncUserDetails, serviceDetails.getUniqueId(),
+ // ComponentTypeEnum.SERVICE);
+ // assertTrue("response code is not 201, returned: " +
+ // response.getErrorCode(),response.getErrorCode() == 201);
+ // RestResponse changeServiceState =
+ // LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ // assertTrue("certify service request returned status:" +
+ // changeServiceState.getErrorCode(),changeServiceState.getErrorCode() ==
+ // 200);
+ // LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails,
+ // LifeCycleStatesEnum.CHECKOUT);
+ //
+ // //Update Service IsVNF to false
+ // restResponse = ServiceRestUtils.updateService(serviceDetails,
+ // sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating service metadata", 400,
+ // restResponse.getErrorCode().intValue());
+ // List<String> variables = new ArrayList<String>();
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_IS_VNF_CANNOT_BE_CHANGED.name(),
+ // variables, restResponse.getResponse());
+ //
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "1.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ //
+ // }
+ //
+ // @JsonIgnore
+ // @Test
+ // public void UpdateServiceVersion11_IsVNF_toTrue() throws Exception{
+ // // Can't update isVNF when service version is 1.X
+ // User sdncUserDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // // new service details
+ // // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // // clean audit DB before updating service
+ // DbUtils.cleanAllAudits();
+ // ServiceRestUtils.deleteServiceById(serviceDetails.getUniqueId(),
+ // sdncUserDetails.getUserId());
+ // serviceDetails = ElementFactory.getDefaultService();
+ //
+ // //send create service toward BE
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating Interface Artifact",
+ // 201, restResponse.getErrorCode().intValue());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // RestResponse serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "0.1");
+ // Service serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // //String serviceUniqueName =
+ // ServiceRestUtils.getServiceUniqueId(serviceByNameAndVersion);
+ //
+ // //validate audit
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceValidationUtils.constructFieldsForAuditValidation(serviceDetails,
+ // "0.1", sdncUserDetails);
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //// ServiceRestUtils.addServiceMandatoryArtifacts(sdncUserDetails,
+ // restResponse);
+ // RestResponse response =
+ // ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails,
+ // sdncUserDetails, serviceDetails.getUniqueId(),
+ // ComponentTypeEnum.SERVICE);
+ // assertTrue("response code is not 201, returned: " +
+ // response.getErrorCode(),response.getErrorCode() == 201);
+ // RestResponse changeServiceState =
+ // LCSbaseTest.certifyService(serviceDetails, sdncDesignerDetails);
+ // assertTrue("certify service request returned status:" +
+ // changeServiceState.getErrorCode(),changeServiceState.getErrorCode() ==
+ // 200);
+ // LifecycleRestUtils.changeServiceState(serviceDetails, sdncUserDetails,
+ // LifeCycleStatesEnum.CHECKOUT);
+ //
+ // //Update Service IsVNF to false
+ // restResponse = ServiceRestUtils.updateService(serviceDetails,
+ // sdncUserDetails);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after updating service metadata", 400,
+ // restResponse.getErrorCode().intValue());
+ // List<String> variables = new ArrayList<String>();
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.SERVICE_IS_VNF_CANNOT_BE_CHANGED.name(),
+ // variables, restResponse.getResponse());
+ //
+ // //get service and verify that service created with isVNF defined in
+ // serviceDetails
+ // serviceByNameAndVersion =
+ // ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails,
+ // serviceDetails.getName(), "1.1");
+ // serviceObject =
+ // ResponseParser.convertServiceResponseToJavaObject(serviceByNameAndVersion.getResponse());
+ // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails,
+ // serviceObject, sdncUserDetails,
+ // LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ // }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java
new file mode 100644
index 0000000000..c83018241b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/ActivateDeActivateDeleteUser.java
@@ -0,0 +1,832 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.user;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.http.HttpStatus;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.users.UserResponseMessageEnum;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ResourceValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.UserValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.google.gson.reflect.TypeToken;
+
+/**
+ * @author alitvinsky
+ *
+ */
+public class ActivateDeActivateDeleteUser extends ComponentBaseTest {
+ private static Logger logger = LoggerFactory.getLogger(ActivateDeActivateDeleteUser.class.getName());
+ protected Gson gson = new Gson();
+ protected User sdncAdminUser;
+
+ @BeforeMethod
+ public void init() {
+ sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ }
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ActivateDeActivateDeleteUser() {
+ super(name, ActivateDeActivateDeleteUser.class.getName());
+ }
+
+ @Test
+ public void authorizeDeActivatedUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ AssertJUnit.assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ // clean audit before authorization test
+ DbUtils.cleanAllAudits();
+
+ // Perform login from WebSeal
+ User sealUserDetails = sdncUserDetails;
+ RestResponse authorizedUserResponse = UserRestUtils.authorizedUserTowardsCatalogBeQA(sealUserDetails);
+
+ // validate response
+
+ ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_ACCESS.name());
+
+ AssertJUnit.assertNotNull("check response object is not null after user login", authorizedUserResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after user login",
+ authorizedUserResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after deActive user", errorInfo2.getCode(),
+ authorizedUserResponse.getErrorCode());
+
+ List<String> variables2 = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESTRICTED_ACCESS.name(), variables2,
+ authorizedUserResponse.getResponse());
+
+ // validate against ES DB
+
+ UserValidationUtils.validateDataAgainstAuditDB_access(sealUserDetails,
+ DbUtils.parseAuditRespByAction("Access"), authorizedUserResponse, errorInfo2, variables2);
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ public User getDefaultUserDetails() {
+
+ String httpCspUserId = "km2000";
+ String userFirstName = "Kot";
+ String userLastName = "May";
+ String email = "km2000@intl.sdc.com";
+ String role = UserRoleEnum.ADMIN.name();
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ return sdncUserDetails;
+ }
+
+ public void validateSuccessCreateUserResponse(User sdncUserDetails, RestResponse createUserResponse)
+ throws Exception {
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", createUserResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create user",
+ createUserResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create user", HttpStatus.SC_CREATED,
+ createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+ // UserRestUtils.validateAddUserAuditMessage(sdncUserDetails,
+ // sdncAdminUser, String.valueOf(HttpStatus.SC_CREATED),
+ // UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ // UserRestUtils.getAddUserAuditMessage("AddUser"));
+ String addUser = "AddUser";
+ ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(addUser,
+ sdncAdminUser, ActionStatus.CREATED, sdncUserDetails, null);
+ AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, addUser);
+
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+
+ }
+
+ public void validateSuccessDeActivateUserResponse(User sdncUserDetails, RestResponse deActivateUserResponse)
+ throws Exception {
+
+ AssertJUnit.assertNotNull("check response object is not null after deActive user", deActivateUserResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after deActive user",
+ deActivateUserResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after deActive user", 200,
+ deActivateUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, deActivateUserResponse.getResponse());
+
+ String deleteUser = "DeleteUser";
+ ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor
+ .constructFieldsForAuditValidation(deleteUser, sdncAdminUser, ActionStatus.OK, null, sdncUserDetails);
+ AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, deleteUser);
+
+ }
+
+ // US498322 - Add Status Field to USER
+
+ @Test
+ public void createNewUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ @Test
+ public void createDefaultUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+ sdncUserDetails.setFirstName(null);
+ sdncUserDetails.setLastName(null);
+ sdncUserDetails.setEmail(null);
+ sdncUserDetails.setRole(null);
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ @Test
+ public void createTesterUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+ sdncUserDetails.setLastName(null);
+ sdncUserDetails.setRole(UserRoleEnum.TESTER.name());
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ @Test
+ public void deActivateCreatedAdminUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ assertEquals("Check response code after get user", errorInfo.getCode(), getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ @Test
+ public void deActivateTheSameUserTwice() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ // deActivate the same user once time more
+ RestResponse deActivateUserResponse2 = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ assertEquals("Check response code after deActive user", errorInfo2.getCode(),
+ deActivateUserResponse2.getErrorCode());
+
+ List<String> variables2 = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables2,
+ deActivateUserResponse2.getResponse());
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ @Test
+ public void createAgainDeActivatedUser() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+
+ try {
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ // create the user with the same UserId(details) as deActivated user
+ DbUtils.cleanAllAudits();
+
+ RestResponse createUserResponse2 = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ ErrorInfo errorInfo2 = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ assertEquals("Check response code after deActive user", errorInfo2.getCode(),
+ createUserResponse2.getErrorCode());
+
+ List<String> variables2 = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables2,
+ createUserResponse2.getResponse());
+
+ } finally {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ // very not recommend to run this test, resources/services may be zombie
+ // @Test
+ public void deActivateLastAdminUser() throws Exception {
+
+ try {
+
+ // send get all ADMIN user request toward BE
+ RestResponse getAllAdminUsers = UserRestUtils.getAllAdminUsers(sdncAdminUser);
+
+ assertNotNull("check response object is not null after create user", getAllAdminUsers);
+ assertNotNull("check error code exists in response after create user", getAllAdminUsers.getErrorCode());
+ assertEquals("Check response code after create user", 200, getAllAdminUsers.getErrorCode().intValue());
+
+ TypeToken<List<User>> typeToken = new TypeToken<List<User>>() {
+ };
+ List<User> listOfUsersOnResponse = gson.fromJson(getAllAdminUsers.getResponse(), typeToken.getType());
+ logger.debug("listOfUsers: {}", listOfUsersOnResponse);
+
+ // build map of all Admin users from listOfUsersOnResponse from
+ // response
+ Map<String, User> mapAllUsersOnResponse = new HashMap<String, User>();
+ for (User sdncUser : listOfUsersOnResponse) {
+ mapAllUsersOnResponse.put(sdncUser.getUserId(), sdncUser);
+ }
+
+ // remove from mapAllUsersOnResponse map one of admin users
+ mapAllUsersOnResponse.remove(sdncAdminUser.getUserId());
+ logger.debug("map Of all Admin users exclude one : {}", mapAllUsersOnResponse);
+
+ // deActivate all Admin users from the userIdAllAdminList list
+ for (Entry<String, User> entry : mapAllUsersOnResponse.entrySet()) {
+ UserRestUtils.deActivateUser(entry.getValue(), sdncAdminUser);
+ }
+
+ // deActivate last Admin user user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncAdminUser, sdncAdminUser);
+
+ ErrorInfo errorInfo = ErrorValidationUtils
+ .parseErrorConfigYaml(ActionStatus.DELETE_USER_ADMIN_CONFLICT.name());
+
+ assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ deActivateUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList();
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.DELETE_USER_ADMIN_CONFLICT.name(), variables,
+ deActivateUserResponse.getResponse());
+
+ } finally {
+ // UserRestUtils.deleteUser(UserRestUtils.getAdminDetails2(),
+ // sdncAdminUser);
+ // UserRestUtils.deleteUser(UserRestUtils.getAdminDetails3(),
+ // sdncAdminUser);
+ // UserRestUtils.createUser(UserRestUtils.getAdminDetails2(),
+ // sdncAdminUser);
+ // UserRestUtils.createUser(UserRestUtils.getAdminDetails3(),
+ // sdncAdminUser);
+ }
+
+ }
+
+ // test check the resource accessibility via catalog view, resource was
+ // created by user which was deActivated
+
+ @Test
+ public void resourceAccessibility() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource("tosca.nodes.newresource4test4",
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ String resourceBaseVersion = "0.1";
+
+ try {
+ // Delete resource
+ // resourceUtils.deleteResource_allVersions(resourceDetails,
+ // sdncAdminUser);
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+
+ DbUtils.cleanAllAudits();
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // ------------------------Start create
+ // resource---------------------------------------------------------------------------------
+
+ // create resource
+ RestResponse createResponse = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ assertEquals("Check response code after create", 201, createResponse.getErrorCode().intValue());
+
+ Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResponse.getResponse());
+
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncUserDetails,
+ createdResource.getUniqueId());
+ assertEquals("Check response code after get", 200, resourceGetResponse.getErrorCode().intValue());
+
+ // validate get response
+ ResourceRespJavaObject resourceRespJavaObject = Convertor.constructFieldsForRespValidation(resourceDetails,
+ resourceBaseVersion);
+ resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setAbstractt("false");
+ resourceRespJavaObject.setCreatorUserId(sdncUserDetails.getUserId());
+ resourceRespJavaObject.setLastUpdaterUserId(sdncUserDetails.getUserId());
+
+ resourceRespJavaObject
+ .setCreatorFullName(sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName());
+ resourceRespJavaObject
+ .setLastUpdaterFullName(sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName());
+
+ ResourceValidationUtils.validateResp(resourceGetResponse, resourceRespJavaObject);
+
+ // ------------------------End create
+ // resource---------------------------------------------------------------------------------
+
+ // clean audit before authorization test
+ DbUtils.cleanAllAudits();
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ UserValidationUtils.validateDeleteUserAuditMessage(sdncUserDetails, sdncAdminUser, "200",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("DeleteUser"));
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ // checking if created resource is accessible
+ DbUtils.cleanAllAudits();
+
+ RestResponse getCatalogDataResponse = CatalogRestUtils.getCatalog(sdncAdminUser.getUserId());
+
+ // validate response
+
+ assertNotNull("check response object is not null after user login", getCatalogDataResponse);
+ assertNotNull("check error code exists in response after user login",
+ getCatalogDataResponse.getErrorCode());
+ assertEquals("Check response code after deActive user", 200,
+ getCatalogDataResponse.getErrorCode().intValue());
+
+ // expected resource list
+ List<String> resourceExpectedUniqIdList = new ArrayList<String>();
+ resourceExpectedUniqIdList.add(resourceDetails.getUniqueId());
+ logger.debug("resourceExpectedUniqIdList: {}", resourceExpectedUniqIdList);
+
+ compareResourceUniqIdList(getCatalogDataResponse.getResponse(), resourceExpectedUniqIdList, true);
+
+ } finally {
+ // resourceUtils.deleteResource_allVersions(resourceDetails,
+ // sdncAdminUser);
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ // test check the resource accessibility via catalog view, resource was
+ // created by user which was deActivated
+
+ @Test
+ public void resourceAccessibilityOnImport() throws Exception {
+
+ User sdncUserDetails = getDefaultUserDetails();
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource("importResource4test",
+ NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, "jh0003");
+ resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(),
+ ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory());
+ // String resourceBaseVersion = "1.0";
+
+ try {
+ // Delete resource
+ // resourceUtils.deleteResource_allVersions(resourceDetails,
+ // sdncAdminUser);
+ RestResponse deleteUserResponse = UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ assertTrue("delete user request failed",
+ deleteUserResponse.getErrorCode() == 200 || deleteUserResponse.getErrorCode() == 404);
+ DbUtils.cleanAllAudits();
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+
+ // ------------------------Start import
+ // resource---------------------------------------------------------------------------------
+
+ // import new resource with CERTIFIED state
+ User importer = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN4);
+ RestResponse importResponse = ImportRestUtils.importResourceByName(resourceDetails, importer);
+
+ assertNotNull("check response object is not null after create user", importResponse);
+ assertNotNull("check error code exists in response after create user", importResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, importResponse.getErrorCode().intValue());
+
+ // ------------------------End import
+ // resource---------------------------------------------------------------------------------
+
+ // clean audit before authorization test
+ DbUtils.cleanAllAudits();
+
+ // deActivate created user
+ RestResponse deActivateUserResponse = UserRestUtils.deActivateUser(sdncUserDetails, sdncAdminUser);
+ sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ validateSuccessDeActivateUserResponse(sdncUserDetails, deActivateUserResponse);
+
+ UserValidationUtils.validateDeleteUserAuditMessage(sdncUserDetails, sdncAdminUser, "200",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("DeleteUser"));
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+
+ assertEquals("Check response code after deActive user", errorInfo.getCode(),
+ getUserResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), variables,
+ getUserResponse.getResponse());
+
+ // checking if created resource is accessible
+ DbUtils.cleanAllAudits();
+
+ RestResponse getCatalogDataResponse = CatalogRestUtils.getCatalog(sdncAdminUser.getUserId());
+
+ // validate response
+
+ assertNotNull("check response object is not null after user login", getCatalogDataResponse);
+ assertNotNull("check error code exists in response after user login",
+ getCatalogDataResponse.getErrorCode());
+ assertEquals("Check response code after deActive user", 200,
+ getCatalogDataResponse.getErrorCode().intValue());
+
+ // expected resource list
+ List<String> resourceExpectedUniqIdList = new ArrayList<String>();
+ resourceExpectedUniqIdList.add(resourceDetails.getUniqueId());
+ logger.debug("resourceExpectedUniqIdList: {}", resourceExpectedUniqIdList);
+
+ compareResourceUniqIdList(getCatalogDataResponse.getResponse(), resourceExpectedUniqIdList, true);
+
+ } finally {
+ // resourceUtils.deleteResource_allVersions(resourceDetails,
+ // sdncAdminUser);
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ }
+
+ }
+
+ // test check the service accessibility via catalog view, service was
+ // created by user which was deActivated
+
+ // @Test
+ // public void serviceAccessibility() throws Exception{
+ //
+ // User sdncUserDetails = getDefaultUserDetails();
+ //// fill new service details
+ // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ // String serviceBaseVersion = "0.1";
+ //
+ // try{
+ // //Delete service
+ //// ServiceRestUtils.deleteService_allVersions(serviceDetails,
+ // sdncAdminUser);
+ // UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ //
+ // DbUtils.cleanAllAudits();
+ // RestResponse createUserResponse =
+ // UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ // validateSuccessCreateUserResponse(sdncUserDetails, createUserResponse);
+ //
+ //// ------------------------Start create
+ // service---------------------------------------------------------------------------------
+ // RestResponse restResponse =
+ // ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ //
+ // assertNotNull("check response object is not null after create service",
+ // restResponse);
+ // assertNotNull("check error code exists in response after create service",
+ // restResponse.getErrorCode());
+ // assertEquals("Check response code after create service", 201,
+ // restResponse.getErrorCode().intValue());
+ //
+ //// validate create service response vs actual
+ //
+ // Service service =
+ // ServiceRestUtils.convertServiceResponseToJavaObject(restResponse.getResponse());
+ // UserValidationUtils.validateServiceResponseMetaData(serviceDetails,service,sdncUserDetails,
+ // (LifecycleStateEnum)null);
+ //
+ //// validate get service response vs actual
+ // restResponse = ServiceRestUtils.getService(serviceDetails.getUniqueId(),
+ // sdncUserDetails);
+ // service =
+ // ServiceRestUtils.convertServiceResponseToJavaObject(restResponse.getResponse());
+ // UserValidationUtils.validateServiceResponseMetaData(serviceDetails,service,sdncUserDetails,
+ // (LifecycleStateEnum)null);
+ //
+ // //validate audit
+ //
+ // ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ // ServiceRestUtils.constructFieldsForAuditValidation(serviceDetails,
+ // serviceBaseVersion, sdncUserDetails);
+ //
+ // String auditAction="Create";
+ // expectedResourceAuditJavaObject.setAction(auditAction);
+ // expectedResourceAuditJavaObject.setPrevState("");
+ // expectedResourceAuditJavaObject.setPrevVersion("");
+ // expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ // expectedResourceAuditJavaObject.setStatus("201");
+ // expectedResourceAuditJavaObject.setDesc("OK");
+ //
+ // AuditValidationUtils.validateAudit(expectedResourceAuditJavaObject,
+ // auditAction, null, false);
+ //
+ //// ------------------------End create
+ // service---------------------------------------------------------------------------------
+ //
+ //// clean audit before authorization test
+ // DbUtils.cleanAllAudits();
+ //
+ //// deActivate created user
+ // RestResponse deActivateUserResponse =
+ // UserRestUtils.deActivateUser(sdncUserDetails,sdncAdminUser);
+ // sdncUserDetails.setStatus(UserStatusEnum.INACTIVE);
+ // validateSuccessDeActivateUserResponse(sdncUserDetails,
+ // deActivateUserResponse);
+ //
+ // UserValidationUtils.validateDeleteUserAuditMessage(sdncUserDetails,
+ // sdncAdminUser, "200", UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ // UserValidationUtils.getAddUserAuditMessage("DeleteUser"));
+ //
+ // ErrorInfo errorInfo =
+ // ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_INACTIVE.name());
+ // RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails,
+ // sdncAdminUser);
+ //
+ // assertEquals("Check response code after deActive user",
+ // errorInfo.getCode(), getUserResponse.getErrorCode());
+ //
+ // List<String> variables = Arrays.asList(sdncUserDetails.getUserId());
+ // ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(),
+ // variables, getUserResponse.getResponse());
+ //
+ // //checking if created service is accessible
+ // DbUtils.cleanAllAudits();
+ //
+ // RestResponse getCatalogDataResponse =
+ // CatalogRestUtils.getCatalog(sdncAdminUser.getUserId());
+ //
+ // //validate response
+ //
+ // assertNotNull("check response object is not null after user login",
+ // getCatalogDataResponse);
+ // assertNotNull("check error code exists in response after user login",
+ // getCatalogDataResponse.getErrorCode());
+ // assertEquals("Check response code after deActive user", 200,
+ // getCatalogDataResponse.getErrorCode().intValue());
+ //
+ //// expected service list
+ // List<String> serviceExpectedUniqIdList= new ArrayList<String>();
+ // serviceExpectedUniqIdList.add(serviceDetails.getUniqueId());
+ // logger.debug("serviceExpectedUniqIdList: {}", serviceExpectedUniqIdList);
+ //
+ // compareServiceUniqIdList(getCatalogDataResponse.getResponse(),
+ // serviceExpectedUniqIdList, true);
+ //
+ //
+ // }finally{
+ //// ServiceRestUtils.deleteService_allVersions(serviceDetails,
+ // sdncAdminUser);
+ // UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ // }
+ //
+ // }
+
+ public void compareServiceUniqIdList(String response, List<String> expectedList, boolean flag) {
+
+ JsonElement jelement = new JsonParser().parse(response);
+ JsonObject jobject = jelement.getAsJsonObject();
+ JsonArray serviceArray = (JsonArray) jobject.get("services");
+ logger.debug("{}", serviceArray);
+ assertTrue("expected service count: " + expectedList.size() + " or more" + ", actual: " + serviceArray.size(),
+ serviceArray.size() >= expectedList.size());
+
+ // build service list from response
+ List<ServiceReqDetails> serviceReqDetailsListOnResponse = new ArrayList<ServiceReqDetails>();
+ for (int i = 0; i < serviceArray.size(); i++) {
+ ServiceReqDetails json = gson.fromJson(serviceArray.get(i), ServiceReqDetails.class);
+ serviceReqDetailsListOnResponse.add(json);
+ }
+ }
+
+ public void compareResourceUniqIdList(String response, List<String> expectedList, boolean flag) {
+
+ JsonElement jelement = new JsonParser().parse(response);
+ JsonObject jobject = jelement.getAsJsonObject();
+ JsonArray resourceArray = (JsonArray) jobject.get("resources");
+ logger.debug("{}", resourceArray);
+ assertTrue("expected resource count: " + expectedList.size() + " or more" + ", actual: " + resourceArray.size(),
+ resourceArray.size() >= expectedList.size());
+
+ // build resource list from response
+ List<ResourceReqDetails> resourceReqDetailsListOnResponse = new ArrayList<ResourceReqDetails>();
+ for (int i = 0; i < resourceArray.size(); i++) {
+ ResourceReqDetails json = gson.fromJson(resourceArray.get(i), ResourceReqDetails.class);
+ resourceReqDetailsListOnResponse.add(json);
+ }
+
+ logger.debug("ResourceReqDetails list on response: {}", resourceReqDetailsListOnResponse);
+
+ List<String> resourceActualUniqIdList = new ArrayList<String>();
+ for (ResourceReqDetails resource : resourceReqDetailsListOnResponse) {
+ resourceActualUniqIdList.add(resource.getUniqueId());
+ }
+ logger.debug("resourceActualUniqIdList on response: {}", resourceActualUniqIdList);
+ logger.debug("resourceExpectedUniqIdList on response: {}", expectedList);
+
+ if (flag) {
+ assertTrue("actual list does not contain expected list",
+ resourceActualUniqIdList.containsAll(expectedList));
+ } else {
+ assertFalse("actual list contains non expected list elements",
+ resourceActualUniqIdList.containsAll(expectedList));
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java
new file mode 100644
index 0000000000..8684910a18
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/CreateUserApiTest.java
@@ -0,0 +1,1451 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.user;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.IOException;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.users.UserResponseMessageEnum;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.Convertor;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.UserRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.UserValidationUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class CreateUserApiTest extends ComponentBaseTest {
+
+ protected User sdncAdminUser;
+ protected User sdncDesignerUser;
+ protected User sdncGovernorUser;
+ protected User sdncTesterUser;
+
+ public static final int STATUS_CODE_SUCCESS = 200;
+ public static final int STATUS_CODE_SUCSESS_CREATED = 201;
+ public static final int STATUS_CODE_SUCCESS_DELETE_GET = 200;
+ public static final int STATUS_CODE_INVALID_CONTENT = 400;
+ public static final int STATUS_CODE_MISSING_DATA = 400;
+ public static final int STATUS_CODE_MISSING_INFORMATION = 403;
+ public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
+ public static final int STATUS_CODE_NOT_FOUND = 404;
+ public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
+ public static final int USER_ALREADY_EXIST = 409;
+ public static final int INVALID_ROLE = 400;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CreateUserApiTest() {
+ super(name, CreateUserApiTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void init() {
+ sdncAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ sdncDesignerUser = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncGovernorUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ sdncTesterUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+
+ }
+
+ // Story : REST API to provision new user (POST) - US429379
+ // must parameters: UserId and Email
+
+ // **********************************************************201***************************************************
+ // create user with full parameter set(UserID, First Name, Last Name, Email,
+ // Role = "DESIGNER", Creator details)
+ // expected 201 Created
+ @Test
+ public void createUser() throws Exception {
+
+ // user initialization
+ String httpCspUserId = "km2000";
+ String userFirstName = "Kot";
+ String userLastName = "Matroskin";
+ String email = "km2000@intl.sdc.com";
+ String role = "ADMIN";
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ String addUser = "AddUser";
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+
+ AssertJUnit.assertNotNull("check response object is not null after create user", createUserResponse);
+ AssertJUnit.assertNotNull("check error code exists in response after create user",
+ createUserResponse.getErrorCode());
+ AssertJUnit.assertEquals("Check response code after create user", 201,
+ createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+
+ ExpectedUserCRUDAudit constructFieldsForAuditValidation = Convertor.constructFieldsForAuditValidation(addUser,
+ sdncAdminUser, ActionStatus.CREATED, sdncUserDetails, null);
+ AuditValidationUtils.validateAddUserAudit(constructFieldsForAuditValidation, addUser);
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+ }
+
+ protected static final String ADD_USER = "AddUser";
+
+ private User mechIdUser = new User();
+ private User emptyUser = new User();
+ private static final User adminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+
+ @AfterMethod
+ public void setup() throws IOException {
+ UserRestUtils.deactivateUser(mechIdUser, adminUser);
+ }
+
+ // create default user(UserID, Email, Creator details)
+ // expected: role = DESIGNER, first and last name = null, 201 Created
+ @Test
+ public void createDefaultUser() throws Exception {
+ // user initialization
+ String httpCspUserId = "km2000";
+ String userFirstName = null;
+ String userLastName = null;
+ String email = null;
+ String role = null;
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ deleteUserAndAudit(sdncUserDetails);
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+ UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+
+ }
+
+ // create user with one optional parameter first name (UserID, Email, First
+ // Name, Creator details)
+ // expected: role = DESIGNER, last name = null, 201 Created
+ @Test
+ public void createUserFirstName() throws Exception {
+ // user initialization
+ String httpCspUserId = "km2000";
+ String userFirstName = "Kot";
+ String userLastName = null;
+ String email = null;
+ String role = null;
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ deleteUserAndAudit(sdncUserDetails);
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+ UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+ }
+
+ @Test
+ public void createDeleteOpsUser() throws Exception {
+
+ String httpCspUserId = "oo2000";
+ String userFirstName = "ops";
+ String userLastName = "opsLast";
+ String email = "ops@intl.sdc.com";
+ String role = "OPS";
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ deleteUserAndAudit(sdncUserDetails);
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+ UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ RestResponse getDeletedUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ assertEquals("Check response code after delete user", 404, getDeletedUserResponse.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createDeleteGOVERNORUser() throws Exception {
+
+ String httpCspUserId = "gg2000";
+ String userFirstName = "gov";
+ String userLastName = "govLast";
+ String email = "gov@intl.sdc.com";
+ String role = "GOVERNOR";
+ User sdncUserDetails = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ deleteUserAndAudit(sdncUserDetails);
+ RestResponse createUserResponse = UserRestUtils.createUser(sdncUserDetails, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, createUserResponse.getResponse());
+ UserValidationUtils.validateAddUserAuditMessage(sdncUserDetails, sdncAdminUser, "201",
+ UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ RestResponse getUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(sdncUserDetails, getUserResponse.getResponse());
+
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ RestResponse getDeletedUserResponse = UserRestUtils.getUser(sdncUserDetails, sdncAdminUser);
+ assertEquals("Check response code after delete user", 404, getDeletedUserResponse.getErrorCode().intValue());
+
+ }
+
+ // Benny
+ // Admin Create OPS user
+ @Test
+ public void createOpsUser() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "aa1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedOpsUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedOpsUser, createUserResponse.getResponse());
+ deleteAndCheckUserResponse(expectedOpsUser, 200);
+
+ }
+
+ // Admin Create GOVERNOR user
+ @Test
+ public void createGovernorUser() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "aa1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ User expectedUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedUser, createUserResponse.getResponse());
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedUser, getUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(expectedUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from OPS to GOVERNOR
+ @Test
+ public void updateOpsUserRole() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ab1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Designer Create OPS user -409 Response Restricted operation
+ @Test
+ public void createOpsUserByDesigner() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "aa1122";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedOpsUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncDesignerUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 409, createUserResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create user", "Conflict", createUserResponse.getResponseMessage());
+ }
+
+ // Tester Create OPS user -409 Response Restricted operation
+ @Test
+ public void createOpsUserByTester() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "aa1122";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedOpsUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncTesterUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 409, createUserResponse.getErrorCode().intValue());
+ assertEquals("Check response code after create user", "Conflict", createUserResponse.getResponseMessage());
+ }
+
+ // Designer Try Update OPS user role to GOVERNOR - Response 409
+ @Test
+ public void updateOpsUserRolebyDesigner() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "bt751e";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // Admin create user with OPS role
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // Designer user try to update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncDesignerUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Conflict",
+ updateUserRoleResponse.getResponseMessage());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Tester Try Update OPS user role to GOVERNOR - Response 409
+ @Test
+ public void updateOpsUserRolebyTester() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "bt751w";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // Admin create user with OPS role
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // Designer user try to update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncTesterUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Conflict",
+ updateUserRoleResponse.getResponseMessage());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from OPS to Designer
+ @Test
+ public void updateOpsUserRoleFromOpsToDesigner() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ab1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "DESIGNER";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(designerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(designerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from OPS to TESTER
+ @Test
+ public void updateOpsUserRoleFromOpsToTester() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ac1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "TESTER";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User testerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(testerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(testerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Tester try to Update user role from OPS to GOVERNOR - Response 409
+ // Conflict
+ @Test
+ public void updateOpsUserRoleByTester() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ad1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ // Create user by Admin
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR by Tester
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncTesterUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Conflict",
+ updateUserRoleResponse.getResponseMessage());
+
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Designer try to Update user role from OPS to GOVERNOR - Response 409
+ // Conflict
+ @Test
+ public void updateOpsUserRoleByDesigner() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ad1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ // User governerUser = new User(userFirstName,
+ // userLastName,httpCspUserId, email, updatedRole);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ // Create user by Admin
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR by Tester
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncDesignerUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 409, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Conflict",
+ updateUserRoleResponse.getResponseMessage());
+
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Create OPS user - user already exist
+ @Test
+ public void createOpsUserAlreadyExist() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "af1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "OPS";
+ User expectedOpsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedOpsUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedOpsUser, createUserResponse.getResponse());
+ // Create user that already exists
+ RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedOpsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserAgainResponse);
+ assertNotNull("check error code exists in response after create user", createUserAgainResponse.getErrorCode());
+ assertEquals("Check response code after create user", 409, createUserAgainResponse.getErrorCode().intValue());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(expectedOpsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from OPS to GOVERNOR - user already has GOVERNOR
+ // role
+ @Test
+ public void updateRoleToSameRole() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ag1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "GOVERNOR";
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ RestResponse createUserResponse = UserRestUtils.createUser(opsUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from GOVERNOR to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ opsUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from Tester to GOVERNOR - 200 response
+
+ // Admin Update user role from Designer to GOVERNOR - 200 response
+ @Test
+ public void updateUserRoleDesignerToGovernor() throws Exception {
+ DbUtils.cleanAllAudits();
+ String httpCspUserId = "ah1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "DESIGNER";
+ String updatedRole = "GOVERNOR";
+ User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(designerUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(designerUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from TESTER to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ designerUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+ // Update user role
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(governerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(governerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(designerUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update deactivated user role - response 404 (user not found)
+ @Test
+ public void updateRoleToDeactivatedUser() throws Exception {
+ DbUtils.cleanAllAudits();
+ String httpCspUserId = "aj1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "DESIGNER";
+ String updatedRole = "GOVERNOR";
+ User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User governerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(designerUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(designerUser, createUserResponse.getResponse());
+ deleteAndCheckUserResponse(designerUser, 200);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role - user deActivted
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ designerUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after create user", 404, updateUserRoleResponse.getErrorCode().intValue());
+ }
+
+ // Admin Update user role, user does not exist in DB - response 404 (user
+ // not found)
+ @Test
+ public void updateRoleForNonExistingUser() throws Exception {
+ DbUtils.cleanAllAudits();
+ String httpCspUserId = "aj1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "DESIGNER";
+ String updatedRole = "GOVERNOR";
+ User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ // User governerUser = new User(userFirstName,
+ // userLastName,httpCspUserId, email, updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role - user deActivted
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ designerUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 404, updateUserRoleResponse.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from GOVERNOR to TESTER
+ @Test
+ public void updateRoleFromGovernorToTester() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ak1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "TESTER";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User testerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(testerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(testerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from GOVERNOR to DESIGNER
+ @Test
+ public void updateRoleFromGovernorToDesigner() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ak1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "DESIGNER";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User designerUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(designerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(designerUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role from GOVERNOR to OPS
+ @Test
+ public void updateRoleFromGovernorToOps() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ak1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "OPS";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User opsUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(opsUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(opsUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ deleteAndCheckUserResponse(governorUser, 200);
+
+ }
+
+ private void deleteAndCheckUserResponse(User userDetailes, int expectedResponseCode) throws IOException {
+ RestResponse deleteUser = UserRestUtils.deleteUser(sdncGovernorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteUser);
+ assertEquals("Check response code after deleting user", expectedResponseCode,
+ deleteUser.getErrorCode().intValue());
+ }
+
+ // Admin Update user role from GOVERNOR to ADMIN
+ @Test
+ public void updateRoleFromGovernorToAdmin() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ak1000";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "ADMIN";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User adminUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 200, updateUserRoleResponse.getErrorCode().intValue());
+
+ RestResponse getUpdatedRoleUserResponse = UserRestUtils.getUser(adminUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(adminUser, getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role to non existing role - Response 400 Bad Request
+ @Test
+ public void updateRoleToNonExistingRole() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "al1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "VVVVVVV";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User newUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role from OPS to GOVERNOR
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 400, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Bad Request",
+ updateUserRoleResponse.getResponseMessage());
+
+ // RestResponse getUpdatedRoleUserResponse =
+ // UserRestUtils.getUser(adminUser,sdncAdminUser);
+ // UserValidationUtils.validateUserDetailsOnResponse(adminUser,getUpdatedRoleUserResponse.getResponse());
+ // Delete OPS user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ // Admin Update user role to null - Response 400 Bad Request
+ @Test
+ public void updateRoleToNull() throws Exception {
+ DbUtils.cleanAllAudits();
+
+ String httpCspUserId = "ax1001";
+ String userFirstName = "Benny";
+ String userLastName = "Tal";
+ String email = "optBenny@intl.sdc.com";
+ String role = "GOVERNOR";
+ String updatedRole = "";
+ User governorUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ User newUser = new User(userFirstName, userLastName, httpCspUserId, email, updatedRole, null);
+ // UserRestUtils.deleteUser(opsUser, sdncAdminUser, true);
+ // UserRestUtils.deleteUser(UserUpdateRole, sdncAdminUser);
+ RestResponse createUserResponse = UserRestUtils.createUser(governorUser, sdncAdminUser);
+ assertNotNull("check response object is not null after create user", createUserResponse);
+ assertNotNull("check error code exists in response after create user", createUserResponse.getErrorCode());
+ assertEquals("Check response code after create user", 201, createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(governorUser, createUserResponse.getResponse());
+ // opsUser.setRole(updatedRole);
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // update user role
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ governorUser.getUserId());
+ assertNotNull("check response object is not null after updating user", updateUserRoleResponse);
+ assertNotNull("check error code exists in response after updating user", updateUserRoleResponse.getErrorCode());
+ assertEquals("Check response code after updating user", 400, updateUserRoleResponse.getErrorCode().intValue());
+ assertEquals("Check response code after updating user", "Bad Request",
+ updateUserRoleResponse.getResponseMessage());
+ // Delete user
+ RestResponse deleteOpsUser = UserRestUtils.deleteUser(governorUser, sdncAdminUser, true);
+ assertNotNull("check response object is not null after deleting user", deleteOpsUser);
+ assertEquals("Check response code after deleting user", 200, deleteOpsUser.getErrorCode().intValue());
+
+ }
+
+ @Test
+ public void createProductManagerUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Man";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_MANAGER";
+ User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser, true);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse());
+ // Audit validation
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser,
+ Integer.toString(STATUS_CODE_SUCSESS_CREATED), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductStrategistUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodStr@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser,
+ createUserResponse.getResponse());
+ // Audit validation
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser,
+ Integer.toString(STATUS_CODE_SUCSESS_CREATED), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, getUserResponse.getResponse());
+ // Delete ProductStrategist user
+ RestResponse deleteProductStrategistUser = UserRestUtils.deleteUser(expectedProductStrategistUser,
+ sdncAdminUser, true);
+ assertNotNull("Check response object is not null after deleting OPS user", deleteProductStrategistUser);
+ assertEquals("Check response code after deleting OPS user", 200,
+ deleteProductStrategistUser.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductStrategistUserByNonAdminUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodStr@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncDesignerUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_RESTRICTED_OPERATION,
+ createUserResponse.getErrorCode().intValue());
+ // Audit validation
+ expectedProductStrategistUser.setUserId("");
+ expectedProductStrategistUser.setFirstName(null);
+ expectedProductStrategistUser.setLastName(null);
+ expectedProductStrategistUser.setEmail("");
+ expectedProductStrategistUser.setRole("");
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncDesignerUser,
+ Integer.toString(STATUS_CODE_RESTRICTED_OPERATION), errorInfo.getAuditDesc(""),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // Try to get user - user is not created
+ expectedProductStrategistUser.setUserId("pm1000");
+ expectedProductStrategistUser.setFirstName("Prod");
+ expectedProductStrategistUser.setLastName("Strategist");
+ expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com");
+ expectedProductStrategistUser.setRole("PRODUCT_STRATEGIST");
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductManagerUserByNonAdminUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Man";
+ String email = "prodStr@intl.sdc.com";
+ String role = "PRODUCT_MANAGER";
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser, true);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncDesignerUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_RESTRICTED_OPERATION,
+ createUserResponse.getErrorCode().intValue());
+ // Audit validation
+ expectedProductStrategistUser.setUserId("");
+ expectedProductStrategistUser.setFirstName(null);
+ expectedProductStrategistUser.setLastName(null);
+ expectedProductStrategistUser.setEmail("");
+ expectedProductStrategistUser.setRole("");
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncDesignerUser,
+ Integer.toString(STATUS_CODE_RESTRICTED_OPERATION), errorInfo.getAuditDesc(""),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // Try to get user - user is not created
+ expectedProductStrategistUser.setUserId("pm1000");
+ expectedProductStrategistUser.setFirstName("Prod");
+ expectedProductStrategistUser.setLastName("Strategist");
+ expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com");
+ expectedProductStrategistUser.setRole("PRODUCT_MANAGER");
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductStrategistUserByNonExistingUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodStr@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ noSdncUserDetails.setRole("blabla");
+ noSdncUserDetails.setUserId("bt750h");
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, noSdncUserDetails);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_NOT_FOUND,
+ createUserResponse.getErrorCode().intValue());
+ // Audit validation
+ expectedProductStrategistUser.setUserId("");
+ expectedProductStrategistUser.setFirstName(null);
+ expectedProductStrategistUser.setLastName(null);
+ expectedProductStrategistUser.setEmail("");
+ expectedProductStrategistUser.setRole("");
+ noSdncUserDetails.setFirstName("");
+ noSdncUserDetails.setLastName("");
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_NOT_FOUND.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, noSdncUserDetails,
+ Integer.toString(STATUS_CODE_NOT_FOUND), errorInfo.getAuditDesc(noSdncUserDetails.getUserId()),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // Try to get user - user is not created
+ expectedProductStrategistUser.setUserId("pm1000");
+ expectedProductStrategistUser.setFirstName("Prod");
+ expectedProductStrategistUser.setLastName("Strategist");
+ expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com");
+ expectedProductStrategistUser.setRole("PRODUCT_STRATEGIST");
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductManagerUserByNonExistingUser() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Man";
+ String email = "prodStr@intl.sdc.com";
+ String role = "PRODUCT_MANAGER";
+ User noSdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ noSdncUserDetails.setRole("blabla");
+ noSdncUserDetails.setUserId("bt750h");
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+
+ DbUtils.deleteFromEsDbByPattern("_all");
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, noSdncUserDetails);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_NOT_FOUND,
+ createUserResponse.getErrorCode().intValue());
+ // Audit validation
+ expectedProductStrategistUser.setUserId("");
+ expectedProductStrategistUser.setFirstName(null);
+ expectedProductStrategistUser.setLastName(null);
+ expectedProductStrategistUser.setEmail("");
+ expectedProductStrategistUser.setRole("");
+ noSdncUserDetails.setFirstName("");
+ noSdncUserDetails.setLastName("");
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_NOT_FOUND.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, noSdncUserDetails,
+ Integer.toString(STATUS_CODE_NOT_FOUND), errorInfo.getAuditDesc(noSdncUserDetails.getUserId()),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // Try to get user - user is not created
+ expectedProductStrategistUser.setUserId("pm1000");
+ expectedProductStrategistUser.setFirstName("Prod");
+ expectedProductStrategistUser.setLastName("Strategist");
+ expectedProductStrategistUser.setEmail("prodStr@intl.sdc.com");
+ expectedProductStrategistUser.setRole("PRODUCT_MANAGER");
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code ", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void updateProjectManagerRole() throws Exception {
+ // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Man";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_MANAGER";
+ String updatedRole = "GOVERNOR";
+ User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductManagerUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse());
+ // Update user role
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ expectedProductManagerUser.getUserId());
+ assertEquals("Check response code after create user", STATUS_CODE_SUCCESS,
+ updateUserRoleResponse.getErrorCode().intValue());
+ expectedProductManagerUser.setRole(updatedRole);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser,
+ updateUserRoleResponse.getResponse());
+ // Audit validation
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser,
+ Integer.toString(STATUS_CODE_SUCCESS), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("UpdateUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void updateProductStrategistRole() throws Exception {
+ // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ String updatedRole = "TESTER";
+ User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductManagerUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse());
+ // Update user role
+ User newRoleUser = new User();
+ newRoleUser.setRole(updatedRole);
+ // Update user role from PRODUCT_STRATEGIST to PRODUCT_MANAGER
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ expectedProductManagerUser.getUserId());
+ assertEquals("Check response code after create user", STATUS_CODE_SUCCESS,
+ updateUserRoleResponse.getErrorCode().intValue());
+ expectedProductManagerUser.setRole(updatedRole);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser,
+ updateUserRoleResponse.getResponse());
+ // Audit validation
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser,
+ Integer.toString(STATUS_CODE_SUCCESS), UserResponseMessageEnum.SUCCESS_MESSAGE.getValue(),
+ UserValidationUtils.getAddUserAuditMessage("UpdateUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductManagerUserAlreadyExit() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Man";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_MANAGER";
+ User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductManagerUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse());
+ // create same user again
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", USER_ALREADY_EXIST,
+ createUserAgainResponse.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_ALREADY_EXIST.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser,
+ Integer.toString(USER_ALREADY_EXIST), errorInfo.getAuditDesc(expectedProductManagerUser.getUserId()),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test
+ public void createProductStrategistUserAlreadyExit() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ User expectedProductManagerUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductManagerUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, createUserResponse.getResponse());
+ // create same user again
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse createUserAgainResponse = UserRestUtils.createUser(expectedProductManagerUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", USER_ALREADY_EXIST,
+ createUserAgainResponse.getErrorCode().intValue());
+ // Audit validation
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.USER_ALREADY_EXIST.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductManagerUser, sdncAdminUser,
+ Integer.toString(USER_ALREADY_EXIST), errorInfo.getAuditDesc(expectedProductManagerUser.getUserId()),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductManagerUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductManagerUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductManagerUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void UpdateProductStrategistToNonExistingRole() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodMan@intl.sdc.com";
+ String role = "PRODUCT_STRATEGIST";
+ String nonExistingRole = "BLABLA";
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductStrategistUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", STATUS_CODE_SUCSESS_CREATED,
+ createUserResponse.getErrorCode().intValue());
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser,
+ createUserResponse.getResponse());
+ // Update user Role to non Existing role
+ User newRoleUser = new User();
+ newRoleUser.setRole(nonExistingRole);
+ DbUtils.deleteFromEsDbByPattern("_all");
+ RestResponse updateUserRoleResponse = UserRestUtils.updateUserRole(newRoleUser, sdncAdminUser,
+ expectedProductStrategistUser.getUserId());
+ assertEquals("Check response code after updating user role", INVALID_ROLE,
+ updateUserRoleResponse.getErrorCode().intValue());
+
+ // Audit validation
+ /*
+ * expectedProductStrategistUser.setUserId("");
+ * expectedProductStrategistUser.setFirstName(null);
+ * expectedProductStrategistUser.setLastName(null);
+ * expectedProductStrategistUser.setEmail("");
+ * expectedProductStrategistUser.setRole("");
+ */
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_ROLE.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser,
+ Integer.toString(INVALID_ROLE), errorInfo.getAuditDesc(nonExistingRole),
+ UserValidationUtils.getAddUserAuditMessage("UpdateUser"));
+ // get user and compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ UserValidationUtils.validateUserDetailsOnResponse(expectedProductStrategistUser, getUserResponse.getResponse());
+ // Delete ProductManager user
+ RestResponse deleteProductManagerUser = UserRestUtils.deleteUser(expectedProductStrategistUser, sdncAdminUser,
+ true);
+ assertEquals("Check response code after deleting OPS user", STATUS_CODE_SUCCESS,
+ deleteProductManagerUser.getErrorCode().intValue());
+ }
+
+ @Test(enabled = false)
+ public void createUserWithNonExistingRole() throws Exception {
+ String httpCspUserId = "pm1000";
+ String userFirstName = "Prod";
+ String userLastName = "Strategist";
+ String email = "prodMan@intl.sdc.com";
+ String role = "BLABLA";
+ User expectedProductStrategistUser = new User(userFirstName, userLastName, httpCspUserId, email, role, null);
+ deleteUserAndAudit(expectedProductStrategistUser);
+ // create user
+ RestResponse createUserResponse = UserRestUtils.createUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check response code after create Product-Manager user", INVALID_ROLE,
+ createUserResponse.getErrorCode().intValue());
+
+ // Audit validation
+ /*
+ * expectedProductStrategistUser.setUserId("");
+ * expectedProductStrategistUser.setFirstName(null);
+ * expectedProductStrategistUser.setLastName(null);
+ * expectedProductStrategistUser.setEmail("");
+ * expectedProductStrategistUser.setRole("");
+ */
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_ROLE.name());
+ UserValidationUtils.validateAddUserAuditMessage(expectedProductStrategistUser, sdncAdminUser,
+ Integer.toString(INVALID_ROLE), errorInfo.getAuditDesc(role),
+ UserValidationUtils.getAddUserAuditMessage("AddUser"));
+ // get user - verify user is not createdand compare with expected
+ RestResponse getUserResponse = UserRestUtils.getUser(expectedProductStrategistUser, sdncAdminUser);
+ assertEquals("Check user not created", STATUS_CODE_NOT_FOUND, getUserResponse.getErrorCode().intValue());
+
+ }
+
+ private void deleteUserAndAudit(User sdncUserDetails) throws IOException {
+ UserRestUtils.deleteUser(sdncUserDetails, sdncAdminUser, true);
+ DbUtils.cleanAllAudits();
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java
new file mode 100644
index 0000000000..a7552ad3be
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/execute/user/GovernorWorkspaceApiTest.java
@@ -0,0 +1,354 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.execute.user;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ServiceValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GovernorWorkspaceApiTest extends ComponentBaseTest {
+
+ private static Logger logger = LoggerFactory.getLogger(GovernorWorkspaceApiTest.class.getName());
+ @Rule
+ public static TestName name = new TestName();
+
+ public GovernorWorkspaceApiTest() {
+ super(name, GovernorWorkspaceApiTest.class.getName());
+
+ }
+
+ protected final User admin1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected final User governor = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+ protected final User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected ResourceReqDetails resourceDetails1;
+ protected ComponentInstanceReqDetails componentInstanceReqDetails;
+ protected ArtifactReqDetails heatArtifactDetails;
+
+ protected final String serviceVersion = "0.1";
+ protected final String servicesString = "services";
+ protected final String userRemarks = "commentTest";
+
+ protected ServiceReqDetails serviceDetails11 = null;
+ protected ServiceReqDetails serviceDetails22 = null;
+ protected ServiceReqDetails serviceDetails33 = null;
+
+ @BeforeMethod
+ public void initBeforeTest() throws Exception {
+ DbUtils.deleteFromEsDbByPattern("_all");
+ Resource resourceObj = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetails1 = new ResourceReqDetails(resourceObj);
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ createThreeServices(sdncDesignerDetails1);
+ }
+
+ protected void createThreeServices(User user) throws Exception {
+
+ String checkinComment = "good checkin";
+ String checkinComentJson = "{\"userRemarks\": \"" + checkinComment + "\"}";
+
+ RestResponse addInformationalArtifactToResource = ArtifactRestUtils.addInformationalArtifactToResource(
+ heatArtifactDetails, sdncDesignerDetails1, resourceDetails1.getUniqueId());
+ RestResponse certifyResource = LifecycleRestUtils.certifyResource(resourceDetails1);
+ componentInstanceReqDetails = ElementFactory.getDefaultComponentInstance("defaultInstance", resourceDetails1);
+
+ serviceDetails11 = ElementFactory.getDefaultService();
+ serviceDetails22 = ElementFactory.getDefaultService();
+ serviceDetails33 = ElementFactory.getDefaultService();
+
+ serviceDetails11.setName(serviceDetails11.getName() + "1");
+ List<String> tags = serviceDetails11.getTags();
+ tags.add(serviceDetails11.getName());
+ serviceDetails11.setTags(tags);
+
+ serviceDetails22.setName(serviceDetails11.getName() + "2");
+ tags = serviceDetails22.getTags();
+ tags.add(serviceDetails22.getName());
+ serviceDetails22.setTags(tags);
+
+ serviceDetails33.setName(serviceDetails11.getName() + "3");
+ tags = serviceDetails33.getTags();
+ tags.add(serviceDetails33.getName());
+ serviceDetails33.setTags(tags);
+ //
+ // serviceUtils.deleteService_allVersions(serviceDetails11, designer1);
+ // serviceUtils.deleteService_allVersions(serviceDetails22, designer1);
+ // serviceUtils.deleteService_allVersions(serviceDetails33, designer1);
+
+ RestResponse createServiceResponse1 = createService(user, serviceDetails11);
+ RestResponse createServiceResponse2 = createService(user, serviceDetails22);
+ RestResponse createServiceResponse3 = createService(user, serviceDetails33);
+
+ // addResourceWithHeatArt();
+ //
+ // serviceUtils.addServiceMandatoryArtifacts(user,
+ // createServiceResponse1);
+ //
+ //
+ // RestResponse createServiceResponse2 =
+ // serviceUtils.createServiceTowardsCatalogBe(serviceDetails22, user);
+ // assertNotNull("check response object is not null after creating
+ // service", createServiceResponse2);
+ // assertNotNull("check if error code exists in response after creating
+ // service", createServiceResponse2.getErrorCode());
+ // assertEquals("Check response code after creating service", 201,
+ // createServiceResponse2.getErrorCode().intValue());
+ // serviceDetails22.setUniqueId(serviceUtils.getServiceUniqueId(createServiceResponse2));
+ // logger.debug("Created service2 = {}", serviceDetails22);
+ // serviceUtils.addServiceMandatoryArtifacts(user,
+ // createServiceResponse2);
+ //
+ // RestResponse createServiceResponse3 =
+ // serviceUtils.createServiceTowardsCatalogBe(serviceDetails33, user);
+ // assertNotNull("check response object is not null after creating
+ // service", createServiceResponse3);
+ // assertNotNull("check if error code exists in response after creating
+ // service", createServiceResponse3.getErrorCode());
+ // assertEquals("Check response code after creating service", 201,
+ // createServiceResponse3.getErrorCode().intValue());
+ // serviceDetails33.setUniqueId(serviceUtils.getServiceUniqueId(createServiceResponse3));
+ // logger.debug("Created service3 = {}", serviceDetails33);
+ // serviceUtils.addServiceMandatoryArtifacts(user,
+ // createServiceResponse3);
+
+ }
+
+ protected RestResponse createService(User user, ServiceReqDetails serviceDetails) throws Exception, IOException {
+ RestResponse createServiceResponse1 = ServiceRestUtils.createService(serviceDetails, user);
+ assertNotNull("check response object is not null after creating service", createServiceResponse1);
+ assertNotNull("check if error code exists in response after creating service",
+ createServiceResponse1.getErrorCode());
+ assertEquals("Check response code after creating service", 201,
+ createServiceResponse1.getErrorCode().intValue());
+ Service convertServiceResponseToJavaObject = ResponseParser
+ .convertServiceResponseToJavaObject(createServiceResponse1.getResponse());
+ serviceDetails.setUniqueId(convertServiceResponseToJavaObject.getUniqueId());
+ logger.debug("Created service1 = {}", serviceDetails);
+ addResourceWithHeatArt(serviceDetails);
+ return createServiceResponse1;
+ }
+
+ protected void addResourceWithHeatArt(ServiceReqDetails serviceDetails) throws Exception {
+
+ RestResponse createResourceInstance = ComponentInstanceRestUtils.createComponentInstance(
+ componentInstanceReqDetails, sdncDesignerDetails1, serviceDetails.getUniqueId(),
+ ComponentTypeEnum.SERVICE);
+ // System.out.println("serviceUID --->" + serviceDetails.getUniqueId());
+ assertEquals("Check response code ", 201, createResourceInstance.getErrorCode().intValue());
+ }
+
+ protected void certifyAllServices() throws Exception {
+ LifecycleRestUtils.certifyService(serviceDetails11);
+ LifecycleRestUtils.certifyService(serviceDetails22);
+ LifecycleRestUtils.certifyService(serviceDetails33);
+ }
+
+ protected boolean isElementInArray(String elementId, JSONArray jsonArray) throws Exception {
+ for (int i = 0; i < jsonArray.size(); i++) {
+ JSONObject jobject = (JSONObject) jsonArray.get(i);
+
+ if (jobject.get("uniqueId").toString().equals(elementId)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected void approveDistributionStatusOfCertifiedService(ServiceReqDetails serviceDetails, User user)
+ throws Exception {
+ approveDistributionStatusOfService(serviceDetails, user, "1.0");
+ }
+
+ protected void approveDistributionStatusOfService(ServiceReqDetails serviceDetails, User user, String version)
+ throws Exception {
+ RestResponse res = LifecycleRestUtils.sendApproveDistribution(user, serviceDetails.getUniqueId(), userRemarks);
+ assertEquals(200, res.getErrorCode().intValue());
+ ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ }
+
+ protected void rejectDistributionStatusOfService(ServiceReqDetails serviceDetails, User user) throws Exception {
+ rejectDistributionStatusOfService(serviceDetails, user, "1.0");
+ }
+
+ protected void rejectDistributionStatusOfService(ServiceReqDetails serviceDetails, User user, String version)
+ throws Exception {
+ RestResponse res = LifecycleRestUtils.rejectDistribution(serviceDetails, version, user, userRemarks);
+ assertEquals(200, res.getErrorCode().intValue());
+ ServiceValidationUtils.validateDistrubtionStatusValue(res, DistributionStatusEnum.DISTRIBUTION_REJECTED);
+ }
+
+ protected JSONArray getFollowedListAsJsonArray(User user) throws Exception {
+ RestResponse getGovernorFollowed = ServiceRestUtils.getFollowed(user);
+ assertNotNull(getGovernorFollowed);
+ assertNotNull(getGovernorFollowed.getErrorCode());
+ assertEquals(200, getGovernorFollowed.getErrorCode().intValue());
+
+ JSONArray listArrayFromRestResponse = ServiceRestUtils.getListArrayFromRestResponse(getGovernorFollowed);
+
+ return listArrayFromRestResponse;
+ }
+
+ protected void changeDistributionStatusOfAllService(boolean approved, User user) throws Exception {
+ if (approved) {
+ approveDistributionStatusOfCertifiedService(serviceDetails11, user);
+ approveDistributionStatusOfCertifiedService(serviceDetails22, user);
+ approveDistributionStatusOfCertifiedService(serviceDetails33, user);
+ } else {
+ rejectDistributionStatusOfService(serviceDetails11, user);
+ rejectDistributionStatusOfService(serviceDetails22, user);
+ rejectDistributionStatusOfService(serviceDetails33, user);
+ }
+
+ }
+
+ protected JSONArray checkFollowed(User user) throws Exception {
+ JSONArray getFollowedList = getFollowedListAsJsonArray(user);
+ assertFalse(getFollowedList.isEmpty());
+ assertTrue(isElementInArray(serviceDetails11.getUniqueId(), getFollowedList));
+ assertTrue(isElementInArray(serviceDetails22.getUniqueId(), getFollowedList));
+ assertTrue(isElementInArray(serviceDetails33.getUniqueId(), getFollowedList));
+
+ return getFollowedList;
+ }
+
+ // -------------------------------------T E S T
+ // S------------------------------------------------------//
+
+ @Test
+ public void governorList_AllCertifiedVersionsOfService() throws Exception {
+ certifyAllServices();
+ String serviceUniqueIdCertified1 = serviceDetails11.getUniqueId();
+ RestResponse res = LifecycleRestUtils.changeServiceState(serviceDetails11, sdncDesignerDetails1, "1.0",
+ LifeCycleStatesEnum.CHECKOUT);
+ assertEquals(200, res.getErrorCode().intValue());
+
+ JSONArray getFollowedList = getFollowedListAsJsonArray(governor);
+ assertFalse(getFollowedList.isEmpty());
+ assertFalse(isElementInArray(serviceDetails11.getUniqueId(), getFollowedList));
+ assertTrue(isElementInArray(serviceDetails22.getUniqueId(), getFollowedList));
+ assertTrue(isElementInArray(serviceDetails33.getUniqueId(), getFollowedList));
+ assertTrue(isElementInArray(serviceUniqueIdCertified1, getFollowedList));
+ assertEquals(3, getFollowedList.size());
+
+ // certifyService(serviceDetails11, "1.1");
+ LifecycleRestUtils.certifyService(serviceDetails11);
+
+ JSONArray governorFollowedList2 = checkFollowed(governor);
+ assertEquals(4, governorFollowedList2.size());
+ assertTrue(isElementInArray(serviceDetails11.getUniqueId(), governorFollowedList2));
+ assertTrue(isElementInArray(serviceUniqueIdCertified1, governorFollowedList2));
+
+ }
+
+ // -------------------------------------T E S T
+ // S------------------------------------------------------//
+
+ @Test
+ public void governorList_distributionNotApproved() throws Exception {
+ certifyAllServices();
+
+ JSONArray checkFollowed = checkFollowed(governor);
+ assertEquals(3, checkFollowed.size());
+ }
+
+ @Test
+ public void governorGetEmptyListTest_notCertifiedServices() throws Exception {
+ JSONArray governorFollowedList = getFollowedListAsJsonArray(governor);
+
+ assertTrue(governorFollowedList.isEmpty());
+ }
+
+ @Test
+ public void governorList_distributionApproved() throws Exception {
+ certifyAllServices();
+ boolean approved = true;
+ changeDistributionStatusOfAllService(approved, governor);
+
+ JSONArray checkFollowed = checkFollowed(governor);
+ assertEquals(3, checkFollowed.size());
+ }
+
+ @Test(enabled = false)
+ public void governorList_distributed() throws Exception {
+ certifyAllServices();
+
+ LifecycleRestUtils.changeDistributionStatus(serviceDetails11, "1.0", governor, userRemarks,
+ DistributionStatusEnum.DISTRIBUTED);
+ LifecycleRestUtils.changeDistributionStatus(serviceDetails22, "1.0", governor, userRemarks,
+ DistributionStatusEnum.DISTRIBUTED);
+ LifecycleRestUtils.changeDistributionStatus(serviceDetails33, "1.0", governor, userRemarks,
+ DistributionStatusEnum.DISTRIBUTED);
+
+ JSONArray governorFollowedList = getFollowedListAsJsonArray(governor);
+ assertFalse(governorFollowedList.isEmpty());
+ assertTrue(isElementInArray(serviceDetails11.getUniqueId(), governorFollowedList));
+ assertTrue(isElementInArray(serviceDetails22.getUniqueId(), governorFollowedList));
+ assertTrue(isElementInArray(serviceDetails33.getUniqueId(), governorFollowedList));
+ }
+
+ @Test
+ public void governorList_distributionRejected() throws Exception {
+ certifyAllServices();
+ boolean distributionRejected = false;
+ changeDistributionStatusOfAllService(distributionRejected, governor);
+
+ JSONArray checkFollowed = checkFollowed(governor);
+ assertEquals(3, checkFollowed.size());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java
new file mode 100644
index 0000000000..c80f6c612d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/executeOnUGN/distributionClient/ClientConfiguration.java
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.executeOnUGN.distributionClient;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ClientConfiguration {
+
+ private String asdcAddress;
+ private String user;
+ private String password;
+ private Integer pollingInterval;
+ private Integer pollingTimeout;
+ private List<String> relevantArtifactTypes;
+ private String consumerGroup;
+ private String environmentName;
+ private String consumerID;
+
+ public ClientConfiguration() {
+
+ super();
+
+ this.asdcAddress = "localhost:8443";
+ this.consumerID = "mso-123456";
+ this.consumerGroup = "mso-group";
+ this.environmentName = "PROD";
+ this.password = "password";
+ this.pollingInterval = 20;
+ this.pollingTimeout = 20;
+ this.relevantArtifactTypes = new ArrayList<String>();
+ this.relevantArtifactTypes.add("SHELL");
+ this.user = "mso-user";
+ }
+
+ public String getAsdcAddress() {
+ return asdcAddress;
+ }
+
+ public void setAsdcAddress(String asdcAddress) {
+ this.asdcAddress = asdcAddress;
+ }
+
+ public String getUser() {
+ return user;
+ }
+
+ public void setUser(String user) {
+ this.user = user;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+ public int getPollingInterval() {
+ return pollingInterval;
+ }
+
+ public void setPollingInterval(Integer pollingInterval) {
+ this.pollingInterval = pollingInterval;
+ }
+
+ public int getPollingTimeout() {
+ return pollingTimeout;
+ }
+
+ public void setPollingTimeout(Integer pollingTimeout) {
+ this.pollingTimeout = pollingTimeout;
+ }
+
+ public List<String> getRelevantArtifactTypes() {
+ return relevantArtifactTypes;
+ }
+
+ public void setRelevantArtifactTypes(List<String> relevantArtifactTypes) {
+ this.relevantArtifactTypes = relevantArtifactTypes;
+ }
+
+ public String getConsumerGroup() {
+ return consumerGroup;
+ }
+
+ public void setConsumerGroup(String consumerGroup) {
+ this.consumerGroup = consumerGroup;
+ }
+
+ public String getEnvironmentName() {
+ return environmentName;
+ }
+
+ public void setEnvironmentName(String environmentName) {
+ this.environmentName = environmentName;
+ }
+
+ public String getComsumerID() {
+ return consumerID;
+ }
+
+ public void setComsumerID(String comsumerID) {
+ this.consumerID = comsumerID;
+ }
+
+ public ClientConfiguration(String asdcAddress, String user, String password, Integer pollingInterval,
+ Integer pollingTimeout, List<String> relevantArtifactTypes, String consumerGroup, String environmentName,
+ String comsumerID) {
+ super();
+ this.asdcAddress = asdcAddress;
+ this.user = user;
+ this.password = password;
+ this.pollingInterval = pollingInterval;
+ this.pollingTimeout = pollingTimeout;
+ this.relevantArtifactTypes = relevantArtifactTypes;
+ this.consumerGroup = consumerGroup;
+ this.environmentName = environmentName;
+ this.consumerID = comsumerID;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java
new file mode 100644
index 0000000000..14c7a37101
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/ComplexResourceBaseTest.java
@@ -0,0 +1,177 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.preRequisites;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.annotations.BeforeMethod;
+
+public class ComplexResourceBaseTest extends ComponentBaseTest {
+
+ protected ServiceReqDetails serviceDetails;
+ protected ResourceReqDetails resourceDetailsVFC;
+ protected ResourceReqDetails resourceDetailsVL;
+ protected ResourceReqDetails resourceDetailsVF;
+ protected ResourceReqDetails resourceDetailsCP;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetailsVF;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetailsVFC;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetailsVL;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetailsCP;
+ protected User sdncDesignerDetails1;
+ protected User sdncTesterDeatails1;
+ protected User sdncAdminDetails1;
+ protected ArtifactReqDetails heatArtifactDetails;
+
+ protected ArtifactReqDetails defaultArtifactDetails;
+ protected int maxLength = 50;
+ protected Resource resourceVF = null;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public ComplexResourceBaseTest() {
+ super(name, ComplexResourceBaseTest.class.getName());
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+
+ initializeMembers();
+
+ createComponents();
+
+ }
+
+ public void initializeMembers() throws IOException, Exception {
+
+ serviceDetails = ElementFactory.getDefaultService();
+ resourceDetailsVFC = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC, "resourceVFC");
+ resourceDetailsVF = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, "resourceVF3");
+ resourceDetailsVL = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VL, "resourceVL");
+ resourceDetailsCP = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CP, "resourceCP");
+ sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncTesterDeatails1 = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ sdncAdminDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+
+ }
+
+ protected void createComponents() throws Exception {
+
+ RestResponse response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId());
+
+ response = ResourceRestUtils.createResource(resourceDetailsVFC, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetailsVFC.getUniqueId());
+ response = LifecycleRestUtils.changeResourceState(resourceDetailsVFC, sdncDesignerDetails1,
+ resourceDetailsVFC.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ response = ResourceRestUtils.createResource(resourceDetailsVF, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetailsVF.getUniqueId());
+
+ response = ResourceRestUtils.createResource(resourceDetailsCP, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetailsCP.getUniqueId());
+ response = LifecycleRestUtils.changeResourceState(resourceDetailsCP, sdncDesignerDetails1,
+ resourceDetailsCP.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ response = ResourceRestUtils.createResource(resourceDetailsVL, sdncDesignerDetails1);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+ assertNotNull("resource uniqueId is null:", resourceDetailsVL.getUniqueId());
+ response = LifecycleRestUtils.changeResourceState(resourceDetailsVL, sdncDesignerDetails1,
+ resourceDetailsVL.getVersion(), LifeCycleStatesEnum.CHECKIN);
+ assertTrue("change LS state to CHECKIN, returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ resourceInstanceReqDetailsVFC = ElementFactory.getDefaultComponentInstance("VFC", resourceDetailsVFC);
+ resourceInstanceReqDetailsVF = ElementFactory.getDefaultComponentInstance("VF", resourceDetailsVF);
+ resourceInstanceReqDetailsVL = ElementFactory.getDefaultComponentInstance("VL", resourceDetailsVL);
+ resourceInstanceReqDetailsCP = ElementFactory.getDefaultComponentInstance("CP", resourceDetailsCP);
+
+ }
+
+ protected void createVFWithCertifiedResourceInstance(ResourceReqDetails resourceDetails,
+ ComponentInstanceReqDetails resourceInstanceReqDetails) throws Exception {
+
+ RestResponse response = LifecycleRestUtils.changeResourceState(resourceDetails, sdncDesignerDetails1,
+ resourceDetails.getVersion(), LifeCycleStatesEnum.CHECKOUT);
+ assertEquals("Check response code after CHECKOUT", 200, response.getErrorCode().intValue());
+
+ // add heat artifact to resource and certify
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncDesignerDetails1,
+ resourceDetails.getUniqueId());
+ assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ response = LCSbaseTest.certifyResource(resourceDetails, sdncDesignerDetails1);
+ assertEquals("Check response code after CERTIFY request", 200, response.getErrorCode().intValue());
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+
+ resourceInstanceReqDetails.setComponentUid(resourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncDesignerDetails1,
+ resourceVF);
+ assertEquals("Check response code after create RI", 201, response.getErrorCode().intValue());
+
+ resourceVF = convertResourceGetResponseToJavaObject(resourceDetailsVF);
+ }
+
+ protected Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException {
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails, sdncDesignerDetails1);
+ assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue());
+ return ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java
new file mode 100644
index 0000000000..bde68528bf
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/DownloadArtifactBaseTest.java
@@ -0,0 +1,125 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.preRequisites;
+
+import java.io.IOException;
+
+import org.apache.log4j.lf5.util.ResourceUtils;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.execute.lifecycle.LCSbaseTest;
+import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.AssertJUnit;
+import org.testng.annotations.BeforeMethod;
+
+public class DownloadArtifactBaseTest extends ComponentBaseTest {
+
+ protected ResourceReqDetails downloadResourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected User sdncUserDetails;
+ protected User sdncDesignerDetails1;
+ protected ArtifactReqDetails heatArtifactDetails;
+
+ protected ArtifactReqDetails defaultArtifactDetails;
+ protected ResourceUtils resourceUtils;
+ protected ArtifactUtils artifactUtils;
+ protected Service service;
+
+ public DownloadArtifactBaseTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+
+ initializeMembers();
+ createComponents();
+
+ }
+
+ public void initializeMembers() throws IOException, Exception {
+ downloadResourceDetails = ElementFactory.getDefaultResource();
+ serviceDetails = ElementFactory.getDefaultService();
+ sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ heatArtifactDetails = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance();
+
+ }
+
+ protected void createComponents() throws Exception {
+
+ RestResponse response = ResourceRestUtils.createResource(downloadResourceDetails, sdncUserDetails);
+ AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 201);
+ AssertJUnit.assertNotNull("resource uniqueId is null:", downloadResourceDetails.getUniqueId());
+
+ ArtifactReqDetails heatArtifactDetails = ElementFactory
+ .getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ response = ArtifactRestUtils.addInformationalArtifactToResource(heatArtifactDetails, sdncUserDetails,
+ downloadResourceDetails.getUniqueId());
+ AssertJUnit.assertTrue("add HEAT artifact to resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ // certified resource
+ response = LCSbaseTest.certifyResource(downloadResourceDetails, sdncDesignerDetails1);
+ AssertJUnit.assertTrue("certify resource request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 200);
+
+ response = ServiceRestUtils.createService(serviceDetails, sdncUserDetails);
+ AssertJUnit.assertTrue("create request returned status:" + response.getErrorCode(),
+ response.getErrorCode() == 201);
+ AssertJUnit.assertNotNull("service uniqueId is null:", serviceDetails.getUniqueId());
+
+ // add resource instance with HEAT deployment artifact to the service
+ resourceInstanceReqDetails.setComponentUid(downloadResourceDetails.getUniqueId());
+ response = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, sdncUserDetails,
+ serviceDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ AssertJUnit.assertTrue("response code is not 201, returned: " + response.getErrorCode(),
+ response.getErrorCode() == 201);
+
+ response = ServiceRestUtils.getService(serviceDetails, sdncUserDetails);
+ AssertJUnit.assertTrue("response code is not 200, returned: " + response.getErrorCode(),
+ response.getErrorCode() == 200);
+ service = ResponseParser.convertServiceResponseToJavaObject(response.getResponse());
+
+ DbUtils.cleanAllAudits();
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java
new file mode 100644
index 0000000000..add06a587c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/preRequisites/SimpleOneRsrcOneServiceTest.java
@@ -0,0 +1,96 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.preRequisites;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+
+import org.apache.log4j.lf5.util.ResourceUtils;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.annotations.BeforeMethod;
+
+public abstract class SimpleOneRsrcOneServiceTest extends ComponentBaseTest {
+
+ protected ResourceReqDetails resourceDetails;
+ protected ServiceReqDetails serviceDetails;
+ protected ComponentInstanceReqDetails resourceInstanceReqDetails;
+ protected ArtifactReqDetails heatArtifactDetails1;
+
+ private static final String heatExtension = "yaml";
+ private static final String yangXmlExtension = "xml";
+ private static final String muranoPkgExtension = "zip";
+ private static final String extension = null;
+ private final String folderName = "heatEnv";
+
+ protected User sdncDesignerDetails;
+ protected ArtifactReqDetails defaultArtifactDetails;
+ protected ResourceUtils resourceUtils;
+ protected ArtifactUtils artifactUtils;
+ protected Utils utils;
+
+ private static RestResponse createServiceResponse;
+
+ public SimpleOneRsrcOneServiceTest(TestName testName, String className) {
+ super(testName, className);
+ }
+
+ @BeforeMethod
+ public void before() throws Exception {
+
+ initializeMembers();
+ createComponents();
+
+ }
+
+ public void initializeMembers() throws IOException, Exception {
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ resourceDetails = ElementFactory.getDefaultResource();
+ serviceDetails = ElementFactory.getDefaultService();
+ heatArtifactDetails1 = ElementFactory.getDefaultDeploymentArtifactForType(ArtifactTypeEnum.HEAT.getType());
+ resourceInstanceReqDetails = ElementFactory.getDefaultComponentInstance("resourceInstanceReqDetails");
+ }
+
+ protected void createComponents() throws Exception {
+
+ RestResponse response = ResourceRestUtils.createResource(resourceDetails, sdncDesignerDetails);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+
+ response = ServiceRestUtils.createService(serviceDetails, sdncDesignerDetails);
+ assertTrue("create request returned status:" + response.getErrorCode(), response.getErrorCode() == 201);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java
new file mode 100644
index 0000000000..aa6131c8ff
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/rules/MyTestWatcher.java
@@ -0,0 +1,82 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.rules;
+
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+import org.openecomp.sdc.ci.tests.api.SdcTest;
+
+public class MyTestWatcher extends TestWatcher {
+
+ SdcTest odlTest;
+
+ public MyTestWatcher(SdcTest odlTest) {
+ this.odlTest = odlTest;
+ }
+
+ /**
+ * Invoked when a test succeeds
+ *
+ * @param description
+ */
+ @Override
+ protected void succeeded(Description description) {
+ String testName = description.getMethodName();
+ odlTest.addTestSummary(testName, true);
+
+ }
+
+ /**
+ * Invoked when a test fails
+ *
+ * @param e
+ * @param description
+ */
+ @Override
+ protected void failed(Throwable e, Description description) {
+ String testName = description.getMethodName();
+ odlTest.addTestSummary(testName, false, e);
+ }
+
+ /**
+ * Invoked when a test is about to start
+ *
+ * @param description
+ */
+ @Override
+ protected void starting(Description description) {
+ // System.out.println("protected void starting(Description description)
+ // {");
+ this.odlTest.getLogger().debug("Start running test {}", description.getMethodName());
+ }
+
+ /**
+ * Invoked when a test method finishes (whether passing or failing)
+ *
+ * @param description
+ */
+ @Override
+ protected void finished(Description description) {
+ // System.out.println("protected void finished(Description description)
+ // {");
+ this.odlTest.getLogger().debug("Finish running test {}", description.getMethodName());
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java
new file mode 100644
index 0000000000..5119263032
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/ExtentReporterNG.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.run;
+
+import java.io.File;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import org.testng.IReporter;
+import org.testng.IResultMap;
+import org.testng.ISuite;
+import org.testng.ISuiteResult;
+import org.testng.ITestContext;
+import org.testng.ITestResult;
+import org.testng.xml.XmlSuite;
+
+import com.relevantcodes.extentreports.ExtentReports;
+import com.relevantcodes.extentreports.ExtentTest;
+import com.relevantcodes.extentreports.LogStatus;
+
+public class ExtentReporterNG implements IReporter {
+ private ExtentReports extent;
+
+ @Override
+ public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
+ extent = new ExtentReports(outputDirectory + File.separator + "ExtentReportsTestNG.html", true);
+
+ for (ISuite suite : suites) {
+ Map<String, ISuiteResult> result = suite.getResults();
+
+ for (ISuiteResult r : result.values()) {
+ ITestContext context = r.getTestContext();
+
+ buildTestNodes(context.getPassedTests(), LogStatus.PASS);
+ buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
+ buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
+ }
+ }
+
+ extent.flush();
+ extent.close();
+ }
+
+ private void buildTestNodes(IResultMap tests, LogStatus status) {
+ ExtentTest test;
+
+ if (tests.size() > 0) {
+ for (ITestResult result : tests.getAllResults()) {
+ test = extent.startTest(result.getMethod().getMethodName());
+
+ test.getTest().setStartedTime(getTime(result.getStartMillis()));
+ test.getTest().setEndedTime(getTime(result.getEndMillis()));
+
+ for (String group : result.getMethod().getGroups())
+ test.assignCategory(group);
+
+ String message = "Test " + status.toString().toLowerCase() + "ed";
+
+ if (result.getThrowable() != null)
+ message = result.getThrowable().getMessage();
+
+ test.log(status, message);
+
+ extent.endTest(test);
+ }
+ }
+ }
+
+ private Date getTime(long millis) {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTimeInMillis(millis);
+ return calendar.getTime();
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java
new file mode 100644
index 0000000000..3f895a3780
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest.java
@@ -0,0 +1,293 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.run;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.PropertyConfigurator;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.testng.TestNG;
+
+public class StartTest {
+
+ public static long timeOfTest = 0;
+
+ public static boolean debug = false;
+
+ public static AtomicBoolean loggerInitialized = new AtomicBoolean(false);
+
+ protected static Logger logger = null;
+
+ public static void main(String[] args) {
+
+ String debugEnabled = System.getProperty("debug");
+ if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) {
+ debug = true;
+ }
+ System.out.println("Debug mode is " + (debug ? "enabled" : "disabled"));
+
+ enableLogger();
+
+ Config config = null;
+ try {
+ config = Utils.getConfig();
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ if (config == null) {
+ logger.error("Failed to configuration file of ci tests.");
+ System.exit(1);
+ }
+
+ // need to update
+ // List<String> packagesToRun = config.getPackages();
+ // if (packagesToRun == null || true == packagesToRun.isEmpty()) {
+ // logger.error("No package was configured to be executed.");
+ // System.exit(2);
+ // }
+ // StartTest tests = new StartTest();
+
+ // stop on error logic
+ // boolean stopOnClassFailure = false;
+ // String stopOnClassFailureStr =
+ // System.getProperty("stopOnClassFailure");
+ // if (stopOnClassFailureStr != null &&
+ // stopOnClassFailureStr.equalsIgnoreCase("true")) {
+ // stopOnClassFailure = true;
+ // } else {
+ // Boolean stopOnClassFailureObj = config.isStopOnClassFailure();
+ // if (stopOnClassFailureObj != null) {
+ // stopOnClassFailure = stopOnClassFailureObj.booleanValue();
+ // }
+ // }
+ //
+
+ // tests.start(packagesToRun, stopOnClassFailure);
+
+ // TestListenerAdapter tla = new TestListenerAdapter();
+ //
+ // TestHTMLReporter report = new TestHTMLReporter();
+ //// report.
+
+ TestNG testng = new TestNG();
+
+ List<String> suites = new ArrayList<String>();
+ suites.add("testSuites/" + args[0]);
+ testng.setTestSuites(suites);
+ // testng.addListener(tla);
+ testng.setUseDefaultListeners(true);
+ testng.setOutputDirectory("target/");
+
+ StartTest tests = new StartTest();
+ // testng.setPreserveOrder(true);
+ // testng.setVerbose(2);
+ // testng.setSuiteThreadPoolSize(1);
+ // testng.setThreadCount(1);
+ testng.run();
+
+ }
+
+ public StartTest() {
+ logger = Logger.getLogger(StartTest.class.getName());
+ }
+
+ public static void enableLogger() {
+
+ if (false == loggerInitialized.get()) {
+
+ loggerInitialized.set(true);
+
+ String log4jPropsFile = System.getProperty("log4j.configuration");
+ if (System.getProperty("os.name").contains("Windows")) {
+ String logProps = "src/main/resources/ci/conf/log4j.properties";
+ if (log4jPropsFile == null) {
+ System.setProperty("targetlog", "target/");
+ log4jPropsFile = logProps;
+ }
+
+ }
+ PropertyConfigurator.configureAndWatch(log4jPropsFile);
+
+ }
+ }
+
+ // logger.debug("Going to run test class {}", testClass.getName());
+ // logger.debug("Test class {} finished {}", testClass.getName(), (result.wasSuccessful() ? "OK." : " WITH ERROR."));
+ // logger.debug("class {} failed tests: {}", testClass.getName(), (failuresPerClass * 1.0) / runsPerClass * 100 + " %");
+ // logger.debug("class {} ignored tests: {}", testClass.getName(), (ignoredPerClass * 1.0) / runsPerClass * 100 + " %");
+ private List<Class> getClassesForPackage(String pkgname) {
+
+ List<Class> classes = new ArrayList<Class>();
+
+ // Get a File object for the package
+ File directory = null;
+ String fullPath;
+ String relPath = pkgname.replace('.', '/');
+
+ // System.out.println("ClassDiscovery: Package: " + pkgname +
+ // " becomes Path:" + relPath);
+
+ URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
+
+ // System.out.println("ClassDiscovery: Resource = " + resource);
+ if (resource == null) {
+ throw new RuntimeException("No resource for " + relPath);
+ }
+ fullPath = resource.getFile();
+ // System.out.println("ClassDiscovery: FullPath = " + resource);
+
+ if (debug) {
+ System.out.println("fullPath is " + fullPath);
+ }
+
+ try {
+ directory = new File(resource.toURI());
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(
+ pkgname + " (" + resource
+ + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...",
+ e);
+ } catch (IllegalArgumentException e) {
+ directory = null;
+ }
+ // System.out.println("ClassDiscovery: Directory = " + directory);
+
+ if (directory != null && directory.exists()) {
+
+ // Get the list of the files contained in the package
+ String[] files = directory.list();
+ for (int i = 0; i < files.length; i++) {
+
+ // we are only interested in .class files
+ if (files[i].endsWith(".class") && false == files[i].contains("$")) {
+
+ // removes the .class extension
+ String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
+
+ // System.out.println("ClassDiscovery: className = " +
+ // className);
+
+ if (debug) {
+ System.out.println("ClassDiscovery: className = " + className);
+ }
+
+ try {
+ Class clas = Class.forName(className);
+ boolean isAddToRun = false;
+ Method[] methods = clas.getMethods();
+ for (Method method : methods) {
+ Annotation[] anns = method.getAnnotations();
+ for (Annotation an : anns) {
+ if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
+ isAddToRun = true;
+ break;
+ }
+ }
+ }
+ if (isAddToRun)
+ classes.add(clas);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("ClassNotFoundException loading " + className);
+ }
+ }
+ }
+ } else {
+ try {
+ String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
+
+ if (debug) {
+ System.out.println("jarPath is " + jarPath);
+ }
+
+ JarFile jarFile = new JarFile(jarPath);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ JarEntry entry = entries.nextElement();
+ String entryName = entry.getName();
+ if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
+
+ // System.out.println("ClassDiscovery: JarEntry: " +
+ // entryName);
+ String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
+
+ // System.out.println("ClassDiscovery: className = " +
+ // className);
+
+ if (false == className.contains("$")) {
+
+ if (debug) {
+ System.out.println("ClassDiscovery: className = " + className);
+ }
+
+ try {
+ Class clas = Class.forName(className);
+ boolean isAddToRun = false;
+ Method[] methods = clas.getMethods();
+ for (Method method : methods) {
+ Annotation[] anns = method.getAnnotations();
+ for (Annotation an : anns) {
+ if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
+ isAddToRun = true;
+ break;
+ }
+ }
+ }
+ if (isAddToRun)
+ classes.add(clas);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("ClassNotFoundException loading " + className);
+ }
+ }
+ }
+ }
+ jarFile.close();
+
+ } catch (IOException e) {
+ throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
+ }
+ }
+ return classes;
+ }
+
+ private void addTableHead(StringBuilder results) {
+ results.append("<tr>");
+ results.append("<th>").append("Unit Test").append("</th>");
+ results.append("<th>").append("Result").append("</th>");
+ results.append("</tr>");
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java
new file mode 100644
index 0000000000..bab5afaa08
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/run/StartTest2backup.java
@@ -0,0 +1,410 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.run;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+import org.apache.log4j.PropertyConfigurator;
+import org.junit.runner.JUnitCore;
+import org.junit.runner.Result;
+import org.junit.runner.notification.Failure;
+import org.openecomp.sdc.ci.tests.api.SdcTest;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StartTest2backup {
+
+ private List<Class<? extends SdcTest>> testClasses = new ArrayList<Class<? extends SdcTest>>();
+ public static long timeOfTest = 0;
+
+ public static boolean debug = false;
+
+ public static AtomicBoolean loggerInitialized = new AtomicBoolean(false);
+
+ protected static Logger logger = null;
+
+ public static void main(String[] args) {
+
+ String debugEnabled = System.getProperty("debug");
+ if (debugEnabled != null && debugEnabled.equalsIgnoreCase("true")) {
+ debug = true;
+ }
+ System.out.println("Debug mode is " + (debug ? "enabled" : "disabled"));
+
+ enableLogger();
+
+ Config config = null;
+ try {
+ config = Utils.getConfig();
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ if (config == null) {
+ logger.error("Failed to configuration file of ci tests.");
+ System.exit(1);
+ }
+
+ List<String> packagesToRun = config.getPackages();
+ if (packagesToRun == null || true == packagesToRun.isEmpty()) {
+ logger.error("No package was configured to be executed.");
+ System.exit(2);
+ }
+ StartTest2backup tests = new StartTest2backup();
+
+ boolean stopOnClassFailure = false;
+ String stopOnClassFailureStr = System.getProperty("stopOnClassFailure");
+ if (stopOnClassFailureStr != null && stopOnClassFailureStr.equalsIgnoreCase("true")) {
+ stopOnClassFailure = true;
+ } else {
+ Boolean stopOnClassFailureObj = config.isStopOnClassFailure();
+ if (stopOnClassFailureObj != null) {
+ stopOnClassFailure = stopOnClassFailureObj.booleanValue();
+ }
+ }
+
+ tests.start(packagesToRun, stopOnClassFailure);
+ }
+
+ public StartTest2backup() {
+ logger = LoggerFactory.getLogger(StartTest2backup.class.getName());
+ }
+
+ public static void enableLogger() {
+
+ if (false == loggerInitialized.get()) {
+
+ loggerInitialized.set(true);
+
+ String log4jPropsFile = System.getProperty("log4j.configuration");
+ if (System.getProperty("os.name").contains("Windows")) {
+ String logProps = "src/main/resources/ci/conf/log4j.properties";
+ if (log4jPropsFile == null) {
+ System.setProperty("targetlog", "target/");
+ log4jPropsFile = logProps;
+ }
+
+ }
+ PropertyConfigurator.configureAndWatch(log4jPropsFile);
+
+ }
+ }
+
+ public void start(List<String> packages, boolean exitOnFailure) {
+
+ boolean success = true;
+ StringBuilder results = new StringBuilder();
+ Result result;
+
+ if (packages == null) {
+ return;
+ }
+
+ for (String packageName : packages) {
+ // List<Class> classesForPackage =
+ // getClassesForPackage("org.openecomp.sdc.ci.tests.execute");
+ List<Class> classesForPackage = getClassesForPackage(packageName);
+ if (classesForPackage != null && false == classesForPackage.isEmpty()) {
+ for (Class testUnit : classesForPackage) {
+ testClasses.add(testUnit);
+ }
+ }
+ }
+
+ System.out.println(testClasses);
+
+ // tsetClasses.add(LogValidatorTest.class);
+ // tsetClasses.add(AttNorthboundTest.class);
+
+ results.append(
+ "<Html><head><style>th{background-color: gray;color: white;height: 30px;}td {color: black;height: 30px;}.fail {background-color: #FF5555;width: 100px;text-align: center;}.success {background-color: #00FF00;width: 100px;text-align: center;}.name {width: 200px;background-color: #F0F0F0;}.message {width: 300px;background-color: #F0F0F0;}</style></head><body>");
+
+ Calendar calendar = Calendar.getInstance();
+ timeOfTest = calendar.getTimeInMillis();
+ SimpleDateFormat date_format = new SimpleDateFormat("MMM dd yyyy HH:mm:ss");
+ results.append("<br/><h2> This report generated on " + date_format.format(calendar.getTime()) + "</h2><br/>");
+
+ results.append("<table>");
+ addTableHead(results);
+
+ int size = testClasses.size();
+ int index = 0;
+
+ int totalRunTests = 0;
+ int totalFailureTests = 0;
+ int totalIgnoreTests = 0;
+ int numOfFailureClasses = 0;
+ for (Class<? extends SdcTest> testClass : testClasses) {
+
+ index++;
+
+ StringBuilder builder = new StringBuilder();
+ String str = "***************************************************************************";
+ builder.append(str + "\n");
+ String current = "class " + index + "/" + size + " failure(" + numOfFailureClasses + ") + RUNS("
+ + totalRunTests + ")" + " FAILURES(" + totalFailureTests + ") IGNORED(" + totalIgnoreTests + ")";
+ int interval = ((str.length() - current.length() - 2) / 2);
+ String substring = str.substring(0, interval);
+ builder.append(substring + " " + current + " " + substring + "\n");
+ builder.append(str + "\n");
+
+ System.out.println(builder.toString());
+
+ logger.debug(builder.toString());
+ logger.debug("Going to run test class {}", testClass.getName());
+
+ result = JUnitCore.runClasses(testClass);
+ if (result.wasSuccessful() == false) {
+ numOfFailureClasses++;
+ }
+ logger.debug("Test class {} finished {}", testClass.getName(), (result.wasSuccessful() ? "OK." : " WITH ERROR."));
+ List<Failure> failures = result.getFailures();
+ if (failures != null) {
+ for (Failure failure : failures) {
+ logger.error("Test class " + testClass.getName() + " failure test " + failure.getTestHeader() + "-"
+ + failure.getTrace());
+ }
+ }
+ int runsPerClass = result.getRunCount();
+ int failuresPerClass = result.getFailureCount();
+ int ignoredPerClass = result.getIgnoreCount();
+
+ totalRunTests += runsPerClass;
+ totalFailureTests += failuresPerClass;
+ totalIgnoreTests += ignoredPerClass;
+
+ logger.debug("class {} failed tests: {}", testClass.getName(), (failuresPerClass * 1.0) / runsPerClass * 100 + " %");
+ logger.debug("class {} ignored tests: {}", testClass.getName(), (ignoredPerClass * 1.0) / runsPerClass * 100 + " %");
+
+ // List<Failure> failures = result.getFailures();
+ // if (failures != null) {
+ // for (Failure failure : failures) {
+ // System.err.println("9999999999" + failure.getTestHeader());
+ // }
+ // }
+
+ addUnitTestResult(results, testClass, result);
+ success &= result.wasSuccessful();
+
+ if (numOfFailureClasses > 0) {
+ // if (exitOnFailure) {
+ if (exitOnFailure) {
+ break;
+ }
+ }
+ }
+
+ results.append("</table>");
+ results.append("<br/><h2> Tests Summary: </h2><br/>");
+ results.append("Total Runs : " + totalRunTests + "<br/>");
+ results.append("Total Failure : " + totalFailureTests + "<br/>");
+ results.append("Total: " + totalFailureTests + "/" + totalRunTests + "<br/>");
+ results.append("</html>");
+
+ FileUtils.writeToFile(Config.instance().getOutputFolder() + File.separator + Config.instance().getReportName(),
+ results.toString());
+
+ if (!success) {
+ System.out.println("FAILURE");
+ logger.error("Failure tests : "
+ + ((totalFailureTests + totalIgnoreTests) * 1.0) / (totalRunTests + totalIgnoreTests) + " %");
+ logger.error("Ignored tests : " + (totalIgnoreTests * 1.0) / (totalRunTests + totalIgnoreTests) + " %");
+ System.exit(1);
+ }
+
+ System.out.println("SUCCESS");
+ }
+
+ private List<Class> getClassesForPackage(String pkgname) {
+
+ List<Class> classes = new ArrayList<Class>();
+
+ // Get a File object for the package
+ File directory = null;
+ String fullPath;
+ String relPath = pkgname.replace('.', '/');
+
+ // System.out.println("ClassDiscovery: Package: " + pkgname +
+ // " becomes Path:" + relPath);
+
+ URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
+
+ // System.out.println("ClassDiscovery: Resource = " + resource);
+ if (resource == null) {
+ throw new RuntimeException("No resource for " + relPath);
+ }
+ fullPath = resource.getFile();
+ // System.out.println("ClassDiscovery: FullPath = " + resource);
+
+ if (debug) {
+ System.out.println("fullPath is " + fullPath);
+ }
+
+ try {
+ directory = new File(resource.toURI());
+ } catch (URISyntaxException e) {
+ throw new RuntimeException(
+ pkgname + " (" + resource
+ + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...",
+ e);
+ } catch (IllegalArgumentException e) {
+ directory = null;
+ }
+ // System.out.println("ClassDiscovery: Directory = " + directory);
+
+ if (directory != null && directory.exists()) {
+
+ // Get the list of the files contained in the package
+ String[] files = directory.list();
+ for (int i = 0; i < files.length; i++) {
+
+ // we are only interested in .class files
+ if (files[i].endsWith(".class") && false == files[i].contains("$")) {
+
+ // removes the .class extension
+ String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
+
+ // System.out.println("ClassDiscovery: className = " +
+ // className);
+
+ if (debug) {
+ System.out.println("ClassDiscovery: className = " + className);
+ }
+
+ try {
+ Class clas = Class.forName(className);
+ boolean isAddToRun = false;
+ Method[] methods = clas.getMethods();
+ for (Method method : methods) {
+ Annotation[] anns = method.getAnnotations();
+ for (Annotation an : anns) {
+ if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
+ isAddToRun = true;
+ break;
+ }
+ }
+ }
+ if (isAddToRun)
+ classes.add(clas);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("ClassNotFoundException loading " + className);
+ }
+ }
+ }
+ } else {
+ try {
+ String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
+
+ if (debug) {
+ System.out.println("jarPath is " + jarPath);
+ }
+
+ JarFile jarFile = new JarFile(jarPath);
+ Enumeration<JarEntry> entries = jarFile.entries();
+ while (entries.hasMoreElements()) {
+ JarEntry entry = entries.nextElement();
+ String entryName = entry.getName();
+ if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) {
+
+ // System.out.println("ClassDiscovery: JarEntry: " +
+ // entryName);
+ String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
+
+ // System.out.println("ClassDiscovery: className = " +
+ // className);
+
+ if (false == className.contains("$")) {
+
+ if (debug) {
+ System.out.println("ClassDiscovery: className = " + className);
+ }
+
+ try {
+ Class clas = Class.forName(className);
+ boolean isAddToRun = false;
+ Method[] methods = clas.getMethods();
+ for (Method method : methods) {
+ Annotation[] anns = method.getAnnotations();
+ for (Annotation an : anns) {
+ if (an.annotationType().getSimpleName().equalsIgnoreCase("Test")) {
+ isAddToRun = true;
+ break;
+ }
+ }
+ }
+ if (isAddToRun)
+ classes.add(clas);
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException("ClassNotFoundException loading " + className);
+ }
+ }
+ }
+ }
+ jarFile.close();
+
+ } catch (IOException e) {
+ throw new RuntimeException(pkgname + " (" + directory + ") does not appear to be a valid package", e);
+ }
+ }
+ return classes;
+ }
+
+ private void addTableHead(StringBuilder results) {
+ results.append("<tr>");
+ results.append("<th>").append("Unit Test").append("</th>");
+ results.append("<th>").append("Result").append("</th>");
+ results.append("</tr>");
+ }
+
+ private void addUnitTestResult(StringBuilder results, Class<? extends SdcTest> testClass,
+ Result unitTestResult) {
+
+ boolean isSuccess = unitTestResult.wasSuccessful();
+
+ String result = (isSuccess) ? "success" : "fail";
+ String fileName = FileUtils.getFileName(testClass.getName());
+ results.append("<tr>");
+ // results.append("<td>").append(FileUtils.getFileName(testClass.getName())).append("</td>");
+ results.append("<td class=\"name\">")
+ .append("<a href=\"" + fileName + timeOfTest + ".html\">" + fileName + "</a>").append("</td>");
+ results.append("<td class=\"" + result + "\">").append(result).append("</td>");
+ results.append("</tr>");
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java
new file mode 100644
index 0000000000..00ff48e887
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/CrudE2E.java
@@ -0,0 +1,220 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.sanity;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import fj.data.Either;
+
+public class CrudE2E extends ComponentBaseTest {
+ private static Logger log = LoggerFactory.getLogger(CrudE2E.class.getName());
+
+ public Component resourceDetailsVFCcomp_01;
+ public Component resourceDetailsVFCsoft_01;
+ public Component resourceDetailsCP_01;
+ public Component resourceDetailsVL_01;
+ public Component resourceDetailsVF_01;
+ public Component resourceDetailsVF_02;
+
+ public ComponentInstance resourceDetailsVFC1compIns1;
+ public ComponentInstance resourceDetailsVFC1softIns1;
+ public ComponentInstance resourceDetailsCP1ins_01;
+ public ComponentInstance resourceDetailsVL1ins_01;
+ public ComponentInstance resourceDetailsVF1ins_01;
+ public Component defaultService1;
+ private List<String> variablesAsList = new ArrayList<String>();
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public CrudE2E() {
+ super(name, CrudE2E.class.getName());
+ }
+
+ @Test
+ public void complexScenario() throws Exception {
+
+ User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+
+ //////// create defaultService1 ///////////////////////
+ Either<Service, RestResponse> createDefaultService1e = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true);
+ defaultService1 = createDefaultService1e.left().value();
+
+ //////// create VFC1 (resourceDetailsVFCcomp_01) DerivedFrom COMPUTE
+ //////// type add all possible informational artifacts and change state
+ //////// to CERTIFY////////
+ Either<Resource, RestResponse> resourceDetailsVFCcompE = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.COMPUTE,ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVFCcomp_01 = resourceDetailsVFCcompE.left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.CHEF, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.PUPPET, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.DG_XML, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MURANO_PKG, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVFCcomp_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCcomp_01, UserRoleEnum.DESIGNER,LifeCycleStatesEnum.CERTIFY, true);
+
+ //////// create VFC2 (resourceDetailsVFCsoft_01) DerivedFrom SOFTWARE
+ //////// type and change state to CERTIFY////////
+ Either<Resource, RestResponse> resourceDetailsVFCsoftE = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.SOFTWARE_COMPONENT,ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVFCsoft_01 = resourceDetailsVFCsoftE.left().value();
+ AtomicOperationUtils.changeComponentState(resourceDetailsVFCsoft_01, UserRoleEnum.DESIGNER,LifeCycleStatesEnum.CERTIFY, true);
+
+ //////// create CP1 (resourceDetailsVFCsoft_01) DerivedFrom PORT type
+ //////// and change state to CHECKIN////////
+ Either<Resource, RestResponse> resourceDetailsCP_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT,ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsCP_01 = resourceDetailsCP_01e.left().value();
+ AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER,LifeCycleStatesEnum.CHECKIN, true);
+
+ //////// create VL1 (resourceDetailsVFCsoft_01) DerivedFrom NETWORK type
+ //////// and change state to CERTIFY////////
+ Either<Resource, RestResponse> resourceDetailsVL_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK,ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVL_01 = resourceDetailsVL_01e.left().value();
+ AtomicOperationUtils.changeComponentState(resourceDetailsVL_01, UserRoleEnum.DESIGNER,LifeCycleStatesEnum.CERTIFY, true);
+
+ //////// create VF1 (resourceDetailsVFCcomp_01) DerivedFrom COMPUTE type
+ //////// add all possible deployment and informational artifacts
+ //////// //////////
+ Either<Resource, RestResponse> resourceDetailsVF_01e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF_01 = resourceDetailsVF_01e.left().value();
+ ArtifactDefinition heatArtifact = AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_VOL, resourceDetailsVF_01,UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.HEAT_NET, resourceDetailsVF_01,UserRoleEnum.DESIGNER, true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVF_01, UserRoleEnum.DESIGNER,true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.CHEF, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.PUPPET, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.YANG_XML, resourceDetailsVF_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.DG_XML, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MURANO_PKG, resourceDetailsVF_01,UserRoleEnum.DESIGNER, false, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.OTHER, resourceDetailsVF_01, UserRoleEnum.DESIGNER,false, true);
+
+ //////// Add VFC1 VFC2 CP and VL to VF container /////////////
+ resourceDetailsVFC1compIns1 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCcomp_01, resourceDetailsVF_01,UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetailsVFC1softIns1 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVFCsoft_01, resourceDetailsVF_01,UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetailsCP1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsCP_01,resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value();
+ resourceDetailsVL1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVL_01,resourceDetailsVF_01, UserRoleEnum.DESIGNER, true).left().value();
+
+ //////// associate cp-vl vl-vfcComp and vfcComp-vfcSoft////////
+ resourceDetailsVF_01 = AtomicOperationUtils.getResourceObject(resourceDetailsVF_01, UserRoleEnum.DESIGNER);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01,resourceDetailsVL1ins_01, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01,resourceDetailsVFC1compIns1, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsVFC1compIns1,resourceDetailsVFC1softIns1, AssocType.NODE.getAssocType(), UserRoleEnum.DESIGNER, true);
+
+ //////// download all VF1 artifacts////////
+ Collection<ArtifactDefinition> artifacts = resourceDetailsVF_01.getDeploymentArtifacts().values();
+ List<String> collect = artifacts.stream().filter(p -> p.checkEsIdExist() == true).map(p -> p.getUniqueId()).collect(Collectors.toList());
+ artifacts.stream().filter(p -> p.checkEsIdExist() == true).map(p -> p.getUniqueId()).forEach(item -> log.debug(item));
+
+ //////// get all VF1 artifacts////////
+
+ Collection<List<ComponentInstanceProperty>> componentInstancesProperties = resourceDetailsVF_01.getComponentInstancesProperties().values();
+ List<String> collect2 = componentInstancesProperties.stream().filter(p -> p.isEmpty() == false).flatMap(l -> l.stream()).collect(Collectors.toList()).stream().map(p -> p.getUniqueId()).collect(Collectors.toList());
+
+ //////// certify VF1 - failed due to uncertified CP instance ////////
+ RestResponse changeVfStateFailed = LifecycleRestUtils.changeComponentState(resourceDetailsVF_01, designer,LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ Resource resResourceDetailsVF_01 = (Resource) resourceDetailsVF_01;
+ variablesAsList = Arrays.asList(resResourceDetailsVF_01.getResourceType().toString(),resourceDetailsCP_01.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name(), variablesAsList,changeVfStateFailed.getResponse());
+
+ //////// certify resources CP1 ////////
+ resourceDetailsCP_01 = AtomicOperationUtils.changeComponentState(resourceDetailsCP_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //////// replace VF1 instances with new certified instances (CP1
+ //////// replaced) ////////
+ Either<Pair<Component, ComponentInstance>, RestResponse> changeComponentInstanceVersion = AtomicOperationUtils.changeComponentInstanceVersion(resourceDetailsVF_01, resourceDetailsCP1ins_01, resourceDetailsCP_01,UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF_01 = changeComponentInstanceVersion.left().value().getLeft();
+ resourceDetailsCP1ins_01 = changeComponentInstanceVersion.left().value().getRight();
+
+ //////// associate cp-vl and cp-vfc1,////////
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01,resourceDetailsVL1ins_01, AssocType.LINKABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.associate2ResourceInstances(resourceDetailsVF_01, resourceDetailsCP1ins_01,resourceDetailsVFC1compIns1, AssocType.BINDABLE.getAssocType(), UserRoleEnum.DESIGNER, true);
+
+ /////// change VF1 state to CHECK-IN and add it as instance to service1
+ /////// container
+ resourceDetailsVF_01 = AtomicOperationUtils.changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resourceDetailsVF1ins_01 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceDetailsVF_01,defaultService1, UserRoleEnum.DESIGNER, true).left().value();
+
+ //////// distribute service1 - failed due to incorrect LifeCyclestatus
+ //////// ////////
+ RestResponse distributeService = AtomicOperationUtils.distributeService(defaultService1, false);
+ Assert.assertEquals(distributeService, null, "verification failed");
+
+ //////// certify service1 - failed due to uncertified instances ////////
+ designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ RestResponse changeServicetStateFailed = LifecycleRestUtils.changeComponentState(defaultService1, designer,LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ variablesAsList = Arrays.asList(defaultService1.getComponentType().toString().toLowerCase(),resourceDetailsVF_01.getName());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name(), variablesAsList,changeServicetStateFailed.getResponse());
+
+ ////// change VF1 state to CERTIFIED
+ resourceDetailsVF_01 = AtomicOperationUtils.changeComponentState(resourceDetailsVF_01, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //////// replace VF1 instances with new certified instances ////////
+ changeComponentInstanceVersion = AtomicOperationUtils.changeComponentInstanceVersion(defaultService1,resourceDetailsVF1ins_01, resourceDetailsVF_01, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF_01 = changeComponentInstanceVersion.left().value().getLeft();
+ resourceDetailsVFC1compIns1 = changeComponentInstanceVersion.left().value().getRight();
+
+ /////// certify service1 ////////
+ defaultService1 = AtomicOperationUtils.changeComponentState(defaultService1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ //////// distribute service1 - successfully ////////
+ AtomicOperationUtils.distributeService(defaultService1, true);
+
+ /////// create VF2 ////////
+ Either<Resource, RestResponse> resourceDetailsVF_02e = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT,ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, UserRoleEnum.DESIGNER, true);
+ resourceDetailsVF_02 = resourceDetailsVF_02e.left().value();
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
new file mode 100644
index 0000000000..8b8a793bc6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/sanity/MultipleResourceUpdate.java
@@ -0,0 +1,126 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.sanity;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AssocType;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.testng.annotations.Test;
+
+public class MultipleResourceUpdate extends ComponentBaseTest {
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public MultipleResourceUpdate() {
+ super(name, MultipleResourceUpdate.class.getName());
+ }
+
+ @Test
+ public void simpleScenario() throws Exception {
+
+ // Creating VF and Resource instances
+ Resource vf = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource cp1 = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.PORT,
+ ResourceCategoryEnum.NETWORK_CONNECTIVITY_CON_POINT, UserRoleEnum.DESIGNER, true).left().value();
+ Resource cp2 = AtomicOperationUtils.createResourceByType(ResourceTypeEnum.CP, UserRoleEnum.DESIGNER, true).left().value();
+ Resource vl = AtomicOperationUtils
+ .createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VL, NormativeTypesEnum.NETWORK,
+ ResourceCategoryEnum.NETWORK_CONNECTIVITY_VIRTUAL_LINK, UserRoleEnum.DESIGNER, true).left().value();
+
+ vf.getCreatorUserId();
+
+ // Check In Resources
+ AtomicOperationUtils.changeComponentState(cp1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ AtomicOperationUtils.changeComponentState(cp2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+ AtomicOperationUtils.changeComponentState(vl, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true);
+
+ // CheckIn all other except VF
+ ComponentInstance instanceCP1 = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp1, vf, UserRoleEnum.DESIGNER, true).left().value();
+ ComponentInstance instanceVL = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(vl, vf, UserRoleEnum.DESIGNER, true).left().value();
+ ComponentInstance instanceCP2 = AtomicOperationUtils
+ .addComponentInstanceToComponentContainer(cp2, vf, UserRoleEnum.DESIGNER, true).left().value();
+
+ vf = (Resource) AtomicOperationUtils.getCompoenntObject(vf, UserRoleEnum.DESIGNER);
+
+ // Create Vertex(Link/Associate 2 Resource Instances on Canvas)
+ AtomicOperationUtils.associate2ResourceInstances(vf, instanceCP1, instanceVL, AssocType.LINKABLE.getAssocType(),
+ UserRoleEnum.DESIGNER, true);
+
+ List<ComponentInstanceReqDetails> componentInstanceReqDetailsList = new ArrayList<>();
+ componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceCP1));
+ componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceCP2));
+ componentInstanceReqDetailsList.add(new ComponentInstanceReqDetails(instanceVL));
+
+ ComponentInstanceReqDetails compInstDet = componentInstanceReqDetailsList.get(0);
+ compInstDet.setPosX("150");
+ compInstDet.setPosY("150");
+ compInstDet = componentInstanceReqDetailsList.get(1);
+ compInstDet.setPosX("400");
+ compInstDet.setPosY("150");
+ compInstDet = componentInstanceReqDetailsList.get(2);
+ compInstDet.setPosX("150");
+ compInstDet.setPosY("300");
+
+ RestResponse response = ComponentInstanceRestUtils.updateMultipleComponentInstance(
+ componentInstanceReqDetailsList, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), vf.getUniqueId(),
+ vf.getComponentType());
+ assertTrue("response code is not 200, returned: " + response.getErrorCode(),
+ response.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+
+ compInstDet = componentInstanceReqDetailsList.get(0);
+ compInstDet.setPosX("350");
+ compInstDet.setPosY("350");
+ compInstDet = componentInstanceReqDetailsList.get(1);
+ compInstDet.setPosX("600");
+ compInstDet.setPosY("350");
+ compInstDet = componentInstanceReqDetailsList.get(2);
+ compInstDet.setPosX("350");
+ compInstDet.setPosY("500");
+
+ response = ComponentInstanceRestUtils.updateMultipleComponentInstance(componentInstanceReqDetailsList,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), vf.getUniqueId(), vf.getComponentType());
+ assertTrue("response code is not 200, returned: " + response.getErrorCode(),
+ response.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java
new file mode 100644
index 0000000000..76c0c86680
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaCapabilitiesNodeTemplatesDefinition.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public class ToscaCapabilitiesNodeTemplatesDefinition {
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
new file mode 100644
index 0000000000..5ce4b8c618
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import java.util.List;
+
+public class ToscaDefinition {
+
+ String toscaDefinitionVersion;
+ List<ToscaImportsDefinition> toscaImports;
+ List<ToscaNodeTypesDefinition> toscaNodeTypes;
+ ToscaTopologyTemplateDefinition toscaTopologyTemplate;
+
+ public ToscaDefinition() {
+ super();
+ }
+
+ public String getToscaDefinitionVersion() {
+ return toscaDefinitionVersion;
+ }
+
+ public void setToscaDefinitionVersion(String toscaDefinitionVersion) {
+ this.toscaDefinitionVersion = toscaDefinitionVersion;
+ }
+
+ public List<ToscaImportsDefinition> getToscaImports() {
+ return toscaImports;
+ }
+
+ public void setToscaImports(List<ToscaImportsDefinition> toscaImports) {
+ this.toscaImports = toscaImports;
+ }
+
+ public List<ToscaNodeTypesDefinition> getToscaNodeTypes() {
+ return toscaNodeTypes;
+ }
+
+ public void setToscaNodeTypes(List<ToscaNodeTypesDefinition> toscaNodeTypes) {
+ this.toscaNodeTypes = toscaNodeTypes;
+ }
+
+ public ToscaTopologyTemplateDefinition getToscaTopologyTemplate() {
+ return toscaTopologyTemplate;
+ }
+
+ public void setToscaTopologyTemplate(ToscaTopologyTemplateDefinition toscaTopologyTemplate) {
+ this.toscaTopologyTemplate = toscaTopologyTemplate;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaDefinition [toscaDefinitionVersion=" + toscaDefinitionVersion + ", toscaImports=" + toscaImports
+ + ", toscaNodeTypes=" + toscaNodeTypes + ", toscaTopologyTemplate=" + toscaTopologyTemplate + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java
new file mode 100644
index 0000000000..e19fcb3aba
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java
@@ -0,0 +1,78 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import java.util.List;
+
+// spec page 102
+public class ToscaGroupsTopologyTemplateDefinition {
+
+ String type; // required
+ String description;
+ // List<ToscaGroupsProperiesDefinition> toscaGroupsProperiesDefinition;
+ List<String> targets; // required
+ // List<ToscaGroupsInterfacesDefinition> toscaGroupsInterfacesDefinition;
+ List<String> members;
+
+ public ToscaGroupsTopologyTemplateDefinition() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public List<String> getTargets() {
+ return targets;
+ }
+
+ public void setTargets(List<String> targets) {
+ this.targets = targets;
+ }
+
+ public List<String> getMembers() {
+ return members;
+ }
+
+ public void setMembers(List<String> members) {
+ this.members = members;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaGroupsTopologyTemplateDefinition [type=" + type + ", description=" + description + ", targets="
+ + targets + ", members=" + members + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java
new file mode 100644
index 0000000000..5363223c38
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import java.util.List;
+
+import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
+
+public class ToscaImportsDefinition {
+
+ String typeName;
+
+ List<GroupHeatMetaDefinition> groupHeatMetaDefinition;
+
+ public ToscaImportsDefinition() {
+ super();
+ }
+
+ public String getTypeName() {
+ return typeName;
+ }
+
+ public void setTypeName(String typeName) {
+ this.typeName = typeName;
+ }
+
+ public List<GroupHeatMetaDefinition> getGroupHeatMetaDefinition() {
+ return groupHeatMetaDefinition;
+ }
+
+ public void setGroupHeatMetaDefinition(List<GroupHeatMetaDefinition> groupHeatMetaDefinition) {
+ this.groupHeatMetaDefinition = groupHeatMetaDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "TypeHeatMetaDefinition [typeName=" + typeName + ", groupHeatMetaDefinition=" + groupHeatMetaDefinition
+ + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java
new file mode 100644
index 0000000000..62f859c567
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java
@@ -0,0 +1,25 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public class ToscaInputsTopologyTemplateDefinition {
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java
new file mode 100644
index 0000000000..8970467e9c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTemplatesTopologyTemplateDefinition.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import java.util.List;
+
+public class ToscaNodeTemplatesTopologyTemplateDefinition {
+
+ String name;
+ String type;
+ List<ToscaPropertiesNodeTemplatesDefinition> properties;
+ List<ToscaRequirementsNodeTemplatesDefinition> requirements;
+ List<ToscaCapabilitiesNodeTemplatesDefinition> capabilities;
+
+ public ToscaNodeTemplatesTopologyTemplateDefinition() {
+ super();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public List<ToscaPropertiesNodeTemplatesDefinition> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(List<ToscaPropertiesNodeTemplatesDefinition> properties) {
+ this.properties = properties;
+ }
+
+ public List<ToscaRequirementsNodeTemplatesDefinition> getRequirements() {
+ return requirements;
+ }
+
+ public void setRequirements(List<ToscaRequirementsNodeTemplatesDefinition> requirements) {
+ this.requirements = requirements;
+ }
+
+ public List<ToscaCapabilitiesNodeTemplatesDefinition> getCapabilities() {
+ return capabilities;
+ }
+
+ public void setCapabilities(List<ToscaCapabilitiesNodeTemplatesDefinition> capabilities) {
+ this.capabilities = capabilities;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaNodeTemplatesTopologyTemplateDefinition [name=" + name + ", type=" + type + ", properties="
+ + properties + ", requirements=" + requirements + ", capabilities=" + capabilities + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java
new file mode 100644
index 0000000000..148e99c58c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaNodeTypesDefinition.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+// spec page 88
+public class ToscaNodeTypesDefinition {
+
+ String name;
+ String derivedFrom;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDerivedFrom() {
+ return derivedFrom;
+ }
+
+ public void setDerivedFrom(String derivedFrom) {
+ this.derivedFrom = derivedFrom;
+ }
+
+ public ToscaNodeTypesDefinition() {
+ super();
+ }
+
+ @Override
+ public String toString() {
+ return "CsarNodeTypesDefinition [name=" + name + ", derivedFrom=" + derivedFrom + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java
new file mode 100644
index 0000000000..cf0add050d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaPropertiesNodeTemplatesDefinition.java
@@ -0,0 +1,53 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public class ToscaPropertiesNodeTemplatesDefinition {
+
+ String name;
+ Object value;
+
+ public ToscaPropertiesNodeTemplatesDefinition() {
+ super();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public void setValue(Object value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaPropertyNodeTemplatesTopologyTemplateDefinition [name=" + name + ", value=" + value + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java
new file mode 100644
index 0000000000..bd9f0f0f5e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaRequirementsNodeTemplatesDefinition.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+public class ToscaRequirementsNodeTemplatesDefinition {
+
+ String name;
+ String capability;
+ String node;
+ String relationship;
+
+ public ToscaRequirementsNodeTemplatesDefinition() {
+ super();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getCapability() {
+ return capability;
+ }
+
+ public void setCapability(String capability) {
+ this.capability = capability;
+ }
+
+ public String getNode() {
+ return node;
+ }
+
+ public void setNode(String node) {
+ this.node = node;
+ }
+
+ public String getRelationship() {
+ return relationship;
+ }
+
+ public void setRelationship(String relationship) {
+ this.relationship = relationship;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaRequirementsDefinition [name=" + name + ", capability=" + capability + ", node=" + node
+ + ", relationship=" + relationship + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java
new file mode 100644
index 0000000000..549867a562
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaTopologyTemplateDefinition.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.tosca.datatypes;
+
+import java.util.List;
+
+// spec page 104
+public class ToscaTopologyTemplateDefinition {
+
+ String description;
+ List<ToscaInputsTopologyTemplateDefinition> toscaInputsTopologyTemplateDefinition;
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition;
+ // List<ToscaRelationshipTemplatesTopologyTemplateDefinition>
+ List<ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinition;
+ // List<ToscaPoliciesTopologyTemplateDefinition>
+ // toscaPolociesTopologyTemplateDefinition;
+ // List<ToscaOutputsTopologyTemplateDefinition>
+ // toscaOutputsTopologyTemplateDefinition;
+
+ public ToscaTopologyTemplateDefinition() {
+ super();
+ }
+
+ public List<ToscaInputsTopologyTemplateDefinition> getToscaInputsTopologyTemplateDefinition() {
+ return toscaInputsTopologyTemplateDefinition;
+ }
+
+ public void setToscaInputsTopologyTemplateDefinition(
+ List<ToscaInputsTopologyTemplateDefinition> toscaInputsTopologyTemplateDefinition) {
+ this.toscaInputsTopologyTemplateDefinition = toscaInputsTopologyTemplateDefinition;
+ }
+
+ public List<ToscaNodeTemplatesTopologyTemplateDefinition> getToscaNodeTemplatesTopologyTemplateDefinition() {
+ return toscaNodeTemplatesTopologyTemplateDefinition;
+ }
+
+ public void setToscaNodeTemplatesTopologyTemplateDefinition(
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition) {
+ this.toscaNodeTemplatesTopologyTemplateDefinition = toscaNodeTemplatesTopologyTemplateDefinition;
+ }
+
+ public List<ToscaGroupsTopologyTemplateDefinition> getToscaGroupsTopologyTemplateDefinition() {
+ return toscaGroupsTopologyTemplateDefinition;
+ }
+
+ public void setToscaGroupsTopologyTemplateDefinition(
+ List<ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinition) {
+ this.toscaGroupsTopologyTemplateDefinition = toscaGroupsTopologyTemplateDefinition;
+ }
+
+ @Override
+ public String toString() {
+ return "ToscaTopologyTemplateDefinition [toscaInputsTopologyTemplateDefinition="
+ + toscaInputsTopologyTemplateDefinition + ", toscaNodeTemplatesTopologyTemplateDefinition="
+ + toscaNodeTemplatesTopologyTemplateDefinition + ", toscaGroupsTopologyTemplateDefinition="
+ + toscaGroupsTopologyTemplateDefinition + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java
new file mode 100644
index 0000000000..9ca8adee53
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/AddUserAuditMessageInfo.java
@@ -0,0 +1,113 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.users;
+
+public class AddUserAuditMessageInfo {
+
+ String TIMESTAMP;
+ String ACTION;
+ // String MODIFIER_NAME;
+ String MODIFIER;
+ // String USER_UID;
+ // String USER_NAME;
+ // String USER_EMAIL;
+ // String USER_ROLE;
+ String USER;
+ String STATUS;
+ String DESC;
+
+ public AddUserAuditMessageInfo(String timestamp, String action, String modifierName, String modifierUid,
+ String user, String status, String desc) {
+ super();
+ this.TIMESTAMP = timestamp;
+ this.ACTION = action;
+ // this.MODIFIER_NAME = modifierName;
+ this.MODIFIER = modifierUid;
+ this.USER = user;
+ this.STATUS = status;
+ this.DESC = desc;
+ }
+
+ public AddUserAuditMessageInfo() {
+ super();
+ }
+
+ public String getTIMESTAMP() {
+ return TIMESTAMP;
+ }
+
+ public void setTIMESTAMP(String tIMESTAMP) {
+ TIMESTAMP = tIMESTAMP;
+ }
+
+ public String getACTION() {
+ return ACTION;
+ }
+
+ public void setACTION(String aCTION) {
+ ACTION = aCTION;
+ }
+
+ // public String getMODIFIER_NAME() {
+ // return MODIFIER_NAME;
+ // }
+ // public void setMODIFIER_NAME(String mODIFIER_NAME) {
+ // MODIFIER_NAME = mODIFIER_NAME;
+ // }
+ public String getMODIFIER() {
+ return MODIFIER;
+ }
+
+ public void setMODIFIER(String mODIFIER_UID) {
+ MODIFIER = mODIFIER_UID;
+ }
+
+ public String getUSER() {
+ return USER;
+ }
+
+ public void setUSER(String uSER) {
+ USER = uSER;
+ }
+
+ public String getSTATUS() {
+ return STATUS;
+ }
+
+ public void setSTATUS(String sTATUS) {
+ STATUS = sTATUS;
+ }
+
+ public String getDESC() {
+ return DESC;
+ }
+
+ public void setDESC(String dESC) {
+ DESC = dESC;
+ }
+
+ @Override
+ public String toString() {
+ return "AddUserAuditMessageInfo [timestamp=" + TIMESTAMP + ", action=" + ACTION + ", modifierUid=" + MODIFIER
+ + ", user=" + USER + ", status=" + STATUS + ", desc=" + DESC + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java
new file mode 100644
index 0000000000..b34d474cf0
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserAuditJavaObject.java
@@ -0,0 +1,133 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.users;
+
+public class UserAuditJavaObject {
+
+ String TIMESTAMP;
+ String ACTION;
+ // String MODIFIER_NAME;
+ String MODIFIER;
+ String USER;
+ // String USER_NAME;
+ // String USER_EMAIL;
+ // String USER_ROLE;
+ String STATUS;
+ String DESC;
+
+ public UserAuditJavaObject(String timestamp, String action, String modifier, String user, String status,
+ String desc) {
+ super();
+ this.TIMESTAMP = timestamp;
+ this.ACTION = action;
+ // this.MODIFIER_NAME = modifierName;
+ this.MODIFIER = modifier;
+ this.USER = user;
+ // this.USER_NAME = userName;
+ // this.USER_EMAIL = userEmail;
+ // this.USER_ROLE = userRole;
+ this.STATUS = status;
+ this.DESC = desc;
+ }
+
+ public UserAuditJavaObject() {
+ super();
+ }
+
+ public String getTIMESTAMP() {
+ return TIMESTAMP;
+ }
+
+ public void setTIMESTAMP(String tIMESTAMP) {
+ TIMESTAMP = tIMESTAMP;
+ }
+
+ public String getACTION() {
+ return ACTION;
+ }
+
+ public void setACTION(String aCTION) {
+ ACTION = aCTION;
+ }
+
+ // public String getMODIFIER_NAME() {
+ // return MODIFIER_NAME;
+ // }
+ // public void setMODIFIER_NAME(String mODIFIER_NAME) {
+ // MODIFIER_NAME = mODIFIER_NAME;
+ // }
+ public String getMODIFIER() {
+ return MODIFIER;
+ }
+
+ public void setMODIFIER(String mODIFIER_UID) {
+ MODIFIER = mODIFIER_UID;
+ }
+
+ public String getUSER() {
+ return USER;
+ }
+
+ public void setUSER(String uSER) {
+ USER = uSER;
+ }
+
+ // public String getUSER_NAME() {
+ // return USER_NAME;
+ // }
+ // public void setUSER_NAME(String uSER_NAME) {
+ // USER_NAME = uSER_NAME;
+ // }
+ // public String getUSER_EMAIL() {
+ // return USER_EMAIL;
+ // }
+ // public void setUSER_EMAIL(String uSER_EMAIL) {
+ // USER_EMAIL = uSER_EMAIL;
+ // }
+ // public String getUSER_ROLE() {
+ // return USER_ROLE;
+ // }
+ // public void setUSER_ROLE(String uSER_ROLE) {
+ // USER_ROLE = uSER_ROLE;
+ // }
+ public String getSTATUS() {
+ return STATUS;
+ }
+
+ public void setSTATUS(String sTATUS) {
+ STATUS = sTATUS;
+ }
+
+ public String getDESC() {
+ return DESC;
+ }
+
+ public void setDESC(String dESC) {
+ DESC = dESC;
+ }
+
+ @Override
+ public String toString() {
+ return "UserAuditJavaObject [timestamp=" + TIMESTAMP + ", action=" + ACTION + ", modifier=" + MODIFIER
+ + ", user=" + USER + ", status=" + STATUS + ", desc=" + DESC + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java
new file mode 100644
index 0000000000..06320bcb5f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserHeaderData.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.users;
+
+public class UserHeaderData {
+ String contentType;
+ String httpCspUserId;
+ String accept;
+
+ public UserHeaderData(String contentType, String httpCspUserId, String accept) {
+ super();
+ this.contentType = contentType;
+ this.httpCspUserId = httpCspUserId;
+ this.accept = accept;
+ }
+
+ public String getContentType() {
+ return contentType;
+ }
+
+ public void setContentType(String contentType) {
+ this.contentType = contentType;
+ }
+
+ public String getHttpCspUserId() {
+ return httpCspUserId;
+ }
+
+ public void setHttpCspUserId(String httpCspUserId) {
+ this.httpCspUserId = httpCspUserId;
+ }
+
+ public String getAccept() {
+ return accept;
+ }
+
+ public void setAccept(String accept) {
+ this.accept = accept;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java
new file mode 100644
index 0000000000..4db52c2886
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/UserResponseMessageEnum.java
@@ -0,0 +1,48 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.users;
+
+public enum UserResponseMessageEnum {
+
+ SUCCESS_MESSAGE("OK"),
+ MISSING_INFORMATION("Error: Missing information"),
+ METHOD_NOT_ALLOWED("Error: Method not allowed"),
+ RESTRICTED_OPERATION("Error: Restricted operation"),
+ USER_ALREADY_EXISTS("Error: User with %s ID already exists"),
+ INVALID_EMAIL("Error: Invalid Content. Invalid e-mail address %s"),
+ INVALID_ROLE("Error: Invalid Content. Invalid role %s"),
+ INVALID_CONTENT("Error: Invalid content"),
+ USER_NOT_FOUND("Error: User with %s ID is not found"),
+ INTERNAL_SERVER_ERROR("Error: Internal Server Error. Try later again"),
+ ADMINISTARTOR_CAN_BE_DELETED("Error: Administrator can be deleted by other administrator only"),
+ RESTRICTED_ACCESS("Error: Restricted access");
+
+ String value;
+
+ private UserResponseMessageEnum(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java
new file mode 100644
index 0000000000..609ebf22b7
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/users/WebSealUserDetails.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.users;
+
+public class WebSealUserDetails {
+ String firstName;
+ String lastName;
+ String userId;
+ String email;
+
+ public WebSealUserDetails() {
+ super();
+ }
+
+ public WebSealUserDetails(String firstName, String lastName, String userId, String emailAddress) {
+ super();
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.userId = userId;
+ this.email = emailAddress;
+
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getEmailAddress() {
+ return email;
+ }
+
+ public void setEmailAddress(String emailAddress) {
+ this.email = emailAddress;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
new file mode 100644
index 0000000000..12f8ffe984
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ArtifactUtils.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
+public class ArtifactUtils {
+
+ public static ArtifactDefinition convertArtifactReqToDefinition(ArtifactReqDetails artifactReq) {
+ ArtifactDefinition artifact = new ArtifactDefinition();
+ artifact.setArtifactLabel(artifactReq.getArtifactLabel());
+ artifact.setArtifactDisplayName(artifactReq.getArtifactDisplayName());
+ artifact.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifactReq.getArtifactGroupType()));
+ artifact.setArtifactType(artifactReq.getArtifactType().toUpperCase());
+ artifact.setArtifactName(artifactReq.getArtifactName());
+ artifact.setDescription(artifactReq.getDescription());
+ artifact.setUniqueId(artifactReq.getUniqueId());
+ artifact.setTimeout(artifactReq.getTimeout());
+ artifact.setEsId(artifactReq.getUniqueId());
+
+ return artifact;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
new file mode 100644
index 0000000000..22295cb451
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/DbUtils.java
@@ -0,0 +1,306 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.apache.tinkerpop.gremlin.structure.Edge;
+import org.apache.tinkerpop.gremlin.structure.Element;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject;
+import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import com.thinkaurelius.titan.core.TitanEdge;
+import com.thinkaurelius.titan.core.TitanFactory;
+import com.thinkaurelius.titan.core.TitanGraph;
+import com.thinkaurelius.titan.core.TitanVertex;
+
+import fj.data.Either;
+
+public class DbUtils {
+
+ private static String titanConfigFilePath;
+ private static TitanGraph titanGraph;
+
+ public static void cleanAllAudits() throws IOException {
+ // utils.deleteFromEsDbByPattern("_all");
+ // deleteFromEsDbByPattern("auditingevents-*");
+ CassandraUtils.truncateAllTables("sdcaudit");
+
+ // List <EsIndexTypeIdToDelete> auditIdArray = new
+ // ArrayList<EsIndexTypeIdToDelete>();
+ // auditIdArray = buildObjectArrayListByTypesIndex("auditingevents*",
+ // "useraccessevent");
+ //
+ // logger.info("Starting to delete all service topologies from ES");
+ // for (int i = 0; i < auditIdArray.size(); i ++){
+ // EsIndexTypeIdToDelete esIndexTypeIdToDelete = auditIdArray.get(i);
+ // utils.deleteFromEsDbByPattern(esIndexTypeIdToDelete.getIndex()+"/"+esIndexTypeIdToDelete.getType()+"/"+esIndexTypeIdToDelete.getId());
+ //
+ // }
+ }
+
+ public static RestResponse deleteFromEsDbByPattern(String patternToDelete) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(),
+ patternToDelete);
+ HttpRequest httpRequest = new HttpRequest();
+ RestResponse restResponse = httpRequest.httpSendDelete(url, null);
+ restResponse.getErrorCode();
+ // System.out.println("URL to delete" + url);
+ // System.out.println("response code" + restResponse.getErrorCode());
+ cleanAllAudits();
+
+ return restResponse;
+ }
+
+ public static RestResponse getFromEsByPattern(String patternToGet) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), patternToGet);
+ HttpRequest httpRequest = new HttpRequest();
+ RestResponse restResponse = httpRequest.httpSendGet(url, null);
+ restResponse.getErrorCode();
+ // System.out.println("URL to get" + url);
+ // System.out.println("response code" + restResponse.getErrorCode());
+
+ return restResponse;
+ }
+
+ public Either<Vertex, Boolean> getVertexByUId(String uid) {
+ TitanGraph titanGraph = getTitanGraph();
+ Either<Vertex, Boolean> result = Either.right(false);
+ // Iterator<Vertex> vertexItr = titanGraph.getVertices().iterator();
+
+ Iterator<TitanVertex> vertexItr = titanGraph.query().vertices().iterator();
+ while (vertexItr.hasNext()) {
+ Vertex vertex = vertexItr.next();
+ // String uidFoundVal = vertex.getProperty("uid");
+ String uidFoundVal = vertex.value("uid");
+ if (uid.equals(uidFoundVal)) {
+ result = Either.left(vertex);
+ }
+ }
+ return result;
+ }
+
+ public static TitanState getCurrentTitanState() {
+ TitanGraph titanGraph = getTitanGraph();
+ List<Vertex> vertices = new ArrayList<>();
+ List<Edge> edges = new ArrayList<>();
+ // Iterator<Edge> edgesItr = titanGraph.getEdges().iterator();
+ Iterator<TitanEdge> edgesItr = titanGraph.query().edges().iterator();
+ // Iterator<Vertex> verticesItr = titanGraph.getVertices().iterator();
+ Iterator<TitanVertex> verticesItr = titanGraph.query().vertices().iterator();
+ while (edgesItr.hasNext()) {
+ edges.add(edgesItr.next());
+ }
+ while (verticesItr.hasNext()) {
+ vertices.add(verticesItr.next());
+ }
+
+ TitanState currState = new TitanState(edges, vertices);
+ return currState;
+
+ }
+
+ //
+ private static TitanGraph getTitanGraph() {
+ if (titanGraph == null) {
+ titanGraph = TitanFactory.open(titanConfigFilePath);
+ }
+ return titanGraph;
+ }
+
+ public void restoreToTitanState(TitanState titanStateToRestoreTo) {
+ List<Vertex> verticesToRemove = new ArrayList<>(), verticesToAdd = new ArrayList<>();
+ List<Edge> edgesToRemove = new ArrayList<>(), edgesToAdd = new ArrayList<>();
+
+ TitanState currentTitanState = getCurrentTitanState();
+
+ List<Edge> joinedEdges = new ArrayList<>();
+ joinedEdges.addAll(titanStateToRestoreTo.edges);
+ joinedEdges.retainAll(currentTitanState.edges);
+
+ List<Vertex> joinedVertices = new ArrayList<>();
+ joinedVertices.addAll(titanStateToRestoreTo.vertices);
+ joinedVertices.retainAll(currentTitanState.vertices);
+
+ edgesToRemove.addAll(currentTitanState.edges);
+ edgesToRemove.removeAll(joinedEdges);
+
+ verticesToRemove.addAll(currentTitanState.vertices);
+ verticesToRemove.removeAll(joinedVertices);
+
+ edgesToAdd.addAll(titanStateToRestoreTo.edges);
+ edgesToAdd.removeAll(joinedEdges);
+
+ verticesToAdd.addAll(titanStateToRestoreTo.vertices);
+ verticesToAdd.removeAll(joinedVertices);
+
+ modifyGraphAccordingToDelta(verticesToRemove, verticesToAdd, edgesToRemove, edgesToAdd);
+
+ }
+
+ private void modifyGraphAccordingToDelta(List<Vertex> verticesToRemove, List<Vertex> verticesToAdd,
+ List<Edge> edgesToRemove, List<Edge> edgesToAdd) {
+
+ TitanGraph titanGraph = getTitanGraph();
+
+ for (Vertex vertex : verticesToRemove) {
+ // titanGraph.removeVertex(vertex);
+ vertex.remove();
+ }
+ for (Vertex vertex : verticesToAdd) {
+ TitanVertex titanVertex = titanGraph.addVertex();
+ copyProperties(vertex, titanVertex);
+ }
+
+ for (Edge edge : edgesToRemove) {
+ // titanGraph.removeEdge(edge);
+ edge.remove();
+ }
+
+ for (Edge edge : edgesToAdd) {
+ // Element addedEdge = titanGraph.addEdge(edge.getId(),
+ // edge.getVertex(Direction.OUT), edge.getVertex(Direction.IN),
+ // edge.getLabel());
+
+ // Edge edge = tGraph.addEdge(null, fromV.left().value(),
+ // toV.left().value(), type);
+
+ Element addedEdge = edge.outVertex().addEdge(edge.label(), edge.inVertex());
+
+ copyProperties(edge, addedEdge);
+
+ }
+
+ // titanGraph.commit();
+ titanGraph.tx().commit();
+
+ }
+
+ private void copyProperties(Element copyFrom, Element copyTo) {
+ // Set<String> properties = copyFrom.getPropertyKeys();
+ Set<String> properties = copyFrom.keys();
+ for (String propertyKey : properties) {
+ // copyTo.setProperty(propertyKey,
+ // copyFrom.getProperty(propertyKey));
+ copyTo.property(propertyKey, copyFrom.value(propertyKey));
+ }
+
+ }
+
+ public static class TitanState {
+ private List<Edge> edges;
+ private List<Vertex> vertices;
+
+ private TitanState(List<Edge> edges, List<Vertex> vertices) {
+ this.edges = edges;
+ this.vertices = vertices;
+ }
+
+ @Override
+ public String toString() {
+ return "TitanState [edges=" + edges.size() + ", vertices=" + vertices.size() + "]";
+ }
+
+ }
+
+ public void shutDowntitan() {
+ if (titanGraph != null) {
+ // titanGraph.shutdown();
+ titanGraph.close();
+ }
+ }
+
+ public static void setProperties(Element element, Map<String, Object> properties) {
+
+ if (properties != null && false == properties.isEmpty()) {
+
+ Object[] propertyKeyValues = new Object[properties.size() * 2];
+ int i = 0;
+ for (Entry<String, Object> entry : properties.entrySet()) {
+ propertyKeyValues[i++] = entry.getKey();
+ propertyKeyValues[i++] = entry.getValue();
+ }
+
+ ElementHelper.attachProperties(element, propertyKeyValues);
+
+ }
+
+ }
+
+ public static UserAuditJavaObject parseAuditRespByAction(String action) throws Exception {
+
+ // String index = "auditingevents*";
+ // String type = "useradminevent";
+ // String pattern = "/_search?q=action:\""+action+"\"";
+ // String auditingMessage = retrieveAuditMessageByIndexType(index, type,
+ // pattern);
+ UserAuditJavaObject auditParsedResp = new UserAuditJavaObject();
+ Gson gson = new Gson();
+
+ String pattern = "/_search?q=ACTION:\"" + action + "\"";
+ String auditingMessage = retrieveAuditMessagesByPattern(pattern);
+ JsonElement jElement = new JsonParser().parse(auditingMessage);
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonObject hitsObject = (JsonObject) jObject.get("hits");
+ JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
+ // for (int i = 0; i < hitsArray.size();){
+ if (hitsArray.size() == 0) {
+ return auditParsedResp;
+ }
+ JsonObject jHitObject = (JsonObject) hitsArray.get(0);
+ JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
+
+ auditParsedResp = gson.fromJson(jSourceObject, UserAuditJavaObject.class);
+ // logger.debug("auditParsedResp: {}", auditParsedResp);
+
+ return auditParsedResp;
+
+ }
+
+ public static String retrieveAuditMessagesByPattern(String pattern) throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest getAuditingMessage = new HttpRequest();
+ String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), pattern);
+ RestResponse restResponse = getAuditingMessage.httpSendGet(url, null);
+
+ return restResponse.getResponse();
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
new file mode 100644
index 0000000000..7d90eb0b6d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Decoder.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.apache.commons.codec.binary.Base64;
+
+public class Decoder {
+
+ public static String encode(byte[] byteArrayToEncode) {
+
+ byte[] bytesEncoded = Base64.encodeBase64(byteArrayToEncode);
+ String strEncoded = new String(bytesEncoded);
+ return strEncoded;
+ }
+
+ public static String decode(String strEncoded) throws IOException {
+
+ byte[] byteDecoded = Base64.decodeBase64(strEncoded);
+ String decoded = new String(byteDecoded);
+
+ return decoded;
+
+ }
+
+ public static String readFileToString(String file) throws IOException {
+
+ BufferedReader reader = new BufferedReader(new FileReader(file));
+ String line = null;
+ StringBuilder stringBuilder = new StringBuilder();
+ String ls = System.getProperty("line.separator");
+
+ while ((line = reader.readLine()) != null) {
+ stringBuilder.append(line);
+ stringBuilder.append(ls);
+ }
+ reader.close();
+ return stringBuilder.toString();
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
new file mode 100644
index 0000000000..66d2a8450c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ReqCap.java
@@ -0,0 +1,630 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.testng.Assert;
+
+public class ReqCap {
+
+ public static Map<String, List<CapabilityDefinition>> expectedContainerCapabilities;
+ public static Map<String, List<RequirementDefinition>> expectedContainerRequirements;
+ public static Map<String, RequirementDefinition> removedRequirements;
+ public static Map<String, ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>> expectedContInstReqCap;
+
+ public static void verifyVFReqCap(String componentId) throws Exception {
+ RestResponse restResponse = ResourceRestUtils.getResource(componentId);
+ Resource resource = ResponseParser.parseToObject(restResponse.getResponse(), Resource.class);
+ verifyReqCap(resource);
+ }
+
+ public static void verifyServiceReqCap(String componentId, User sdncDesignerDetails) throws Exception {
+ RestResponse restResponse = ServiceRestUtils.getService(componentId, sdncDesignerDetails);
+ Service service = ResponseParser.parseToObject(restResponse.getResponse(), Service.class);
+ verifyReqCap(service);
+ }
+
+ public static void verifyProductReqCap(String componentId, User sdncPsDetails1) throws Exception {
+ RestResponse restResponse = ProductRestUtils.getProduct(componentId, sdncPsDetails1.getUserId());
+ Product product = ResponseParser.parseToObject(restResponse.getResponse(), Product.class);
+ verifyReqCap(product);
+ }
+
+ public static void verifyReqCap(Component actualComponent) {
+ verifyContainerReqCap(actualComponent);
+ verifyCompInstReqCap(actualComponent);
+ }
+
+ public RestResponse changeServiceInstanceVersion(String componentUniqueId, String serviceInstanceToReplaceUniqueId,
+ String serviceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType, boolean isHighestLevel)
+ throws Exception {
+ RestResponse changeResourceInstanceVersion = ProductRestUtils.changeServiceInstanceVersion(componentUniqueId,
+ serviceInstanceToReplaceUniqueId, serviceUniqueId, sdncModifierDetails, componentType);
+ if (changeResourceInstanceVersion.getErrorCode().equals(BaseRestUtils.STATUS_CODE_SUCCESS) && isHighestLevel) {
+ /*
+ * // Add RI Capabilities and Requirements to expected MAP -->
+ * expectedVfCapabilities and expectedVfRequirements
+ *
+ * ComponentInstance componentInstance =
+ * ResponseParser.parseToObjectUsingMapper(
+ * changeResourceInstanceVersion.getResponse(),
+ * ComponentInstance.class);
+ * addCompInstReqCapToExpected(componentInstance, componentType);
+ */
+ }
+ return changeResourceInstanceVersion;
+ }
+
+ public static void updateExpectedReqCapAfterChangeLifecycleState(String oldContainerUniqueIdToReplace,
+ String newContainerUniqueId) {
+
+ // Update of container req/cap
+
+ Set<String> compInstKeysToChange = new HashSet<>();
+
+ for (String expKey : expectedContainerCapabilities.keySet()) {
+ List<CapabilityDefinition> expCapList = expectedContainerCapabilities.get(expKey);
+ for (CapabilityDefinition cap : expCapList) {
+ String ownerId = cap.getOwnerId();
+
+ if (ownerId.contains(oldContainerUniqueIdToReplace)) {
+ compInstKeysToChange.add(ownerId);
+ cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ }
+ }
+ }
+
+ for (String expKey : expectedContainerRequirements.keySet()) {
+ List<RequirementDefinition> expCapList = expectedContainerRequirements.get(expKey);
+ for (RequirementDefinition cap : expCapList) {
+ String ownerId = cap.getOwnerId();
+ if (ownerId.contains(oldContainerUniqueIdToReplace)) {
+ compInstKeysToChange.add(ownerId);
+ cap.setOwnerId(cap.getOwnerId().replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId));
+ }
+ }
+ }
+
+ // Update of internal comp instances req/cap
+ for (String oldKey : compInstKeysToChange) {
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> immutablePair = expectedContInstReqCap
+ .get(oldKey);
+ if (immutablePair != null) {
+ expectedContInstReqCap.remove(oldKey);
+ String newKey = oldKey.replaceAll(oldContainerUniqueIdToReplace, newContainerUniqueId);
+ expectedContInstReqCap.put(newKey, immutablePair);
+ }
+ }
+ }
+
+ private static void verifyCompInstReqCap(Component actualComponent) {
+ List<ComponentInstance> componentInstances = actualComponent.getComponentInstances();
+ if (componentInstances != null) {
+ assertEquals(expectedContInstReqCap.size(), componentInstances.size());
+ for (ComponentInstance compInst : componentInstances) {
+ String uniqueId = compInst.getUniqueId();
+ // System.out.println("Verifying req/cap of component instance
+ // "+ uniqueId);
+ Map<String, List<RequirementDefinition>> actualCompInstReq = compInst.getRequirements();
+ if (actualCompInstReq == null) {
+ actualCompInstReq = new HashMap<>();
+ }
+ Map<String, List<CapabilityDefinition>> actualCompInstCap = compInst.getCapabilities();
+ if (actualCompInstCap == null) {
+ actualCompInstCap = new HashMap<>();
+ }
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> expReqCap = expectedContInstReqCap
+ .get(uniqueId);
+ assertNotNull(expReqCap);
+ // System.out.println("expected instance requirements:
+ // "+expReqCap.right);
+ // System.out.println("expected instance capabilities:
+ // "+expReqCap.left);
+ // System.out.println("actual instance requirements:
+ // "+actualCompInstReq);
+ // System.out.println("actual instance capabilities:
+ // "+actualCompInstCap);
+
+ // REQ comparison
+ compareReqCapMaps(expReqCap.right, actualCompInstReq);
+
+ // CAP comparison
+ compareReqCapMaps(expReqCap.left, actualCompInstCap);
+ }
+
+ } else {
+ assertTrue(expectedContInstReqCap.isEmpty());
+ }
+ }
+
+ private static void verifyContainerReqCap(Component actualComponent) {
+ Map<String, List<RequirementDefinition>> actualContainerRequirements = actualComponent.getRequirements();
+ if (actualContainerRequirements == null) {
+ actualContainerRequirements = new HashMap<>();
+ }
+ Map<String, List<CapabilityDefinition>> actualContainerCapabilities = actualComponent.getCapabilities();
+ if (actualContainerCapabilities == null) {
+ actualContainerCapabilities = new HashMap<>();
+ }
+ // System.out.println("Verifying req/cap of container component "+
+ // actualComponent.getUniqueId());
+ // System.out.println("expected container requirements:
+ // "+expectedContainerRequirements);
+ // System.out.println("expected container capabilities:
+ // "+expectedContainerCapabilities);
+ // System.out.println("actual container requirements:
+ // "+actualContainerRequirements);
+ // System.out.println("actual container capabilities:
+ // "+actualContainerCapabilities);
+
+ // REQ comparison
+ compareReqCapMaps(expectedContainerRequirements, actualContainerRequirements);
+
+ // CAP comparison
+ compareReqCapMaps(expectedContainerCapabilities, actualContainerCapabilities);
+ }
+
+ private static <T> void compareReqCapMaps(Map<String, List<T>> expectedMap, Map<String, List<T>> actualMap) {
+ assertEquals(expectedMap.size(), actualMap.size());
+ for (String expKey : expectedMap.keySet()) {
+ List<?> expCapList = expectedMap.get(expKey);
+ List<?> actCapList = actualMap.get(expKey);
+ assertEquals(expCapList.size(), actCapList.size());
+ assertEquals(new HashSet<>(expCapList), new HashSet<>(actCapList));
+ }
+ }
+
+ public static void addCompInstReqCapToExpected(ComponentInstance componentInstance,
+ ComponentTypeEnum containerComponentType, User sdncDesignerDetails) throws Exception {
+
+ sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ String uniqueId = componentInstance.getUniqueId();
+ String name = componentInstance.getName();
+ String originComponentId = componentInstance.getComponentUid();
+ RestResponse getResponse = null;
+ ComponentTypeEnum compInstType = getCompInstTypeByContainerType(containerComponentType);
+ Component component = null;
+ if (compInstType == ComponentTypeEnum.RESOURCE) {
+ getResponse = ResourceRestUtils.getResource(sdncDesignerDetails, originComponentId);
+ ResourceRestUtils.checkSuccess(getResponse);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (compInstType == ComponentTypeEnum.SERVICE) {
+ getResponse = ServiceRestUtils.getService(originComponentId, sdncDesignerDetails);
+ ResourceRestUtils.checkSuccess(getResponse);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else {
+ Assert.fail("Unsupported type - " + containerComponentType);
+ }
+
+ Map<String, List<RequirementDefinition>> resourceRequirements = component.getRequirements();
+ if (resourceRequirements == null) {
+ resourceRequirements = new HashMap<>();
+ }
+
+ Function<Entry<String, List<RequirementDefinition>>, List<RequirementDefinition>> requirementDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new RequirementDefinition(item)).collect(Collectors.toList()));
+ Map<String, List<RequirementDefinition>> reqCopy = resourceRequirements.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), requirementDefinitionMapper));
+
+ Map<String, List<CapabilityDefinition>> resourceCapabilities = component.getCapabilities();
+ if (resourceCapabilities == null) {
+ resourceCapabilities = new HashMap<>();
+ }
+
+ Function<Entry<String, List<CapabilityDefinition>>, List<CapabilityDefinition>> capabilityDefinitionMapper = e -> new ArrayList<>(e.getValue().stream().map(item -> new CapabilityDefinition(item)).collect(Collectors.toList()));
+ Map<String, List<CapabilityDefinition>> capCopy = resourceCapabilities.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), capabilityDefinitionMapper));
+
+ setupContainerExpectedReqCap(uniqueId, name, resourceRequirements, resourceCapabilities);
+ if (component.getComponentType().equals(ComponentTypeEnum.RESOURCE)
+ && ((Resource) component).getResourceType() != ResourceTypeEnum.VF) {
+ setupConstInstExpectedReqCap(uniqueId, name, reqCopy, capCopy);
+ }
+
+ // adding entry for expected componentInstance
+ ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>> compInstReqCapPair = new ImmutablePair<Map<String, List<CapabilityDefinition>>, Map<String, List<RequirementDefinition>>>(
+ capCopy, reqCopy);
+ expectedContInstReqCap.put(uniqueId, compInstReqCapPair);
+ }
+
+ private static void setupContainerExpectedReqCap(String uniqueId, String name,
+ Map<String, List<RequirementDefinition>> componentRequirements,
+ Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
+ List<RequirementDefinition> reqListToAdd = resReq.getValue();
+ for (RequirementDefinition requirementDefinition : reqListToAdd) {
+ requirementDefinition.setOwnerId(uniqueId);
+ requirementDefinition.setOwnerName(name);
+ }
+ List<RequirementDefinition> expectedReqList = expectedContainerRequirements.get(resReq.getKey());
+ if (expectedReqList == null) {
+ expectedReqList = reqListToAdd;
+ } else {
+ expectedReqList.addAll(reqListToAdd);
+ }
+ expectedContainerRequirements.put(resReq.getKey(), expectedReqList);
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
+ List<CapabilityDefinition> capListToAdd = resCap.getValue();
+ for (CapabilityDefinition capDefinition : capListToAdd) {
+ capDefinition.setOwnerId(uniqueId);
+ capDefinition.setOwnerName(name);
+ }
+ List<CapabilityDefinition> expectedCapList = expectedContainerCapabilities.get(resCap.getKey());
+ if (expectedCapList == null) {
+ expectedCapList = capListToAdd;
+ } else {
+ expectedCapList.addAll(capListToAdd);
+ }
+ expectedContainerCapabilities.put(resCap.getKey(), expectedCapList);
+ }
+ }
+
+ private static void setupConstInstExpectedReqCap(String uniqueId, String name,
+ Map<String, List<RequirementDefinition>> componentRequirements,
+ Map<String, List<CapabilityDefinition>> componentCapabilities) {
+ for (Entry<String, List<RequirementDefinition>> resReq : componentRequirements.entrySet()) {
+ List<RequirementDefinition> reqListToAdd = resReq.getValue();
+ for (RequirementDefinition requirementDefinition : reqListToAdd) {
+ requirementDefinition.setOwnerId(uniqueId);
+ requirementDefinition.setOwnerName(name);
+ }
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> resCap : componentCapabilities.entrySet()) {
+ List<CapabilityDefinition> capListToAdd = resCap.getValue();
+ for (CapabilityDefinition capDefinition : capListToAdd) {
+ capDefinition.setOwnerId(uniqueId);
+ capDefinition.setOwnerName(name);
+ }
+ }
+ }
+
+ private static ComponentTypeEnum getCompInstTypeByContainerType(ComponentTypeEnum componentType) {
+ switch (componentType) {
+ case RESOURCE:
+ return ComponentTypeEnum.RESOURCE;
+ case SERVICE:
+ return ComponentTypeEnum.RESOURCE;
+ case PRODUCT:
+ return ComponentTypeEnum.SERVICE;
+ default:
+ break;
+ }
+ return null;
+ }
+
+ public static void deleteCompInstReqCapFromExpected(String componentInstanceId) {
+ List<String> entriesRequirementsToRemove = new ArrayList<>();
+ List<String> entriesCapabilitiesToRemove = new ArrayList<>();
+ for (Entry<String, List<RequirementDefinition>> reqEntry : expectedContainerRequirements.entrySet()) {
+ List<RequirementDefinition> reqList = reqEntry.getValue();
+ List<RequirementDefinition> reqListToDelete = new ArrayList<>();
+ for (RequirementDefinition requirementDefinition : reqList) {
+ if (requirementDefinition.getOwnerId().equals(componentInstanceId)) {
+ reqListToDelete.add(requirementDefinition);
+ }
+ }
+ reqList.removeAll(reqListToDelete);
+ if (reqList.isEmpty()) {
+ entriesRequirementsToRemove.add(reqEntry.getKey());
+ }
+ }
+
+ for (String ekey : entriesRequirementsToRemove) {
+ expectedContainerRequirements.remove(ekey);
+ }
+
+ for (Entry<String, List<CapabilityDefinition>> capEntry : expectedContainerCapabilities.entrySet()) {
+ List<CapabilityDefinition> capList = capEntry.getValue();
+ List<CapabilityDefinition> capListToDelete = new ArrayList<>();
+ for (CapabilityDefinition capabilityDefinition : capList) {
+ if (capabilityDefinition.getOwnerId().equals(componentInstanceId)) {
+ capListToDelete.add(capabilityDefinition);
+ }
+ }
+ capList.removeAll(capListToDelete);
+ if (capList.isEmpty()) {
+ entriesCapabilitiesToRemove.add(capEntry.getKey());
+ }
+ }
+ for (String ekey : entriesCapabilitiesToRemove) {
+ expectedContainerCapabilities.remove(ekey);
+ }
+
+ expectedContInstReqCap.remove(componentInstanceId);
+
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse createAtomicInstanceForVF(Resource containerDetails, Resource compInstOriginDetails,
+ User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE,
+ true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse createAtomicInstanceForService(Service containerDetails, Resource compInstOriginDetails,
+ User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
+ true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse createVFInstance(Service containerDetails, Resource compInstOriginDetails, User modifier)
+ throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
+ true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse createServiceInstance(Product containerDetails, Service compInstOriginDetails,
+ User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT,
+ true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse deleteAtomicInstanceForVF(String compInstUniqueId, Resource containerDetails,
+ User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse deleteAtomicInstanceForService(String compInstUniqueId, Service containerDetails,
+ User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse deleteVFInstance(String compInstUniqueId, Service containerDetails, User modifier)
+ throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, true);
+
+ }
+
+ // Automatically updates the expected req/cap of the container
+ public static RestResponse deleteServiceInstance(String compInstUniqueId, Product containerDetails, User modifier)
+ throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, true);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse createAtomicInstanceForVFDuringSetup(Resource containerDetails,
+ Resource compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.RESOURCE,
+ false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse createAtomicInstanceForServiceDuringSetup(Service containerDetails,
+ Resource compInstOriginDetails, User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
+ false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse createVFInstanceDuringSetup(Service containerDetails, Resource compInstOriginDetails,
+ User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.SERVICE,
+ false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse createServiceInstanceDuringSetup(Product containerDetails, Service compInstOriginDetails,
+ User modifier) throws Exception {
+ return createComponentInstance(containerDetails, compInstOriginDetails, modifier, ComponentTypeEnum.PRODUCT,
+ false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse deleteAtomicInstanceForVFDuringSetup(String compInstUniqueId, Resource containerDetails,
+ User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.RESOURCE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse deleteAtomicInstanceForServiceDuringSetup(String compInstUniqueId,
+ Service containerDetails, User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse deleteVFInstanceDuringSetup(String compInstUniqueId, Service containerDetails,
+ User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.SERVICE, false);
+
+ }
+
+ // Setup of lower components - Doesn't affect req/cap of the container (for
+ // example, setup of VF for testing a Product)
+ public static RestResponse deleteServiceInstanceDuringSetup(String compInstUniqueId, Product containerDetails,
+ User modifier) throws IOException, Exception {
+ return deleteComponentInstance(compInstUniqueId, containerDetails, modifier, ComponentTypeEnum.PRODUCT, false);
+ }
+
+ public static Component getComponentAndValidateRIs(Component componentDetails, int numberOfRIs,
+ int numberOfRelations, User sdncAdminDetails) throws IOException, Exception {
+
+ RestResponse getResponse = null;
+ Component component = null;
+ if (componentDetails instanceof Resource) {
+ getResponse = ResourceRestUtils.getResource(sdncAdminDetails, componentDetails.getUniqueId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Resource.class);
+ } else if (componentDetails instanceof Service) {
+ getResponse = ServiceRestUtils.getService((componentDetails.getUniqueId()), sdncAdminDetails);
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Service.class);
+ } else if (componentDetails instanceof Product) {
+ getResponse = ProductRestUtils.getProduct(componentDetails.getUniqueId(), sdncAdminDetails.getUserId());
+ component = ResponseParser.parseToObjectUsingMapper(getResponse.getResponse(), Product.class);
+ } else {
+ Assert.fail("Unsupported type of componentDetails - " + componentDetails.getClass().getSimpleName());
+ }
+ ResourceRestUtils.checkSuccess(getResponse);
+ int numberOfActualRIs = component.getComponentInstances() != null ? component.getComponentInstances().size()
+ : 0;
+ int numberOfActualRelations = component.getComponentInstancesRelations() != null
+ ? component.getComponentInstancesRelations().size() : 0;
+ assertEquals("Check number of RIs meet the expected number", numberOfRIs, numberOfActualRIs);
+ assertEquals("Check number of RI relations meet the expected number", numberOfRelations,
+ numberOfActualRelations);
+ verifyReqCap(component);
+
+ return component;
+ }
+
+ public static void getComponentAndValidateRIsAfterChangeLifecycleState(String oldComponentUniqueIdToReplace,
+ Component componentDetails, int numOfRIs, int numOfRelations, User sdncAdminDetails)
+ throws IOException, Exception {
+ updateExpectedReqCapAfterChangeLifecycleState(oldComponentUniqueIdToReplace, componentDetails.getUniqueId());
+ getComponentAndValidateRIs(componentDetails, numOfRIs, numOfRelations, sdncAdminDetails);
+ }
+
+ private static RestResponse createComponentInstance(Component containerDetails, Component compInstOriginDetails,
+ User modifier, ComponentTypeEnum containerComponentTypeEnum, boolean isHighestLevel)
+ throws IOException, Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory
+ .getComponentInstance(compInstOriginDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(
+ resourceInstanceReqDetails, modifier, containerDetails.getUniqueId(), containerComponentTypeEnum);
+ if (createResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED) && isHighestLevel) {
+ // Add RI Capabilities and Requirements to expected MAP -->
+ // expectedVfCapabilities and expectedVfRequirements
+ ComponentInstance componentInstance = ResponseParser
+ .parseToObjectUsingMapper(createResourceInstanceResponse.getResponse(), ComponentInstance.class);
+ addCompInstReqCapToExpected(componentInstance, containerComponentTypeEnum, modifier);
+ }
+ return createResourceInstanceResponse;
+ }
+
+ private static RestResponse deleteComponentInstance(String compInstUniqueId, Component containerDetails,
+ User modifier, ComponentTypeEnum componentTypeEnum, boolean isHighestLevel) throws Exception {
+ RestResponse deleteResourceInstanceResponse = ComponentInstanceRestUtils.deleteComponentInstance(modifier,
+ containerDetails.getUniqueId(), compInstUniqueId, componentTypeEnum);
+ if (deleteResourceInstanceResponse.getErrorCode().equals(BaseRestUtils.STATUS_CODE_DELETE) && isHighestLevel) {
+ deleteCompInstReqCapFromExpected(compInstUniqueId);
+ }
+ return deleteResourceInstanceResponse;
+ }
+
+ public static RestResponse associateComponentInstancesForService(RequirementCapabilityRelDef requirementDef,
+ ComponentReqDetails containerDetails, User user) throws IOException {
+
+ RestResponse associateInstances = ComponentInstanceRestUtils.associateInstances(requirementDef, user,
+ containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(associateInstances);
+ deleteAssociatedFromExpected(requirementDef);
+ return associateInstances;
+ }
+
+ private static void deleteAssociatedFromExpected(RequirementCapabilityRelDef requirementDef) {
+ // removing from requirements
+ RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0);
+ String type = relationship.getRelationship().getType();
+ String fromId = requirementDef.getFromNode();
+ List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
+ RequirementDefinition toDelete = null;
+ if (reqList != null) {
+ for (RequirementDefinition reqDef : reqList) {
+ if (reqDef.getOwnerId().equals(fromId)) {
+ toDelete = reqDef;
+ }
+ }
+ if (toDelete != null) {
+ reqList.remove(toDelete);
+ if (reqList.isEmpty()) {
+ expectedContainerRequirements.remove(type);
+ }
+ removedRequirements.put(toDelete.getCapability() + " " + toDelete.getOwnerId(), toDelete);
+ }
+ }
+ }
+
+ public static void dissociateComponentInstancesForService(RequirementCapabilityRelDef requirementDef,
+ ComponentReqDetails containerDetails, User user) throws IOException {
+
+ RestResponse dissociateInstances = ComponentInstanceRestUtils.dissociateInstances(requirementDef, user,
+ containerDetails.getUniqueId(), ComponentTypeEnum.SERVICE);
+ ResourceRestUtils.checkSuccess(dissociateInstances);
+ addDissociatedToExpected(requirementDef);
+ }
+
+ private static void addDissociatedToExpected(RequirementCapabilityRelDef requirementDef) {
+ // adding to requirements
+ RequirementAndRelationshipPair relationship = requirementDef.getRelationships().get(0);
+ String type = relationship.getRelationship().getType();
+ String fromId = requirementDef.getFromNode();
+ String key = type + " " + fromId;
+ RequirementDefinition requirementDefinition = removedRequirements.get(key);
+ if (requirementDefinition != null) {
+ List<RequirementDefinition> reqList = expectedContainerRequirements.get(type);
+ if (reqList == null) {
+ reqList = new ArrayList<>();
+ expectedContainerRequirements.put(type, reqList);
+ }
+ reqList.add(requirementDefinition);
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
new file mode 100644
index 0000000000..e5928b327f
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java
@@ -0,0 +1,267 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTypesDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaPropertiesNodeTemplatesDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+public class ToscaParserUtils {
+
+ private static Logger log = LoggerFactory.getLogger(ToscaParserUtils.class.getName());
+
+ public static Map<?, ?> getToscaYamlMap(String csarUUID, String fileLocation) throws Exception {
+ String csarPayload = CsarValidationUtils.getCsarPayload(csarUUID, fileLocation);
+ if (csarPayload != null) {
+ Yaml yaml = new Yaml();
+ Map<?, ?> map = (Map<?, ?>) yaml.load(csarPayload);
+ return map;
+ }
+ return null;
+ }
+
+ public static ToscaDefinition getToscaDefinitionObjectByCsarUuid(String csarUUID) throws Exception {
+
+ String TOSCAMetaLocation = "TOSCA-Metadata/TOSCA.meta";
+ Map<?, ?> map = getToscaYamlMap(csarUUID, TOSCAMetaLocation);
+ assertNotNull("Tosca Entry-Definitions is null", map);
+ if (map != null) {
+ String definitionYamlLocation = (String) map.get("Entry-Definitions");
+ Map<?, ?> toscaMap = getToscaYamlMap(csarUUID, definitionYamlLocation);
+ assertNotNull("Tosca definition is null", toscaMap);
+ if (toscaMap != null) {
+ ToscaDefinition toscaDefinition = new ToscaDefinition();
+ Set<?> keySet = toscaMap.keySet();
+ for (Object key : keySet) {
+ ToscaKeysEnum toscaKey = ToscaKeysEnum.findToscaKey((String) key);
+ switch (toscaKey) {
+ case TOSCA_DEFINITION_VERSION:
+ getToscaDefinitionVersion(toscaMap, toscaDefinition);
+ break;
+ case NODE_TYPES:
+ getToscaNodeTypes(toscaMap, toscaDefinition);
+ break;
+ case TOPOLOGY_TEMPLATE:
+ getToscaTopologyTemplate(toscaMap, toscaDefinition);
+ break;
+ case IMPORTS:
+ // toscaMap.get("imports");
+ break;
+ default:
+ break;
+ }
+ }
+ return toscaDefinition;
+ }
+ }
+ return null;
+
+ }
+
+ public static void getToscaDefinitionVersion(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
+ if (toscaMap.get("tosca_definitions_version") != null) {
+ toscaDefinition.setToscaDefinitionVersion((String) toscaMap.get("tosca_definitions_version"));
+ }
+ }
+
+ // spec 90 page
+ public static void getToscaNodeTypes(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
+ @SuppressWarnings("unchecked")
+ Map<String, Map<String, String>> nodeTypes = (Map<String, Map<String, String>>) toscaMap.get("node_types");
+ List<ToscaNodeTypesDefinition> listToscaNodeTypes = new ArrayList<>();
+ if (nodeTypes != null) {
+ for (Map.Entry<String, Map<String, String>> entry : nodeTypes.entrySet()) {
+ ToscaNodeTypesDefinition toscaNodeTypes = new ToscaNodeTypesDefinition();
+ String toscaNodeName = entry.getKey();
+ toscaNodeTypes.setName(toscaNodeName);
+
+ Map<String, String> toscaNodeType = entry.getValue();
+ if (toscaNodeType != null) {
+ Set<Entry<String, String>> entrySet = toscaNodeType.entrySet();
+ if (entrySet != null) {
+ // boolean found = false;
+ for (Entry<String, String> toscaNodeTypeMap : entrySet) {
+ String key = toscaNodeTypeMap.getKey();
+ if (key.equals("derived_from")) {
+ String derivedFrom = toscaNodeTypeMap.getValue();
+ toscaNodeTypes.setDerivedFrom(derivedFrom);
+ // found = true;
+ break;
+ } else {
+ continue;
+ }
+
+ }
+ // if (found == false) {
+ // System.out.println("Tosca file not valid,
+ // derived_from not found");
+ // }
+ }
+
+ }
+ listToscaNodeTypes.add(toscaNodeTypes);
+ }
+ toscaDefinition.setToscaNodeTypes(listToscaNodeTypes);
+ }
+ }
+
+ public static void getToscaTopologyTemplate(Map<?, ?> toscaMap, ToscaDefinition toscaDefinition) {
+ ToscaTopologyTemplateDefinition toscaTopologyTemplate = new ToscaTopologyTemplateDefinition();
+ @SuppressWarnings("unchecked")
+ Map<String, Map<String, Object>> topologyTemplateMap = (Map<String, Map<String, Object>>) toscaMap
+ .get("topology_template");
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates = new ArrayList<>();
+
+ if (topologyTemplateMap != null) {
+ getToscaNodeTemplates(topologyTemplateMap, listToscaNodeTemplates);
+ }
+ toscaTopologyTemplate.setToscaNodeTemplatesTopologyTemplateDefinition(listToscaNodeTemplates);
+ toscaDefinition.setToscaTopologyTemplate(toscaTopologyTemplate);
+ }
+
+ public static void getToscaNodeTemplates(Map<String, Map<String, Object>> topologyTemplateMap,
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> listToscaNodeTemplates) {
+ Map<String, Object> nodeTemplatesMap = topologyTemplateMap.get("node_templates");
+ if (nodeTemplatesMap != null) {
+
+ for (Entry<String, Object> nodeTemplates : nodeTemplatesMap.entrySet()) {
+ ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates = new ToscaNodeTemplatesTopologyTemplateDefinition();
+ getToscaNodeTemplatesName(nodeTemplates, toscaNodeTemplates);
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> node = (Map<String, Object>) nodeTemplates.getValue();
+ getNodeTemplatesType(toscaNodeTemplates, node);
+ getToscaNodeTemplateProperties(toscaNodeTemplates, node);
+ getToscaNodeTemplateRequirements(toscaNodeTemplates, node);
+ listToscaNodeTemplates.add(toscaNodeTemplates);
+ }
+ }
+ }
+
+ public static void getToscaNodeTemplateRequirements(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
+ Map<String, Object> node) {
+ List<ToscaRequirementsNodeTemplatesDefinition> toscaRequirements = new ArrayList<>();
+ if (node.get("requirements") != null) {
+ @SuppressWarnings("unchecked")
+ List<Map<String, Object>> requirementList = (List<Map<String, Object>>) node.get("requirements");
+ for (int i = 0; i < requirementList.size(); i++) {
+ for (Map.Entry<String, Object> requirement : requirementList.get(i).entrySet()) {
+ ToscaRequirementsNodeTemplatesDefinition toscaRequirement = new ToscaRequirementsNodeTemplatesDefinition();
+ if (requirement.getKey() != null) {
+ String requirementName = requirement.getKey();
+ toscaRequirement.setName(requirementName);
+ } else {
+ log.debug("Tosca file not valid, requirements should contain name");
+ }
+
+ @SuppressWarnings("unchecked")
+ Map<String, String> requirementMap = (Map<String, String>) requirement.getValue();
+ Set<Entry<String, String>> entrySet = requirementMap.entrySet();
+ if (entrySet != null) {
+ for (Entry<String, String> requirementField : entrySet) {
+ String key = requirementField.getKey();
+ switch (key) {
+ case "capability":
+ if (requirementMap.get(key) != null) {
+ String capability = (String) requirementMap.get(key);
+ toscaRequirement.setCapability(capability);
+ break;
+ } else {
+ continue;
+ }
+ case "node":
+ if (requirementMap.get(key) != null) {
+ String requirementNode = (String) requirementMap.get(key);
+ toscaRequirement.setNode(requirementNode);
+ break;
+ } else {
+ continue;
+ }
+ case "relationship":
+ if (requirementMap.get(key) != null) {
+ String relationship = (String) requirementMap.get(key);
+ toscaRequirement.setRelationship(relationship);
+ break;
+ } else {
+ continue;
+ }
+ default:
+ break;
+ }
+ }
+ }
+ toscaRequirements.add(toscaRequirement);
+ }
+ }
+ }
+ toscaNodeTemplates.setRequirements(toscaRequirements);
+ }
+
+ public static void getToscaNodeTemplateProperties(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
+ Map<String, Object> node) {
+ List<ToscaPropertiesNodeTemplatesDefinition> listToscaProperties = new ArrayList<>();
+ if (node.get("properties") != null) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> properties = (Map<String, Object>) node.get("properties");
+ for (Map.Entry<String, Object> property : properties.entrySet()) {
+ ToscaPropertiesNodeTemplatesDefinition toscaProperty = new ToscaPropertiesNodeTemplatesDefinition();
+ String propertyName = property.getKey();
+ Object propertyValue = property.getValue();
+ toscaProperty.setName(propertyName);
+ toscaProperty.setValue(propertyValue);
+ listToscaProperties.add(toscaProperty);
+ }
+ }
+ toscaNodeTemplates.setProperties(listToscaProperties);
+ }
+
+ protected static void getNodeTemplatesType(ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates,
+ Map<String, Object> node) {
+ if (node.get("type") != null) {
+ String type = (String) node.get("type");
+ toscaNodeTemplates.setType(type);
+ } else {
+ log.debug("Tosca file not valid, nodeTemplate should contain type");
+ }
+ }
+
+ protected static void getToscaNodeTemplatesName(Entry<String, Object> nodeTemplates,
+ ToscaNodeTemplatesTopologyTemplateDefinition toscaNodeTemplates) {
+ String name = nodeTemplates.getKey();
+ toscaNodeTemplates.setName(name);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
new file mode 100644
index 0000000000..962f140dbd
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/Utils.java
@@ -0,0 +1,233 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.log4j.Logger;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.common.api.ToscaNodeTypeInfo;
+import org.openecomp.sdc.common.api.YamlConstants;
+import org.yaml.snakeyaml.Yaml;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public final class Utils {
+
+ Gson gson = new Gson();
+
+ static Logger logger = Logger.getLogger(Utils.class.getName());
+
+ String contentTypeHeaderData = "application/json";
+ String acceptHeaderDate = "application/json";
+
+ public Utils() {
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public ToscaNodeTypeInfo parseToscaNodeYaml(String fileContent) {
+
+ ToscaNodeTypeInfo result = new ToscaNodeTypeInfo();
+ Object templateVersion = null;
+ Object templateName = null;
+
+ if (fileContent != null) {
+ Yaml yaml = new Yaml();
+
+ Map<String, Object> yamlObject = (Map<String, Object>) yaml.load(fileContent);
+
+ templateVersion = yamlObject.get(YamlConstants.TEMPLATE_VERSION);
+ if (templateVersion != null) {
+ result.setTemplateVersion(templateVersion.toString());
+ }
+ templateName = yamlObject.get(YamlConstants.TEMPLATE_NAME);
+ if (templateName != null) {
+ result.setTemplateName(templateName.toString());
+ }
+ Object nodeTypes = yamlObject.get(YamlConstants.NODE_TYPES);
+
+ if (nodeTypes != null) {
+ Map<String, Object> nodeTypesMap = (Map<String, Object>) nodeTypes;
+ for (Entry<String, Object> entry : nodeTypesMap.entrySet()) {
+
+ String nodeName = entry.getKey();
+ if (nodeName != null) {
+ result.setNodeName(nodeName);
+ }
+
+ break;
+
+ }
+ }
+
+ }
+
+ return result;
+ }
+
+ public static String getJsonObjectValueByKey(String metadata, String key) {
+ JsonElement jelement = new JsonParser().parse(metadata);
+
+ JsonObject jobject = jelement.getAsJsonObject();
+ Object obj = jobject.get(key);
+ if (obj == null) {
+ return null;
+ } else {
+ String value;
+ value = (String) jobject.get(key).getAsString();
+ return value;
+ }
+ }
+
+ public static Config getConfig() throws FileNotFoundException {
+ Config config = Config.instance();
+ return config;
+ }
+
+ public static void compareArrayLists(List<String> actualArraylList, List<String> expectedArrayList,
+ String message) {
+
+ ArrayList<String> actual = new ArrayList<String>(actualArraylList);
+ ArrayList<String> expected = new ArrayList<String>(expectedArrayList);
+ assertEquals(message + " count got by rest API not match to " + message + " expected count", expected.size(),
+ actual.size());
+ actual.removeAll(expected);
+ assertEquals(message + " content got by rest API not match to " + message + " expected content", 0,
+ actual.size());
+ }
+
+ public static Object parseYamlConfig(String pattern) throws FileNotFoundException {
+
+ Yaml yaml = new Yaml();
+ Config config = getConfig();
+ String configurationFile = config.getConfigurationFile();
+ File file = new File(configurationFile);
+ // File file = new
+ // File("../catalog-be/src/main/resources/config/configuration.yaml");
+ InputStream inputStream = new FileInputStream(file);
+ Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
+ Object patternMap = (Object) map.get(pattern);
+
+ return patternMap;
+ }
+
+ public static String getDepArtLabelFromConfig(ArtifactTypeEnum artifactTypeEnum) throws FileNotFoundException {
+
+ @SuppressWarnings("unchecked")
+ Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) parseYamlConfig(
+ "deploymentResourceArtifacts");
+ for (Map.Entry<String, Object> iter : mapOfDepResArtTypesObjects.entrySet()) {
+ if (iter.getValue().toString().contains(artifactTypeEnum.getType())) {
+ return iter.getKey().toLowerCase();
+ }
+ }
+
+ return "defaultLabelName";
+ }
+
+ public static String multipleChar(String ch, int repeat) {
+ return StringUtils.repeat(ch, repeat);
+ }
+
+ public static List<String> getListOfDepResArtLabels(Boolean isLowerCase) throws FileNotFoundException {
+
+ List<String> listOfResDepArtTypesFromConfig = new ArrayList<String>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) parseYamlConfig(
+ "deploymentResourceArtifacts");
+ if (resourceDeploymentArtifacts != null) {
+
+ if (isLowerCase) {
+ for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
+ listOfResDepArtTypesFromConfig.add(iter.getKey().toLowerCase());
+ }
+ } else {
+
+ for (Map.Entry<String, Object> iter : resourceDeploymentArtifacts.entrySet()) {
+ listOfResDepArtTypesFromConfig.add(iter.getKey());
+ }
+ }
+ }
+ return listOfResDepArtTypesFromConfig;
+ }
+
+ public static List<String> getListOfToscaArtLabels(Boolean isLowerCase) throws FileNotFoundException {
+
+ List<String> listOfToscaArtTypesFromConfig = new ArrayList<String>();
+ @SuppressWarnings("unchecked")
+ Map<String, Object> toscaArtifacts = (Map<String, Object>) parseYamlConfig("toscaArtifacts");
+ if (toscaArtifacts != null) {
+
+ if (isLowerCase) {
+ for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
+ listOfToscaArtTypesFromConfig.add(iter.getKey().toLowerCase());
+ }
+ } else {
+ for (Map.Entry<String, Object> iter : toscaArtifacts.entrySet()) {
+ listOfToscaArtTypesFromConfig.add(iter.getKey());
+ }
+ }
+ }
+ return listOfToscaArtTypesFromConfig;
+ }
+
+ public static List<String> getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException {
+ List<String> listResDepArtTypesFromConfig = new ArrayList<String>();
+ List<String> listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false);
+ assertNotNull("deployment artifact types list is null", listOfResDepArtLabelsFromConfig);
+ Object parseYamlConfig = Utils.parseYamlConfig("deploymentResourceArtifacts");
+ Map<String, Object> mapOfDepResArtTypesObjects = (Map<String, Object>) Utils
+ .parseYamlConfig("deploymentResourceArtifacts");
+
+ // assertNotNull("deployment artifact types list is null",
+ // mapOfDepResArtTypesObjects);
+ if (listOfResDepArtLabelsFromConfig != null) {
+ for (String resDepArtType : listOfResDepArtLabelsFromConfig) {
+ Object object = mapOfDepResArtTypesObjects.get(resDepArtType);
+ if (object instanceof Map<?, ?>) {
+ Map<String, Object> map = (Map<String, Object>) object;
+ listResDepArtTypesFromConfig.add((String) map.get("type"));
+ } else {
+ assertTrue("return object does not instance of map", false);
+ }
+ }
+ }
+ return listResDepArtTypesFromConfig;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
new file mode 100644
index 0000000000..51b68d4d56
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils.java
@@ -0,0 +1,213 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.cassandra;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.TableMetadata;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.querybuilder.Select.Where;
+
+public final class CassandraUtils {
+ private static Logger logger = LoggerFactory.getLogger(CassandraUtils.class.getName());
+
+ protected static Cluster cluster = null;
+ protected static Session session;
+
+ protected static void initConnection(String keyspace) throws FileNotFoundException {
+
+ String cassandraHost = Utils.getConfig().getCassandraHost();
+ Boolean cassandraAuthenticate = Utils.getConfig().getCassandraAuthenticate();
+ String cassandraUsername = Utils.getConfig().getCassandraUsername();
+ String cassandraPassword = Utils.getConfig().getCassandraPassword();
+ Boolean cassandraSsl = Utils.getConfig().getCassandraSsl();
+ String cassandraTruststorePath = Utils.getConfig().getCassandraTruststorePath();
+ String cassandraTruststorePassword = Utils.getConfig().getCassandraTruststorePassword();
+ /*
+ * String cassandraAuditKeySpace=
+ * Utils.getConfig().getCassandraAuditKeySpace(); String
+ * cassandraArtifactKeySpace=
+ * Utils.getConfig().getCassandraArtifactKeySpace();
+ */
+
+ Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost);
+ if (cassandraAuthenticate) {
+ // authantication
+ clusterBuilder.withCredentials(cassandraUsername, cassandraPassword);
+ }
+
+ if (cassandraSsl) {
+ // ssl
+ System.setProperty("javax.net.ssl.trustStore", cassandraTruststorePath);
+ System.setProperty("javax.net.ssl.trustStorePassword", cassandraTruststorePassword);
+ clusterBuilder.withSSL();
+ }
+
+ cluster = clusterBuilder.build();
+ session = cluster.connect(keyspace);
+
+ }
+
+ public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
+
+ if (session == null || session.isClosed()) {
+ initConnection(keyspace);
+ }
+
+ try {
+
+ if (session != null) {
+ session.execute(QueryBuilder.truncate(keyspace, tableName));
+ logger.debug("The table {}. {} was cleaned", keyspace, tableName);
+ } else {
+ throw new RuntimeException("Keyspace " + keyspace + " not connected");
+ }
+ } finally {
+ // if (cluster != null) {
+ // cluster.close();
+ // }
+ }
+ }
+
+ public static void close() {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+
+ public static void truncateAllKeyspaces() throws FileNotFoundException {
+ // truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
+ truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
+ }
+
+ public static void truncateAllTables(String keyspace) throws FileNotFoundException {
+
+ if (session == null || session.isClosed()) {
+ initConnection(keyspace);
+ }
+ try {
+
+ if (session != null) {
+ Metadata metadata = cluster.getMetadata();
+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
+ if (keyspaceMetadata != null) {
+ Collection<TableMetadata> tables = keyspaceMetadata.getTables();
+ tables.forEach(table -> {
+ session.execute(QueryBuilder.truncate(table));
+ logger.debug("Table trunceted - {}", table.getName());
+ });
+ }
+ } else {
+ throw new RuntimeException("Keyspace " + keyspace + " not connected");
+ }
+
+ } finally {
+ // if (cluster != null) {
+ // cluster.close();
+ // }
+ }
+ }
+
+ public static List<Row> fetchFromTable(String keyspace, String tableName,
+ List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
+
+ List<Pair<String, String>> fieldsConverted = new ArrayList<>();
+
+ fields.forEach(pair -> {
+ Pair<String, String> newPair = new Pair(pair.getValue0().getDisplayName(), pair.getValue1());
+ fieldsConverted.add(newPair);
+ });
+
+ return fetchFromTableQuery(keyspace, tableName, fieldsConverted);
+ }
+
+ public static List<Row> fetchFromTableQuery(String keyspace, String tableName, List<Pair<String, String>> fields)
+ throws FileNotFoundException {
+
+ if (session == null || session.isClosed()) {
+ initConnection(keyspace);
+ }
+ try {
+
+ if (session != null) {
+ Select select = QueryBuilder.select().all().from(keyspace, tableName);
+ if (fields != null) {
+ // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
+ // fields.entrySet();
+ // fields.
+ boolean multiple = (fields.size() > 1) ? true : false;
+ Where where = null;
+ int size = 0;
+
+ for (Pair<String, String> pair : fields) {
+ ++size;
+ if (size == 1) {
+ where = select.where(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
+ } else {
+ where.and(QueryBuilder.eq(pair.getValue0(), pair.getValue1()));
+ }
+ }
+ if (multiple) {
+ select.allowFiltering();
+ }
+
+ }
+
+ List<Row> rows = session.execute(select).all();
+ for (Row row : rows) {
+ logger.debug("{}", row);
+ }
+ return rows;
+ }
+ } finally {
+ // if (cluster != null) {
+ // cluster.close();
+ // }
+ }
+ return null;
+ }
+ //
+ // public static void main(String[] args) throws FileNotFoundException {
+ // Map<AuditingFieldsKeysEnum, String> map = new HashMap<>();
+ // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access");
+ // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200");
+ // // CassandraUtils.truncateTable("sdcArtifact", "resources");
+ //// CassandraUtils.truncateAllTables("sdcAudit");
+ // CassandraUtils.fetchFromTable("sdcAudit", "useraccessevent", map );
+ // }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
new file mode 100644
index 0000000000..414ca2334e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/cassandra/CassandraUtils2.java
@@ -0,0 +1,172 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.cassandra;
+
+import java.io.FileNotFoundException;
+import java.util.Collection;
+import java.util.List;
+
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.TableMetadata;
+import com.datastax.driver.core.querybuilder.QueryBuilder;
+import com.datastax.driver.core.querybuilder.Select;
+import com.datastax.driver.core.querybuilder.Select.Where;
+
+public final class CassandraUtils2 {
+ private static Logger logger = LoggerFactory.getLogger(CassandraUtils2.class.getName());
+
+ public static void truncateTable(String keyspace, String tableName) throws FileNotFoundException {
+
+ String cassandraHost = Utils.getConfig().getCassandraHost();
+
+ Cluster cluster = null;
+ Session session;
+
+ try {
+ Cluster.Builder clusterBuilder = Cluster.builder().addContactPoint(cassandraHost);
+ // authantication
+ // clusterBuilder.withCredentials(username,password);
+ // ssl
+ // System.setProperty("javax.net.ssl.trustStore",truststorePath);
+ // System.setProperty("javax.net.ssl.trustStorePassword",truststorePassword);
+ // clusterBuilder.withSSL();
+ cluster = clusterBuilder.build();
+ session = cluster.connect(keyspace);
+ if (session != null) {
+ session.execute(QueryBuilder.truncate(keyspace, tableName));
+ logger.debug("The table {}. {} was cleaned", keyspace, tableName);
+ } else {
+ throw new RuntimeException("Keyspace " + keyspace + " not connected");
+ }
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
+
+ public static void truncateAllKeyspaces() throws FileNotFoundException {
+ truncateAllTables(AuditingTypesConstants.ARTIFACT_KEYSPACE);
+ truncateAllTables(AuditingTypesConstants.AUDIT_KEYSPACE);
+ }
+
+ public static void truncateAllTables(String keyspace) throws FileNotFoundException {
+ String cassandraHost = Utils.getConfig().getCassandraHost();
+
+ Cluster cluster = null;
+ Session session;
+
+ try {
+ cluster = Cluster.builder().addContactPoint(cassandraHost).build();
+ session = cluster.connect(keyspace);
+ if (session != null) {
+ Metadata metadata = cluster.getMetadata();
+ KeyspaceMetadata keyspaceMetadata = metadata.getKeyspace(keyspace);
+ if (keyspaceMetadata != null) {
+ Collection<TableMetadata> tables = keyspaceMetadata.getTables();
+ tables.forEach(table -> {
+ session.execute(QueryBuilder.truncate(table));
+ logger.debug("Table trunceted - {}", table.getName());
+ });
+ }
+ } else {
+ throw new RuntimeException("Keyspace " + keyspace + " not connected");
+ }
+
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ }
+
+ public static List<Row> fetchFromTable(String keyspace, String tableName,
+ List<Pair<AuditingFieldsKeysEnum, String>> fields) throws FileNotFoundException {
+
+ // List<Pair<AuditingFieldsKeysEnum, String>>
+ // Map<AuditingFieldsKeysEnum, String>
+
+ Cluster cluster = null;
+ Session session;
+ String cassandraHost = Utils.getConfig().getCassandraHost();
+
+ try {
+ cluster = Cluster.builder().addContactPoint(cassandraHost).build();
+ session = cluster.connect(keyspace);
+ if (session != null) {
+ Select select = QueryBuilder.select().all().from(keyspace, tableName);
+ if (fields != null) {
+ // Set<Entry<AuditingFieldsKeysEnum, String>> entrySet =
+ // fields.entrySet();
+ // fields.
+ boolean multiple = (fields.size() > 1) ? true : false;
+ Where where = null;
+ int size = 0;
+
+ for (Pair<AuditingFieldsKeysEnum, String> pair : fields) {
+ ++size;
+ if (size == 1) {
+ where = select.where(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1()));
+ } else {
+ where.and(QueryBuilder.eq(pair.getValue0().getDisplayName(), pair.getValue1()));
+ }
+ }
+ if (multiple) {
+ select.allowFiltering();
+ }
+
+ }
+
+ List<Row> rows = session.execute(select).all();
+ for (Row row : rows) {
+ logger.debug("{}", row);
+ }
+ return rows;
+ }
+ } finally {
+ if (cluster != null) {
+ cluster.close();
+ }
+ }
+ return null;
+ }
+ //
+ // public static void main(String[] args) throws FileNotFoundException {
+ // Map<AuditingFieldsKeysEnum, String> map = new HashMap<>();
+ // map.put(AuditingFieldsKeysEnum.AUDIT_ACTION, "Access");
+ // map.put(AuditingFieldsKeysEnum.AUDIT_STATUS, "200");
+ // // CassandraUtils.truncateTable("sdcArtifact", "resources");
+ //// CassandraUtils.truncateAllTables("sdcAudit");
+ // CassandraUtils.fetchFromTable("sdcAudit", "useraccessevent", map );
+ // }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
new file mode 100644
index 0000000000..0456b2c121
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java
@@ -0,0 +1,627 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.tuple.Pair;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.PropertyRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
+import com.google.gson.Gson;
+
+import fj.data.Either;
+
+public final class AtomicOperationUtils {
+
+ private AtomicOperationUtils() {
+ throw new UnsupportedOperationException();
+ }
+
+ // *********** RESOURCE ****************
+ /**
+ * Import a vfc From tosca file
+ *
+ * @param filePath
+ * @param fileName
+ * @return
+ * @throws IOException
+ * @throws JSONException
+ */
+ public static Either<Resource, RestResponse> importResource(String filePath, String fileName) {
+ try {
+ User designer = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ ImportReqDetails importReqDetails = ElementFactory.getDefaultImportResource("ciTmpVFC");
+ importReqDetails = ImportUtils.getImportResourceDetailsByPathAndName(importReqDetails, filePath, fileName);
+ RestResponse importResourceResponse = ResourceRestUtils.createImportResource(importReqDetails, designer, null);
+ return buildResourceFromResponse(importResourceResponse);
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+ public static Either<Resource, RestResponse> createResourceByType(ResourceTypeEnum resourceType, UserRoleEnum userRole, Boolean validateState) {
+ try {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByType(resourceType, defaultUser);
+ RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
+
+ if (validateState) {
+ assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ return Either.left(resourceResponseObject);
+ }
+ return Either.right(resourceResp);
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+ public static Either<Resource, RestResponse> createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
+ throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, normativeTypes, resourceCategory, defaultUser);
+ RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
+
+ if (validateState) {
+ assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ // Resource resourceResponseObject = ResponseParser
+ // .convertResourceResponseToJavaObject(resourceResp.getResponse());
+ Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
+ return Either.left(resourceResponseObject);
+ }
+ return Either.right(resourceResp);
+ }
+
+ public static Either<Resource, RestResponse> createResourcesByCustomNormativeTypeAndCatregory(ResourceTypeEnum resourceType, Resource resourceNormativeType, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState)
+ throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(resourceType, resourceNormativeType, resourceCategory, defaultUser);
+ RestResponse resourceResp = ResourceRestUtils.createResource(defaultResource, defaultUser);
+
+ if (validateState) {
+ assertTrue("actual result: " + resourceResp.getResponseMessage(), resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ // Resource resourceResponseObject = ResponseParser
+ // .convertResourceResponseToJavaObject(resourceResp.getResponse());
+ Resource resourceResponseObject = ResponseParser.parseToObjectUsingMapper(resourceResp.getResponse(), Resource.class);
+ return Either.left(resourceResponseObject);
+ }
+ return Either.right(resourceResp);
+ }
+
+ // *********** SERVICE ****************
+
+ public static Either<Service, RestResponse> createDefaultService(UserRoleEnum userRole, Boolean validateState) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(defaultUser);
+ RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
+
+ if (validateState) {
+ assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
+ return Either.left(serviceResponseObject);
+ }
+ return Either.right(createServiceResp);
+ }
+
+ public static Either<Service, RestResponse> createServiceByCategory(ServiceCategoriesEnum category, UserRoleEnum userRole, Boolean validateState) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(category, defaultUser);
+ RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser);
+
+ if (validateState) {
+ assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse());
+ return Either.left(serviceResponseObject);
+ }
+ return Either.right(createServiceResp);
+ }
+
+ // *********** PRODUCT ****************
+
+ public static Either<Product, RestResponse> createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ProductReqDetails defaultProduct = ElementFactory.getDefaultProduct();
+ RestResponse createProductResp = ProductRestUtils.createProduct(defaultProduct, defaultUser);
+
+ if (validateState) {
+ assertTrue(createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (createProductResp.getErrorCode() == ProductRestUtils.STATUS_CODE_CREATED) {
+ Product productResponseJavaObject = ResponseParser.convertProductResponseToJavaObject(createProductResp.getResponse());
+ return Either.left(productResponseJavaObject);
+ }
+ return Either.right(createProductResp);
+ }
+
+ // *********** LIFECYCLE ***************
+
+ public static Pair<Component, RestResponse> changeComponentState(Component component, UserRoleEnum userRole, LifeCycleStatesEnum targetState, Boolean validateState) throws Exception {
+
+ Boolean isValidationFailed = false;
+ RestResponse lifeCycleStatesResponse = null;
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+
+ LifeCycleStatesEnum curentCompState = LifeCycleStatesEnum.findByCompState(component.getLifecycleState().toString());
+
+ if (curentCompState == targetState) {
+ return Pair.of(component, null);
+ }
+ // List<LifeCycleStatesEnum> lifeCycleStatesEnumOrigList = new
+ // ArrayList<LifeCycleStatesEnum>(EnumSet.allOf(LifeCycleStatesEnum.class));
+
+ ArrayList<String> lifeCycleStatesEnumList = new ArrayList<String>();
+ if (curentCompState.equals(LifeCycleStatesEnum.CHECKIN) && targetState.equals(LifeCycleStatesEnum.CHECKOUT)) {
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
+ } else {
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKOUT.toString());
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CHECKIN.toString());
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFICATIONREQUEST.toString());
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.STARTCERTIFICATION.toString());
+ lifeCycleStatesEnumList.add(LifeCycleStatesEnum.CERTIFY.toString());
+ }
+ for (int i = 0; i < lifeCycleStatesEnumList.size(); i++) {
+ if (lifeCycleStatesEnumList.get(i).equals(curentCompState.name())) {
+ int a;
+ a = (i == lifeCycleStatesEnumList.size() - 1) ? 0 : i + 1;
+
+ for (int n = a; n < lifeCycleStatesEnumList.size(); n++) {
+ if (lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.STARTCERTIFICATION.name()) || lifeCycleStatesEnumList.get(n).equals(LifeCycleStatesEnum.CERTIFY.name())) {
+ defaultUser = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ } else
+ defaultUser = ElementFactory.getDefaultUser(userRole);
+
+ lifeCycleStatesResponse = LifecycleRestUtils.changeComponentState(component, defaultUser, LifeCycleStatesEnum.findByState(lifeCycleStatesEnumList.get(n)));
+ if (lifeCycleStatesResponse.getErrorCode() != LifecycleRestUtils.STATUS_CODE_SUCCESS)
+ isValidationFailed = true;
+ if (lifeCycleStatesEnumList.get(n).equals(targetState.toString()) || isValidationFailed == true) {
+ break;
+ }
+ }
+ }
+
+ }
+ component = getCompoenntObject(component, userRole);
+ Component componentJavaObject = convertReposnseToComponentObject(component, lifeCycleStatesResponse);
+
+ if (validateState == true && isValidationFailed == true) {
+ assertTrue("change state failed" + lifeCycleStatesResponse.getResponse(), false);
+
+ return Pair.of(componentJavaObject, lifeCycleStatesResponse);
+ }
+
+ if (isValidationFailed == true) {
+ return Pair.of(componentJavaObject, lifeCycleStatesResponse);
+ }
+
+ return Pair.of(componentJavaObject, lifeCycleStatesResponse);
+ }
+
+ public static RestResponse distributeService(Component component, Boolean validateState) throws Exception {
+
+ Service service = (Service) component;
+
+ User opsUser = ElementFactory.getDefaultUser(UserRoleEnum.OPS);
+ User governotUser = ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR);
+
+ ServiceReqDetails serviceDetails = new ServiceReqDetails(service);
+ RestResponse distributionService = null;
+
+ RestResponse approveDistribution = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, governotUser, "approveService", DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ if (approveDistribution.getErrorCode() == 200) {
+ distributionService = LifecycleRestUtils.changeDistributionStatus(serviceDetails, null, opsUser, "approveService", DistributionStatusEnum.DISTRIBUTED);
+ }
+
+ if (validateState) {
+ assertTrue(approveDistribution.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+ assertTrue(distributionService.getErrorCode() == ProductRestUtils.STATUS_CODE_SUCCESS);
+ return distributionService;
+ }
+
+ return distributionService;
+
+ }
+
+ // *********** ARTIFACTS *****************
+
+ public static Either<ArtifactDefinition, RestResponse> uploadArtifactByType(ArtifactTypeEnum artifactType, Component component, UserRoleEnum userRole, Boolean deploymentTrue, Boolean validateState) throws Exception {
+
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(null, artifactType, deploymentTrue);
+ if (deploymentTrue == false)
+ artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.INFORMATIONAL.getType());
+ RestResponse uploadArtifactResp = ArtifactRestUtils.uploadArtifact(artifactDetails, component, defaultUser);
+
+ if (validateState) {
+ assertTrue("artifact upload failed: " + artifactDetails.getArtifactName(), uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ if (uploadArtifactResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
+ ArtifactDefinition artifactJavaObject = ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactResp.getResponse());
+ return Either.left(artifactJavaObject);
+ }
+ return Either.right(uploadArtifactResp);
+ }
+
+ // *********** CONTAINERS *****************
+ /**
+ * Adds Component instance to Component
+ *
+ * @param compInstParent
+ * @param compContainer
+ * @return
+ */
+ public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer) {
+ return addComponentInstanceToComponentContainer(compInstParent, compContainer, UserRoleEnum.DESIGNER, false);
+ }
+
+ public static Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer(Component compInstParent, Component compContainer, UserRoleEnum userRole, Boolean validateState) {
+ try {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ComponentInstanceReqDetails componentInstanceDetails = ElementFactory.getComponentInstance(compInstParent);
+ RestResponse createComponentInstance = ComponentInstanceRestUtils.createComponentInstance(componentInstanceDetails, defaultUser, compContainer);
+
+ if (validateState) {
+ assertTrue(createComponentInstance.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (createComponentInstance.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ ComponentInstance componentInstance = ResponseParser.convertComponentInstanceResponseToJavaObject(createComponentInstance.getResponse());
+ return Either.left(componentInstance);
+ }
+ return Either.right(createComponentInstance);
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+ public static Resource getResourceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ // User defaultUser = ElementFactory.getDefaultUser(userRole);
+ RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
+ Resource container = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ return container;
+ }
+
+ public static Service getServiceObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
+ Service container = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
+ return container;
+ }
+
+ public static Product getProductObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
+ Product container = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
+ return container;
+ }
+
+ public static Component getCompoenntObject(Component containerDetails, UserRoleEnum userRole) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+
+ switch (containerDetails.getComponentType()) {
+ case RESOURCE:
+ RestResponse restResponse = ResourceRestUtils.getResource(containerDetails.getUniqueId());
+ containerDetails = ResponseParser.convertResourceResponseToJavaObject(restResponse.getResponse());
+ break;
+ case SERVICE:
+ RestResponse serviceResponse = ServiceRestUtils.getService(containerDetails.getUniqueId(), defaultUser);
+ containerDetails = ResponseParser.convertServiceResponseToJavaObject(serviceResponse.getResponse());
+ break;
+ case PRODUCT:
+ RestResponse productRest = ProductRestUtils.getProduct(containerDetails.getUniqueId(), defaultUser.getUserId());
+ containerDetails = ResponseParser.convertProductResponseToJavaObject(productRest.getResponse());
+ break;
+ default:
+ break;
+ }
+ return containerDetails;
+ }
+
+ public static Component convertReposnseToComponentObject(Component containerDetails, RestResponse restresponse) throws Exception {
+
+ switch (containerDetails.getComponentType()) {
+ case RESOURCE:
+ containerDetails = ResponseParser.convertResourceResponseToJavaObject(restresponse.getResponse());
+ break;
+ case SERVICE:
+ containerDetails = ResponseParser.convertServiceResponseToJavaObject(restresponse.getResponse());
+ break;
+ case PRODUCT:
+ containerDetails = ResponseParser.convertProductResponseToJavaObject(restresponse.getResponse());
+ break;
+ default:
+ break;
+ }
+ return containerDetails;
+ }
+
+ public static RestResponse associate2ResourceInstances(Component containerDetails, ComponentInstance fromNode, ComponentInstance toNode, String assocType, UserRoleEnum userRole, Boolean validateState) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ RestResponse associate2ResourceInstancesResponse = ResourceRestUtils.associate2ResourceInstances(containerDetails, fromNode, toNode, assocType, defaultUser);
+
+ if (validateState) {
+ assertTrue(associate2ResourceInstancesResponse.getErrorCode() == ServiceRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ return associate2ResourceInstancesResponse;
+ }
+
+ public static Either<Pair<Component, ComponentInstance>, RestResponse> changeComponentInstanceVersion(Component containerDetails, ComponentInstance componentInstanceToReplace, Component newInstance, UserRoleEnum userRole, Boolean validateState)
+ throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+
+ RestResponse changeComponentInstanceVersionResp = ComponentInstanceRestUtils.changeComponentInstanceVersion(containerDetails, componentInstanceToReplace, newInstance, defaultUser);
+ if (validateState) {
+ assertTrue("change ComponentInstance version failed: " + changeComponentInstanceVersionResp.getResponseMessage(), changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ if (changeComponentInstanceVersionResp.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
+
+ Component compoenntObject = AtomicOperationUtils.getCompoenntObject(containerDetails, userRole);
+ ComponentInstance componentInstanceJavaObject = ResponseParser.convertComponentInstanceResponseToJavaObject(changeComponentInstanceVersionResp.getResponse());
+
+ return Either.left(Pair.of(compoenntObject, componentInstanceJavaObject));
+ }
+
+ return Either.right(changeComponentInstanceVersionResp);
+ }
+
+ // *********** PROPERTIES *****************
+
+ public static Either<ComponentInstanceProperty, RestResponse> addCustomPropertyToResource(PropertyReqDetails propDetails, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
+
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ propertyToSend.put(propDetails.getName(), propDetails);
+ Gson gson = new Gson();
+ RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
+
+ if (validateState) {
+ assertTrue("add property to resource failed: " + addPropertyResponse.getErrorCode(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
+ ComponentInstanceProperty compInstProp = null;
+ String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
+ compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
+ return Either.left(compInstProp);
+ }
+ return Either.right(addPropertyResponse);
+ }
+
+ // Benny
+ public static Either<ComponentInstanceProperty, RestResponse> updatePropertyOfResource(PropertyReqDetails propDetails, Resource resourceDetails, String propertyUniqueId, UserRoleEnum userRole, Boolean validateState) throws Exception {
+
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ propertyToSend.put(propDetails.getName(), propDetails);
+ Gson gson = new Gson();
+ RestResponse addPropertyResponse = PropertyRestUtils.updateProperty(resourceDetails.getUniqueId(), propertyUniqueId, gson.toJson(propertyToSend), defaultUser);
+
+ if (validateState) {
+ assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ }
+
+ if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS) {
+ ComponentInstanceProperty compInstProp = null;
+ String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
+ compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
+ return Either.left(compInstProp);
+ }
+ return Either.right(addPropertyResponse);
+ }
+
+ public static RestResponse deletePropertyOfResource(String resourceId, String propertyId, UserRoleEnum userRole) throws Exception {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ return PropertyRestUtils.deleteProperty(resourceId, propertyId, defaultUser);
+ }
+
+ public static Either<ComponentInstanceProperty, RestResponse> addDefaultPropertyToResource(PropertyTypeEnum propertyType, Resource resourceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception {
+
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ PropertyReqDetails propDetails = ElementFactory.getPropertyDetails(propertyType);
+ Map<String, PropertyReqDetails> propertyToSend = new HashMap<String, PropertyReqDetails>();
+ propertyToSend.put(propDetails.getName(), propDetails);
+ Gson gson = new Gson();
+ RestResponse addPropertyResponse = PropertyRestUtils.createProperty(resourceDetails.getUniqueId(), gson.toJson(propertyToSend), defaultUser);
+
+ if (validateState) {
+ assertTrue("add property to resource failed: " + addPropertyResponse.getResponseMessage(), addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (addPropertyResponse.getErrorCode() == BaseRestUtils.STATUS_CODE_CREATED) {
+ ComponentInstanceProperty compInstProp = null;
+ String property = ResponseParser.getJsonObjectValueByKey(addPropertyResponse.getResponse(), propDetails.getName());
+ compInstProp = (ResponseParser.convertPropertyResponseToJavaObject(property));
+
+ return Either.left(compInstProp);
+ }
+ return Either.right(addPropertyResponse);
+ }
+
+ public static RestResponse createDefaultConsumer(Boolean validateState) {
+ try {
+ ConsumerDataDefinition defaultConsumerDefinition = ElementFactory.getDefaultConsumerDetails();
+ RestResponse createResponse = ConsumerRestUtils.createConsumer(defaultConsumerDefinition, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN));
+ BaseRestUtils.checkCreateResponse(createResponse);
+
+ if (validateState) {
+ assertTrue(createResponse.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+ return createResponse;
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+ /**
+ * Builds Resource From rest response
+ *
+ * @param resourceResp
+ * @return
+ */
+ public static Either<Resource, RestResponse> buildResourceFromResponse(RestResponse resourceResp) {
+ Either<Resource, RestResponse> result;
+ if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ result = Either.left(resourceResponseObject);
+ } else {
+ result = Either.right(resourceResp);
+ }
+ return result;
+ }
+
+ private static class AtomicOperationException extends RuntimeException {
+ private AtomicOperationException(Exception e) {
+ super(e);
+ }
+
+ private static final long serialVersionUID = 1L;
+ };
+
+ /**
+ * Import resource from CSAR
+ *
+ * @param resourceType
+ * @param userRole
+ * @param fileName
+ * @param filePath
+ * @return Resource
+ * @throws Exception
+ */
+ public static Resource importResourceFromCSAR(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, String... filePath) throws Exception {
+ // Get the CSARs path
+ String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars";
+ if (filePath != null && filePath.length > 0) {
+ realFilePath = filePath.toString();
+ }
+
+ // Create default import resource & user
+ ImportReqDetails resourceDetails = ElementFactory.getDefaultImportResource();
+ User sdncModifierDetails = ElementFactory.getDefaultUser(userRole);
+
+ byte[] data = null;
+ Path path = Paths.get(realFilePath + File.separator + fileName);
+ data = Files.readAllBytes(path);
+ String payloadName = fileName;
+ String payloadData = Base64.encodeBase64String(data);
+ resourceDetails.setPayloadData(payloadData);
+ resourceDetails.setCsarUUID(payloadName);
+ resourceDetails.setPayloadName(payloadName);
+ resourceDetails.setResourceType(resourceType.name());
+
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ return ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ };
+
+ public static Either<Resource, RestResponse> importResourceByFileName(ResourceTypeEnum resourceType, UserRoleEnum userRole, String fileName, Boolean validateState, String... filePath) throws IOException {
+
+ String realFilePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + "CI" + File.separator + "csars";
+ if (filePath != null && filePath.length > 0) {
+ realFilePath = filePath.toString();
+ }
+
+ try {
+ User defaultUser = ElementFactory.getDefaultUser(userRole);
+ ResourceReqDetails defaultResource = ElementFactory.getDefaultResource(defaultUser);
+ ImportReqDetails defaultImportResource = ElementFactory.getDefaultImportResource(defaultResource);
+ ImportUtils.getImportResourceDetailsByPathAndName(defaultImportResource, realFilePath, fileName);
+ RestResponse resourceResp = ResourceRestUtils.createResource(defaultImportResource, defaultUser);
+
+ if (validateState) {
+ assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED);
+ }
+
+ if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) {
+ Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse());
+ return Either.left(resourceResponseObject);
+ }
+ return Either.right(resourceResp);
+ } catch (Exception e) {
+ throw new AtomicOperationException(e);
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
new file mode 100644
index 0000000000..4aa13b48e4
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/Convertor.java
@@ -0,0 +1,309 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_CREATED;
+import static org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils.STATUS_CODE_SUCCESS;
+
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.lang3.StringUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+
+public class Convertor {
+ // ***** resource *****
+ public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails,
+ String resourceVersion) {
+ return convertToRespObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(),
+ UserRoleEnum.ADMIN.getUserName());
+
+ }
+
+ public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails) {
+ return convertToRespObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(),
+ UserRoleEnum.ADMIN.getUserName());
+
+ }
+
+ public static ResourceRespJavaObject constructFieldsForRespValidation(ResourceReqDetails resourceDetails,
+ String resourceVersion, User user) {
+ return convertToRespObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName());
+
+ }
+
+ private static ResourceRespJavaObject convertToRespObject(ResourceReqDetails resourceDetails,
+ String resourceVersion, String userId, String userName) {
+ ResourceRespJavaObject resourceRespJavaObject = new ResourceRespJavaObject();
+
+ resourceRespJavaObject.setUniqueId(resourceDetails.getUniqueId());
+ resourceRespJavaObject.setName(resourceDetails.getName());
+ resourceRespJavaObject.setCreatorUserId(resourceDetails.getCreatorUserId());
+ resourceRespJavaObject.setCreatorFullName(resourceDetails.getCreatorFullName());
+ resourceRespJavaObject.setLastUpdaterUserId(userId);
+ resourceRespJavaObject.setLastUpdaterFullName(userName);
+ resourceRespJavaObject.setDescription(resourceDetails.getDescription());
+ resourceRespJavaObject.setIcon(resourceDetails.getIcon());
+ resourceRespJavaObject.setTags(resourceDetails.getTags());
+ resourceRespJavaObject.setIsHighestVersion("true");
+ resourceRespJavaObject.setCategories(resourceDetails.getCategories());
+ resourceRespJavaObject.setLifecycleState(
+ resourceDetails.getLifecycleState() != null ? resourceDetails.getLifecycleState().toString()
+ : LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ // resourceRespJavaObject.setLifecycleState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ resourceRespJavaObject.setDerivedFrom(resourceDetails.getDerivedFrom());
+ resourceRespJavaObject.setVendorName(resourceDetails.getVendorName());
+ resourceRespJavaObject.setVendorRelease(resourceDetails.getVendorRelease());
+ resourceRespJavaObject.setContactId(resourceDetails.getContactId());
+ resourceRespJavaObject.setAbstractt("false");
+ resourceRespJavaObject.setVersion(resourceVersion);
+ resourceRespJavaObject.setCost(resourceDetails.getCost());
+ resourceRespJavaObject.setLicenseType(resourceDetails.getLicenseType());
+ resourceRespJavaObject.setResourceType(resourceDetails.getResourceType());
+
+ return resourceRespJavaObject;
+
+ }
+
+ // ********** product **************
+
+ public static Product constructFieldsForRespValidation(ProductReqDetails productDetails, String productVersion,
+ User user) {
+ return convertToRespObject(productDetails, productVersion, user.getUserId(), user.getFullName());
+ }
+
+ private static Product convertToRespObject(ProductReqDetails productDetails, String productVersion, String userId,
+ String userName) {
+ Product expectedProduct = new Product();
+
+ expectedProduct.setUniqueId(productDetails.getUniqueId());
+ expectedProduct.setName(productDetails.getName());
+ expectedProduct.setFullName(productDetails.getFullName());
+ expectedProduct.setCreatorUserId(productDetails.getCreatorUserId());
+ expectedProduct.setCreatorFullName(productDetails.getCreatorFullName());
+ expectedProduct.setLastUpdaterUserId(userId);
+ expectedProduct.setLastUpdaterFullName(userName);
+ expectedProduct.setDescription(productDetails.getDescription());
+ // expectedProduct.setIcon(resourceDetails.getIcon());
+ expectedProduct.setTags(productDetails.getTags());
+ expectedProduct.setHighestVersion(true);
+ List<CategoryDefinition> categories = productDetails.getCategories();
+ if (categories == null) {
+ categories = new ArrayList<>();
+ }
+ expectedProduct.setCategories(categories);
+ expectedProduct.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ expectedProduct.setVersion(productVersion);
+ expectedProduct.setContacts(productDetails.getContacts());
+ return expectedProduct;
+ }
+
+ // ***** audit *****
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails,
+ String resourceVersion) {
+ return convertToAuditObject(resourceDetails, resourceVersion, UserRoleEnum.ADMIN.getUserId(),
+ UserRoleEnum.ADMIN.getUserName());
+ }
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(
+ ResourceReqDetails resourceDetails) {
+ return convertToAuditObject(resourceDetails, resourceDetails.getVersion(), UserRoleEnum.ADMIN.getUserId(),
+ UserRoleEnum.ADMIN.getUserName());
+ }
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ResourceReqDetails resourceDetails,
+ String resourceVersion, User user) {
+ return convertToAuditObject(resourceDetails, resourceVersion, user.getUserId(), user.getFullName());
+ }
+
+ private static ExpectedResourceAuditJavaObject convertToAuditObject(ResourceReqDetails resourceDetails,
+ String resourceVersion, String userId, String userName) {
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+
+ expectedResourceAuditJavaObject.setAction("Checkout");
+ expectedResourceAuditJavaObject.setModifierName(userName);
+ expectedResourceAuditJavaObject.setModifierUid(userId);
+ expectedResourceAuditJavaObject.setStatus("200.0");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setResourceName(resourceDetails.getName());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(resourceVersion) - 0.1f));
+ expectedResourceAuditJavaObject.setCurrVersion(resourceVersion);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setComment(null);
+
+ return expectedResourceAuditJavaObject;
+ }
+
+ public static ExpectedProductAudit constructFieldsForAuditValidation(Product productDetails, String action,
+ User user, ActionStatus actionStatus, String prevVersion, String currVersion, LifecycleStateEnum prevState,
+ LifecycleStateEnum currState, String uuid, String... errorMessageParams) throws FileNotFoundException {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ return convertToAuditObject(productDetails, action, user, errorInfo, prevVersion, currVersion, prevState,
+ currState, uuid, errorMessageParams);
+ }
+
+ private static ExpectedProductAudit convertToAuditObject(Product productDetails, String action, User user,
+ ErrorInfo errorInfo, String prevVersion, String currVersion, LifecycleStateEnum prevState,
+ LifecycleStateEnum currState, String uuid, String... errorMessageParams) {
+ ExpectedProductAudit expectedProductAudit = new ExpectedProductAudit();
+
+ expectedProductAudit.setACTION(action);
+ String userId = user.getUserId();
+ String userFullName;
+ if (StringUtils.isEmpty(user.getFirstName()) && StringUtils.isEmpty(user.getLastName())) {
+ userFullName = "";
+ } else {
+ userFullName = user.getFullName();
+ }
+ if (StringUtils.isEmpty(userId)) {
+ userId = "UNKNOWN";
+ }
+ expectedProductAudit.setMODIFIER(
+ !StringUtils.isEmpty(userFullName) ? userFullName + "(" + userId + ")" : "(" + userId + ")");
+ expectedProductAudit.setSTATUS(Integer.toString(errorInfo.getCode()));
+ expectedProductAudit.setDESC(errorInfo.getAuditDesc((Object[]) (errorMessageParams)));
+ expectedProductAudit
+ .setRESOURCE_NAME(productDetails != null ? productDetails.getName() : Constants.EMPTY_STRING);
+ expectedProductAudit.setRESOURCE_TYPE("Product");
+ expectedProductAudit.setPREV_VERSION(prevVersion);
+ expectedProductAudit.setCURR_VERSION(currVersion);
+ expectedProductAudit.setPREV_STATE(prevState != null ? prevState.name() : Constants.EMPTY_STRING);
+ expectedProductAudit.setCURR_STATE(currState != null ? currState.name() : Constants.EMPTY_STRING);
+ expectedProductAudit.setSERVICE_INSTANCE_ID(uuid);
+ return expectedProductAudit;
+ }
+
+ ////////////////
+ // Convertor.constructFieldsForAuditValidationSuccess(addUser,
+ //////////////// sdncAdminUser, mechIdUser, null, STATUS_CODE_CREATED);
+ public static ExpectedUserCRUDAudit constructFieldsForAuditValidation(String action, User userModifier,
+ ActionStatus actionStatus, User userAfter, User userBefore, Object... variables) throws Exception {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ ExpectedUserCRUDAudit expectedAddUserAuditJavaObject = new ExpectedUserCRUDAudit();
+ expectedAddUserAuditJavaObject.setAction(action);
+ expectedAddUserAuditJavaObject.setModifier(
+ userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
+ : "(" + userModifier.getUserId() + ")");
+ String status = Integer.toString(errorInfo.getCode());
+ expectedAddUserAuditJavaObject.setStatus(status);
+ if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
+ expectedAddUserAuditJavaObject.setDesc("OK");
+ } else {
+ expectedAddUserAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ }
+ expectedAddUserAuditJavaObject.setUserBefore(userBefore != null
+ ? userBefore.getUserId() + ", " + userBefore.getFirstName() + " " + userBefore.getLastName() + ", "
+ + userBefore.getEmail() + ", " + userBefore.getRole()
+ : Constants.EMPTY_STRING);
+ expectedAddUserAuditJavaObject.setUserAfter(userAfter != null
+ ? userAfter.getUserId() + ", " + userAfter.getFirstName() + " " + userAfter.getLastName() + ", "
+ + userAfter.getEmail() + ", " + userAfter.getRole()
+ : Constants.EMPTY_STRING);
+ return expectedAddUserAuditJavaObject;
+ }
+
+ // For RESOURCE and SERVICE same Audit
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(
+ ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus,
+ String currVersion, String prevVersion, String curState, String prevState, String uuid, String comment,
+ Object... variables) throws Exception {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(action);
+ expectedResourceAuditJavaObject.setMODIFIER(
+ userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
+ : "(" + userModifier.getUserId() + ")");
+ String status = Integer.toString(errorInfo.getCode());
+ expectedResourceAuditJavaObject.setStatus(status);
+ if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
+ expectedResourceAuditJavaObject.setDesc("OK");
+ } else {
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ }
+ expectedResourceAuditJavaObject.setCurrState(curState);
+ expectedResourceAuditJavaObject.setPrevState(prevState);
+ expectedResourceAuditJavaObject.setCurrVersion(currVersion);
+ expectedResourceAuditJavaObject.setPrevVersion(prevVersion);
+ expectedResourceAuditJavaObject.setComment(comment);
+ expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid);
+ if (componentDetails instanceof ServiceReqDetails) {
+ expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ }
+ if (componentDetails instanceof ResourceReqDetails) {
+ expectedResourceAuditJavaObject.setResourceName(((ResourceReqDetails) componentDetails).getName());
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ }
+ return expectedResourceAuditJavaObject;
+ }
+
+ // Distribution Service Audit
+ public static ExpectedResourceAuditJavaObject constructFieldsForDistributionAuditValidation(
+ ComponentReqDetails componentDetails, String action, User userModifier, ActionStatus actionStatus,
+ String currVersion, String distCurrStatus, String distProvStatus, String curState, String uuid,
+ String comment, Object... variables) throws Exception {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(action);
+ expectedResourceAuditJavaObject.setMODIFIER(
+ userModifier.getFirstName() != null ? userModifier.getFullName() + "(" + userModifier.getUserId() + ")"
+ : "(" + userModifier.getUserId() + ")");
+ String status = Integer.toString(errorInfo.getCode());
+ expectedResourceAuditJavaObject.setStatus(status);
+ if (errorInfo.getCode() == STATUS_CODE_SUCCESS || errorInfo.getCode() == STATUS_CODE_CREATED) {
+ expectedResourceAuditJavaObject.setDesc("OK");
+ } else {
+ expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ }
+ expectedResourceAuditJavaObject.setCurrState(curState);
+ expectedResourceAuditJavaObject.setCurrVersion(currVersion);
+ expectedResourceAuditJavaObject.setDcurrStatus(distCurrStatus);
+ expectedResourceAuditJavaObject.setDprevStatus(distProvStatus);
+ expectedResourceAuditJavaObject.setComment(comment);
+ expectedResourceAuditJavaObject.setSERVICE_INSTANCE_ID(uuid);
+ if (componentDetails instanceof ServiceReqDetails) {
+ expectedResourceAuditJavaObject.setResourceName(((ServiceReqDetails) componentDetails).getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ }
+ return expectedResourceAuditJavaObject;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
new file mode 100644
index 0000000000..ba2ebd9b4e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java
@@ -0,0 +1,873 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.RelationshipImpl;
+import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.PropertyTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
+
+public class ElementFactory {
+
+ private static String DEFAULT_ARTIFACT_LABEL = "artifact1";
+ private static final String RESOURCE_INSTANCE_POS_X = "20";
+ private static final String RESOURCE_INSTANCE_POS_Y = "20";
+ private static final String RESOURCE_INSTANCE_DESCRIPTION = "description";
+
+ // *** RESOURCE ***
+
+ public static ResourceReqDetails getDefaultResource() {
+ return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ }
+
+ public static ResourceReqDetails getDefaultResource(ResourceCategoryEnum category) {
+ return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, category, "jh0003");
+ }
+
+ public static ResourceReqDetails getDefaultResource(String contactId) {
+ return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
+ }
+
+ public static ResourceReqDetails getDefaultResource(User modifier) {
+ return getDefaultResource("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, modifier.getUserId());
+ }
+
+ public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, ResourceCategoryEnum category) {
+ return getDefaultResource("ciRes", derivedFrom, category, "jh0003");
+ }
+
+ public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom) {
+ return getDefaultResource("ciRes", derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ }
+
+ public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derivedFrom) {
+ return getDefaultResource(resourceName, derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003");
+ }
+
+ public static ResourceReqDetails getDefaultResource(NormativeTypesEnum derivedFrom, String contactId) {
+ return getDefaultResource("ciRes", derivedFrom, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, contactId);
+ }
+
+ // New
+ public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, String resourceName) {
+ return getDefaultResourceByType(resourceName, NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, "jh0003", ResourceType.toString());
+ }
+
+ public static ResourceReqDetails getDefaultResourceByType(ResourceTypeEnum ResourceType, User user) {
+ return getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.GENERIC_INFRASTRUCTURE, user.getUserId(), ResourceType.toString());
+ }
+
+ public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, User user) {
+ return getDefaultResourceByType("ciRes", normativeTypes, resourceCategory, user.getUserId(), resourceType.toString());
+ }
+
+ public static PropertyReqDetails getDefaultMapProperty(PropertyTypeEnum innerType) {
+ return getPropertyDetails(innerType);
+ }
+
+ public static PropertyReqDetails getDefaultMapProperty() {
+ return getPropertyDetails(PropertyTypeEnum.STRING_MAP);
+ }
+
+ public static ResourceReqDetails getDefaultResource(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId) {
+ resourceName = (resourceName + generateUUIDforSufix());
+ String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(derived.normativeName);
+ String vendorName = "ATT (Tosca)";
+ String vendorRelease = "1.0.0.wd03";
+ String icon = "defaulticon";
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
+
+ return resourceDetails;
+
+ }
+
+ public static ResourceReqDetails getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, Resource normativeTypes, ResourceCategoryEnum resourceCategory, User user) {
+ return getDefaultResource("ciRes" + resourceType, normativeTypes, resourceCategory, user.getUserId());
+ }
+
+ public static ResourceReqDetails getDefaultResource(String resourceName, Resource derived, ResourceCategoryEnum category, String contactId) {
+ resourceName = (resourceName + generateUUIDforSufix());
+ String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+
+ ArrayList<String> derivedFrom = new ArrayList<String>();
+ derivedFrom.add(derived.getToscaResourceName());
+ String vendorName = "ATT (Tosca)";
+ String vendorRelease = "1.0.0.wd03";
+ String icon = "defaulticon";
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
+
+ return resourceDetails;
+
+ }
+
+ public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, ResourceTypeEnum resourceType) {
+ return getDefaultResourceByType(resourceName, derived, category, contactId, resourceType.toString());
+ }
+
+ // New
+ public static ResourceReqDetails getDefaultResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) {
+ resourceName = (resourceName + resourceType + generateUUIDforSufix());
+ String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = null;
+ if (derived != null) {
+ derivedFrom = new ArrayList<String>();
+ derivedFrom.add(derived.normativeName);
+ }
+ String vendorName = "ATT (Tosca)";
+ String vendorRelease = "1.0.0.wd03";
+ String icon = "defaulticon";
+ ResourceReqDetails resourceDetails = new ResourceReqDetails(resourceName, description, resourceTags, null, derivedFrom, vendorName, vendorRelease, contactId, icon, resourceType.toString());
+ resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
+ return resourceDetails;
+ }
+
+ // New
+ public static ImportReqDetails getDefaultImportResourceByType(String resourceName, NormativeTypesEnum derived, ResourceCategoryEnum category, String contactId, String resourceType) {
+ resourceName = (resourceName + resourceType + generateUUIDforSufix());
+ String description = "Represents a generic software component that can be managed and run by a Compute Node Type.";
+ ArrayList<String> resourceTags = new ArrayList<String>();
+ resourceTags.add(resourceName);
+ ArrayList<String> derivedFrom = null;
+ if (derived != null) {
+ derivedFrom = new ArrayList<String>();
+ derivedFrom.add(derived.normativeName);
+ }
+ String vendorName = "ATT (Tosca)";
+ String vendorRelease = "1.0.0.wd03";
+ String icon = "defaulticon";
+ ImportReqDetails resourceDetails = new ImportReqDetails(resourceName, description, resourceTags, derivedFrom, vendorName, vendorRelease, contactId, icon);
+ resourceDetails.addCategoryChain(category.getCategory(), category.getSubCategory());
+ return resourceDetails;
+ }
+ ////
+
+ public static ImportReqDetails getDefaultImportResource(ResourceReqDetails resourceReqDetails) {
+ ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
+ resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
+ importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setCategories(resourceReqDetails.getCategories());
+ importReqDetails.setPayloadData(
+ "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
+ return importReqDetails;
+ }
+
+ public static ImportReqDetails getDefaultImportResource() {
+ ResourceReqDetails resourceReqDetails = getDefaultResource();
+ ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
+ resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
+ importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setCategories(resourceReqDetails.getCategories());
+ importReqDetails.setPayloadData(
+ "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
+ return importReqDetails;
+ }
+
+ public static ImportReqDetails getDefaultImportResource(String name) {
+ ResourceReqDetails resourceReqDetails = getDefaultResourceByType(ResourceTypeEnum.VFC, name);
+ ImportReqDetails importReqDetails = new ImportReqDetails(resourceReqDetails.getName(), resourceReqDetails.getDescription(), resourceReqDetails.getTags(), resourceReqDetails.getDerivedFrom(), resourceReqDetails.getVendorName(),
+ resourceReqDetails.getVendorRelease(), resourceReqDetails.getContactId(), resourceReqDetails.getIcon());
+ importReqDetails.setPayloadName("myCompute.yaml");
+ importReqDetails.setCategories(resourceReqDetails.getCategories());
+ importReqDetails.setPayloadData(
+ "dG9zY2FfZGVmaW5pdGlvbnNfdmVyc2lvbjogdG9zY2Ffc2ltcGxlX3lhbWxfMV8wXzANCm5vZGVfdHlwZXM6IA0KICBvcmcub3BlbmVjb21wLnJlc291cmNlLk15Q29tcHV0ZToNCiAgICBkZXJpdmVkX2Zyb206IHRvc2NhLm5vZGVzLlJvb3QNCiAgICBhdHRyaWJ1dGVzOg0KICAgICAgcHJpdmF0ZV9hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIHB1YmxpY19hZGRyZXNzOg0KICAgICAgICB0eXBlOiBzdHJpbmcNCiAgICAgIG5ldHdvcmtzOg0KICAgICAgICB0eXBlOiBtYXANCiAgICAgICAgZW50cnlfc2NoZW1hOg0KICAgICAgICAgIHR5cGU6IHRvc2NhLmRhdGF0eXBlcy5uZXR3b3JrLk5ldHdvcmtJbmZvDQogICAgICBwb3J0czoNCiAgICAgICAgdHlwZTogbWFwDQogICAgICAgIGVudHJ5X3NjaGVtYToNCiAgICAgICAgICB0eXBlOiB0b3NjYS5kYXRhdHlwZXMubmV0d29yay5Qb3J0SW5mbw0KICAgIHJlcXVpcmVtZW50czoNCiAgICAgIC0gbG9jYWxfc3RvcmFnZTogDQogICAgICAgICAgY2FwYWJpbGl0eTogdG9zY2EuY2FwYWJpbGl0aWVzLkF0dGFjaG1lbnQNCiAgICAgICAgICBub2RlOiB0b3NjYS5ub2Rlcy5CbG9ja1N0b3JhZ2UNCiAgICAgICAgICByZWxhdGlvbnNoaXA6IHRvc2NhLnJlbGF0aW9uc2hpcHMuQXR0YWNoZXNUbw0KICAgICAgICAgIG9jY3VycmVuY2VzOiBbMCwgVU5CT1VOREVEXSAgDQogICAgY2FwYWJpbGl0aWVzOg0KICAgICAgaG9zdDogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5Db250YWluZXINCiAgICAgICAgdmFsaWRfc291cmNlX3R5cGVzOiBbdG9zY2Eubm9kZXMuU29mdHdhcmVDb21wb25lbnRdIA0KICAgICAgZW5kcG9pbnQgOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuRW5kcG9pbnQuQWRtaW4gDQogICAgICBvczogDQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5PcGVyYXRpbmdTeXN0ZW0NCiAgICAgIHNjYWxhYmxlOg0KICAgICAgICB0eXBlOiB0b3NjYS5jYXBhYmlsaXRpZXMuU2NhbGFibGUNCiAgICAgIGJpbmRpbmc6DQogICAgICAgIHR5cGU6IHRvc2NhLmNhcGFiaWxpdGllcy5uZXR3b3JrLkJpbmRhYmxlDQo=");
+ return importReqDetails;
+ }
+
+ // *** SERVICE ***
+ public static ServiceReqDetails getDefaultService() {
+ return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, "al1976");
+ }
+
+ public static ServiceReqDetails getDefaultService(String contactId) {
+ return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, contactId);
+ }
+
+ public static ServiceReqDetails getDefaultService(User user) {
+ return getDefaultService("ciService", ServiceCategoriesEnum.MOBILITY, user.getUserId());
+ }
+
+ public static ServiceReqDetails getService(ServiceCategoriesEnum category) {
+ return getDefaultService("ciService", category, "al1976");
+ }
+
+ public static ServiceReqDetails getDefaultService(ServiceCategoriesEnum category, User user) {
+ return getDefaultService("ciService", category, user.getUserId());
+ }
+
+ public static ServiceReqDetails getDefaultService(String serviceName, ServiceCategoriesEnum category, String contactId) {
+ serviceName = (serviceName + generateUUIDforSufix());
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add("serviceTag");
+ tags.add("serviceTag1");
+ tags.add(serviceName);
+ String description = "service Description";
+ String icon = "myIcon";
+
+ ServiceReqDetails serviceDetails = new ServiceReqDetails(serviceName, category.getValue(), tags, description, contactId, icon);
+
+ return serviceDetails;
+ }
+
+ // ***** PROPERTY ***
+
+ public static PropertyReqDetails getDefaultProperty() {
+ return getDefaultProperty("disk_size");
+ }
+
+ public static PropertyReqDetails getDefaultProperty(String propertyName) {
+ PropertyReqDetails property = new PropertyReqDetails();
+ property.setName(propertyName);
+ property.setPropertyType("integer");
+ property.setPropertyRequired(false);
+ property.setPropertyDefaultValue("12345");
+ property.setPropertyDescription("test property");
+ property.setPropertyRangeMax("500");
+ property.setPropertyRangeMin("100");
+ property.setPropertyPassword(false);
+ return property;
+ }
+
+ public static PropertyReqDetails getDefaultIntegerProperty() {
+ return getPropertyDetails(PropertyTypeEnum.INTEGER);
+ }
+
+ public static PropertyReqDetails getDefaultStringProperty() {
+ return getPropertyDetails(PropertyTypeEnum.STRING);
+ }
+
+ public static PropertyReqDetails getDefaultBooleanProperty() {
+ return getPropertyDetails(PropertyTypeEnum.BOOLEAN);
+ }
+
+ public static PropertyReqDetails getDefaultListProperty() {
+ return getPropertyDetails(PropertyTypeEnum.STRING_LIST);
+ }
+
+ public static PropertyReqDetails getDefaultListProperty(PropertyTypeEnum innerType) {
+ return getPropertyDetails(innerType);
+ }
+
+ public static PropertyReqDetails getPropertyDetails(PropertyTypeEnum propType) {
+ return new PropertyReqDetails(propType.getName(), propType.getType(), propType.getValue(), propType.getDescription(), propType.getSchemaDefinition());
+ }
+
+ // ***** RESOURCE INSTANCE ***
+ public static ComponentInstanceReqDetails getDefaultComponentInstance() {
+ return getDefaultComponentInstance("resourceInstanceName");
+ }
+
+ public static ComponentInstanceReqDetails getDefaultComponentInstance(String name) {
+ String resourceUid = "resourceId";
+ ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name);
+
+ return resourceInstanceDetails;
+
+ }
+
+ public static ComponentInstanceReqDetails getDefaultComponentInstance(String name, ComponentReqDetails componentReqDetails) {
+ String resourceUid = componentReqDetails.getUniqueId();
+ ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, name);
+
+ return resourceInstanceDetails;
+
+ }
+
+ public static ComponentInstanceReqDetails getComponentResourceInstance(ComponentReqDetails compInstOriginDetails) {
+ String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "resourceInstanceName");
+ String resourceUid = compInstOriginDetails.getUniqueId();
+ ComponentInstanceReqDetails resourceInstanceDetails = new ComponentInstanceReqDetails(resourceUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName);
+ return resourceInstanceDetails;
+
+ }
+
+ public static ComponentInstanceReqDetails getComponentInstance(Component compInstOriginDetails) {
+ String compInstName = (compInstOriginDetails.getName() != null ? compInstOriginDetails.getName() : "componentInstanceName");
+ String compInsUid = compInstOriginDetails.getUniqueId();
+ ComponentInstanceReqDetails componentInstanceDetails = new ComponentInstanceReqDetails(compInsUid, RESOURCE_INSTANCE_DESCRIPTION, RESOURCE_INSTANCE_POS_X, RESOURCE_INSTANCE_POS_Y, compInstName);
+ return componentInstanceDetails;
+
+ }
+
+ // ******* USER **********************
+ public static User getDefaultUser(UserRoleEnum userRole) {
+ User sdncModifierDetails = new User();
+ sdncModifierDetails.setUserId(userRole.getUserId());
+ sdncModifierDetails.setFirstName(userRole.getFirstName());
+ sdncModifierDetails.setLastName(userRole.getLastName());
+ return sdncModifierDetails;
+ }
+
+ public static User getDefaultMechUser() {
+ User sdncMechUserDetails = new User();
+ sdncMechUserDetails.setUserId("m12345");
+ sdncMechUserDetails.setFirstName("Shay");
+ sdncMechUserDetails.setLastName("Sponder");
+ sdncMechUserDetails.setEmail("mechId@intl.sdc.com");
+ sdncMechUserDetails.setRole("DESIGNER");
+ return sdncMechUserDetails;
+ }
+
+ // ******* CONSUMER **********************
+
+ public static ConsumerDataDefinition getDefaultConsumerDetails() {
+ ConsumerDataDefinition consumer = new ConsumerDataDefinition();
+ consumer.setConsumerName("ci");
+ consumer.setConsumerSalt("2a1f887d607d4515d4066fe0f5452a50");
+ consumer.setConsumerPassword("0a0dc557c3bf594b1a48030e3e99227580168b21f44e285c69740b8d5b13e33b");
+ return consumer;
+ }
+
+ // *** ARTIFACT ***
+ public static ArtifactReqDetails getDefaultArtifact() throws IOException, Exception {
+ return getDefaultArtifact(DEFAULT_ARTIFACT_LABEL);
+ }
+
+ public static ArtifactReqDetails getDefaultArtifact(String artifactLabel) throws IOException, Exception {
+ List<String> artifactTypes = ResponseParser.getValuesFromJsonArray(ArtifactRestUtils.getArtifactTypesList());
+ String artifactType = artifactTypes.get(0);
+
+ return getDefaultArtifact(artifactLabel, artifactType);
+ }
+
+ public static ArtifactReqDetails getDefaultArtifact(String artifactLabel, String artifactType) throws IOException, Exception {
+
+ String artifactName = "testArtifact.sh";
+ String artifactDescription = "descriptionTest";
+ String payloadData = "dGVzdA=="; // content of file
+
+ ArtifactReqDetails artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel);
+ artifactDetails.setUrl("");
+ artifactDetails.setArtifactDisplayName(artifactLabel);
+ return artifactDetails;
+ }
+
+ public static ArtifactReqDetails getServiceApiArtifactDetails(String artifactLabel) throws IOException, Exception {
+ ArtifactReqDetails defaultArtifact = getDefaultArtifact(artifactLabel, "OTHER");
+ defaultArtifact.setUrl("http://www.apple.com");
+ defaultArtifact.setServiceApi(true);
+ defaultArtifact.setArtifactDisplayName(StringUtils.capitalize(defaultArtifact.getArtifactLabel()));
+ return defaultArtifact;
+ }
+
+ public static ArtifactReqDetails getDefaultDeploymentArtifactForType(String artifactType) throws IOException, Exception {
+ return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType, true);
+ }
+
+ public static ArtifactReqDetails getArtifactByType(ArtifactTypeEnum artifactLabel, ArtifactTypeEnum artifactType, Boolean deploymentTrue) throws IOException, Exception {
+ return getArtifactByType(DEFAULT_ARTIFACT_LABEL, artifactType.toString(), deploymentTrue);
+
+ }
+
+ public static ArtifactReqDetails getArtifactByType(String artifactLabel, String artifactType, Boolean deploymentTrue) throws IOException, Exception {
+ String artifactName;
+ String payloadData = null;
+ Integer timeout = null;
+ String url = "";
+ String artifactDescription = "descriptionTest";
+
+ // PLEASE NOTE!!!
+ // The non-default payloads here are real ones according to various
+ // types validations,
+ // Please don't change them unless you know what you are doing!
+
+ ArtifactTypeEnum artifactTypeEnum = ArtifactTypeEnum.findType(artifactType);
+
+ /*
+ * Missing file type: DCAE_JSON
+ */
+ switch (artifactTypeEnum) {
+ case DCAE_EVENT:
+ case APPC_CONFIG:
+ case DCAE_DOC:
+ case DCAE_TOSCA:
+ case HEAT:
+ case HEAT_NET:
+ case HEAT_VOL: {
+ artifactName = generateUUIDforSufix() + artifactType + "_install_apache2.yaml";
+ payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ timeout = 60;
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ case DCAE_INVENTORY_TOSCA:
+ case DCAE_INVENTORY_JSON:
+ case DCAE_INVENTORY_POLICY:
+ case DCAE_INVENTORY_DOC:
+ case DCAE_INVENTORY_BLUEPRINT:
+ case DCAE_INVENTORY_EVENT: {
+ artifactName = getDcaeArtifactName(artifactTypeEnum, artifactType);
+ payloadData = "will be override later";
+ timeout = 60;
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ case MURANO_PKG: {
+ artifactName = artifactType + "org.openstack.Rally.zip";
+ payloadData = "ODM4MTRjNzkxZjcwYTlkMjk4ZGQ2ODE4MThmNjg0N2Y=";
+ break;
+ }
+ case DCAE_POLICY: {
+ artifactName = artifactType + "dcae_policy.emf";
+ payloadData = "will be override later";
+ break;
+ }
+ case DCAE_JSON: {
+ artifactName = artifactType + "dcae_policy.json";
+ payloadData = "e30=";
+ break;
+ }
+ case PUPPET:
+ case CHEF:
+ case DG_XML:
+ case YANG: {
+ artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml";
+ payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
+ timeout = 15;
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ case VF_LICENSE:
+ case VENDOR_LICENSE:
+ case MODEL_INVENTORY_PROFILE:
+ case MODEL_QUERY_SPEC:
+ case VNF_CATALOG:
+ case YANG_XML: {
+ artifactName = generateUUIDforSufix() + artifactType + "yangXml.xml";
+ payloadData = "PD94bWwgdmVyc2lvbj0iMS4wIj8+DQo8ZGF0YT4NCiAgPHNwb3J0cz4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+TGlvbmVsIEFuZHJlcyBNZXNzaTwvbmFtZT4NCiAgICAgIDxiaXJ0aGRheT4xOTg3LTA2LTI0VDAwOjAwOjAwLTAwOjAwPC9iaXJ0aGRheT4NCiAgICA8L3BlcnNvbj4NCiAgICA8cGVyc29uPg0KICAgICAgPG5hbWU+Q3Jpc3RpYW5vIFJvbmFsZG88L25hbWU+DQogICAgICA8YmlydGhkYXk+MTk4NS0wMi0wNVQwMDowMDowMC0wMDowMDwvYmlydGhkYXk+DQogICAgPC9wZXJzb24+DQogICAgPHRlYW0+DQogICAgICA8bmFtZT5GQyBCYXJjZWxvbmE8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5MaW9uZWwgQW5kcmVzIE1lc3NpPC9uYW1lPg0KICAgICAgICA8c2Vhc29uPkNoYW1waW9ucyBMZWFndWUgMjAxNC0yMDE1PC9zZWFzb24+DQogICAgICAgIDxudW1iZXI+MTA8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40Mzwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICAgIDx0ZWFtPg0KICAgICAgPG5hbWU+UmVhbCBNYWRyaWQ8L25hbWU+DQogICAgICA8cGxheWVyPg0KICAgICAgICA8bmFtZT5DcmlzdGlhbm8gUm9uYWxkbzwvbmFtZT4NCiAgICAgICAgPHNlYXNvbj5DaGFtcGlvbnMgTGVhZ3VlIDIwMTQtMjAxNTwvc2Vhc29uPg0KICAgICAgICA8bnVtYmVyPjc8L251bWJlcj4NCiAgICAgICAgPHNjb3Jlcz40ODwvc2NvcmVzPg0KICAgICAgPC9wbGF5ZXI+DQogICAgPC90ZWFtPg0KICA8L3Nwb3J0cz4NCg0KPC9kYXRhPg==";
+ timeout = 0;
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ case OTHER: {
+ artifactName = generateUUIDforSufix() + artifactType + "other.pdf";
+ payloadData = "aGVhdF90ZW1wbGF0ZV92ZXJzaW9uOiAyMDEzLTA1LTIzDQoNCmRlc2NyaXB0aW9uOiBTaW1wbGUgdGVtcGxhdGUgdG8gZGVwbG95IGEgc3RhY2sgd2l0aCB0d28gdmlydHVhbCBtYWNoaW5lIGluc3RhbmNlcw0KDQpwYXJhbWV0ZXJzOg0KICBpbWFnZV9uYW1lXzE6DQogICAgdHlwZTogc3RyaW5nDQogICAgbGFiZWw6IEltYWdlIE5hbWUNCiAgICBkZXNjcmlwdGlvbjogU0NPSU1BR0UgU3BlY2lmeSBhbiBpbWFnZSBuYW1lIGZvciBpbnN0YW5jZTENCiAgICBkZWZhdWx0OiBjaXJyb3MtMC4zLjEteDg2XzY0DQogIGltYWdlX25hbWVfMjoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogSW1hZ2UgTmFtZQ0KICAgIGRlc2NyaXB0aW9uOiBTQ09JTUFHRSBTcGVjaWZ5IGFuIGltYWdlIG5hbWUgZm9yIGluc3RhbmNlMg0KICAgIGRlZmF1bHQ6IGNpcnJvcy0wLjMuMS14ODZfNjQNCiAgbmV0d29ya19pZDoNCiAgICB0eXBlOiBzdHJpbmcNCiAgICBsYWJlbDogTmV0d29yayBJRA0KICAgIGRlc2NyaXB0aW9uOiBTQ09ORVRXT1JLIE5ldHdvcmsgdG8gYmUgdXNlZCBmb3IgdGhlIGNvbXB1dGUgaW5zdGFuY2UNCiAgICBoaWRkZW46IHRydWUNCiAgICBjb25zdHJhaW50czoNCiAgICAgIC0gbGVuZ3RoOiB7IG1pbjogNiwgbWF4OiA4IH0NCiAgICAgICAgZGVzY3JpcHRpb246IFBhc3N3b3JkIGxlbmd0aCBtdXN0IGJlIGJldHdlZW4gNiBhbmQgOCBjaGFyYWN0ZXJzLg0KICAgICAgLSByYW5nZTogeyBtaW46IDYsIG1heDogOCB9DQogICAgICAgIGRlc2NyaXB0aW9uOiBSYW5nZSBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3ZhbHVlczoNCiAgICAgICAgLSBtMS5zbWFsbA0KICAgICAgICAtIG0xLm1lZGl1bQ0KICAgICAgICAtIG0xLmxhcmdlDQogICAgICAgIGRlc2NyaXB0aW9uOiBBbGxvd2VkIHZhbHVlcyBkZXNjcmlwdGlvbg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbYS16QS1aMC05XSsiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IGNvbnNpc3Qgb2YgY2hhcmFjdGVycyBhbmQgbnVtYmVycyBvbmx5Lg0KICAgICAgLSBhbGxvd2VkX3BhdHRlcm46ICJbQS1aXStbYS16QS1aMC05XSoiDQogICAgICAgIGRlc2NyaXB0aW9uOiBQYXNzd29yZCBtdXN0IHN0YXJ0IHdpdGggYW4gdXBwZXJjYXNlIGNoYXJhY3Rlci4NCiAgICAgIC0gY3VzdG9tX2NvbnN0cmFpbnQ6IG5vdmEua2V5cGFpcg0KICAgICAgICBkZXNjcmlwdGlvbjogQ3VzdG9tIGRlc2NyaXB0aW9uDQoNCnJlc291cmNlczoNCiAgbXlfaW5zdGFuY2UxOg0KICAgIHR5cGU6IE9TOjpOb3ZhOjpTZXJ2ZXINCiAgICBwcm9wZXJ0aWVzOg0KICAgICAgaW1hZ2U6IHsgZ2V0X3BhcmFtOiBpbWFnZV9uYW1lXzEgfQ0KICAgICAgZmxhdm9yOiBtMS5zbWFsbA0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9DQogIG15X2luc3RhbmNlMjoNCiAgICB0eXBlOiBPUzo6Tm92YTo6U2VydmVyDQogICAgcHJvcGVydGllczoNCiAgICAgIGltYWdlOiB7IGdldF9wYXJhbTogaW1hZ2VfbmFtZV8yIH0NCiAgICAgIGZsYXZvcjogbTEudGlueQ0KICAgICAgbmV0d29ya3M6DQogICAgICAgIC0gbmV0d29yayA6IHsgZ2V0X3BhcmFtIDogbmV0d29ya19pZCB9";
+ timeout = 0;
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ case SHELL_SCRIPT:
+ default: {// dummy
+ artifactName = generateUUIDforSufix() + "testArtifact.sh";
+ payloadData = "dGVzdA==";
+ artifactLabel = normalizeArtifactLabel(artifactName);
+ break;
+ }
+ }
+
+ ArtifactReqDetails artifactDetails = new ArtifactReqDetails(artifactName, artifactType, artifactDescription, payloadData, artifactLabel);
+ artifactDetails.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT.getType());
+ artifactDetails.setUrl(url);
+ artifactDetails.setTimeout(timeout);
+ artifactDetails.setArtifactDisplayName(artifactLabel);
+ return artifactDetails;
+ }
+
+ private static String getDcaeArtifactName(ArtifactTypeEnum artifactTypeEnum, String artifactType) {
+ String artifactName = null;
+ switch (artifactTypeEnum) {
+ case DCAE_INVENTORY_TOSCA: {
+ artifactName = generateUUIDforSufix() + artifactType + "_toscaSampleArtifact.yml";
+ break;
+ }
+ case DCAE_INVENTORY_JSON: {
+ artifactName = generateUUIDforSufix() + artifactType + "_jsonSampleArtifact.json";
+ break;
+ }
+ case DCAE_INVENTORY_POLICY: {
+ artifactName = generateUUIDforSufix() + artifactType + "_emfSampleArtifact.emf";
+ break;
+ }
+ case DCAE_INVENTORY_DOC: {
+ artifactName = generateUUIDforSufix() + artifactType + "_docSampleArtifact.doc";
+ break;
+ }
+ case DCAE_INVENTORY_BLUEPRINT: {
+ artifactName = generateUUIDforSufix() + artifactType + "_bluePrintSampleArtifact.xml";
+ break;
+ }
+ case DCAE_INVENTORY_EVENT: {
+ artifactName = generateUUIDforSufix() + artifactType + "_eventSampleArtifact.xml";
+ break;
+ }
+ }
+ return artifactName;
+ }
+
+ // ---------------------Audit message------------------
+ public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgSuccess() {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName());
+ expectedResourceAuditJavaObject.setResourceName("defaultImportResourceName.yaml");
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("0.1");
+ expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ expectedResourceAuditJavaObject.setStatus("201");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setToscaNodeType("");
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static ExpectedResourceAuditJavaObject getDefaultImportResourceAuditMsgFailure(ErrorInfo errorInfo, List<String> variables) {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(AuditingActionEnum.IMPORT_RESOURCE.getName());
+ expectedResourceAuditJavaObject.setResourceName("");
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("");
+ expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState("");
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ expectedResourceAuditJavaObject.setToscaNodeType("");
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgSuccess() {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName());
+ expectedResourceAuditJavaObject.setResourceName("defaultResourceName");
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("");
+ expectedResourceAuditJavaObject.setCurrVersion("0.1");
+ expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ expectedResourceAuditJavaObject.setPrevState("");
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setComment("");
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static ExpectedResourceAuditJavaObject getDefaultCertificationRequestAuditMsgFailure(ErrorInfo errorInfo, List<String> variables) {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+ expectedResourceAuditJavaObject.setAction(AuditingActionEnum.CERTIFICATION_REQUEST_RESOURCE.getName());
+ expectedResourceAuditJavaObject.setResourceName("");
+ expectedResourceAuditJavaObject.setResourceType("Resource");
+ expectedResourceAuditJavaObject.setPrevVersion("0.1");
+ expectedResourceAuditJavaObject.setCurrVersion("0.1");
+ expectedResourceAuditJavaObject.setModifierName(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getFullName());
+ expectedResourceAuditJavaObject.setModifierUid(ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ expectedResourceAuditJavaObject.setPrevState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ expectedResourceAuditJavaObject.setCurrState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.toString());
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedResourceAuditJavaObject.setDesc(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ expectedResourceAuditJavaObject.setComment("");
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultExternalAuditObject(AssetTypeEnum assetType, AuditingActionEnum action, String query) {
+
+ ExpectedExternalAudit expectedExternalAudit = new ExpectedExternalAudit();
+ expectedExternalAudit.setACTION(action.getName());
+ expectedExternalAudit.setCONSUMER_ID("ci");
+ expectedExternalAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + (query == null ? "" : query));
+ expectedExternalAudit.setSTATUS("200");
+ expectedExternalAudit.setDESC("OK");
+ return expectedExternalAudit;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultAssetListAudit(AssetTypeEnum assetType, AuditingActionEnum auditAction) {
+
+ // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
+ // ExpectedExternalAudit();
+ ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, auditAction, null);
+ return expectedAssetListAuditJavaObject;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultFilteredAssetListAudit(AssetTypeEnum assetType, String query) {
+
+ // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
+ // ExpectedExternalAudit();
+ ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query);
+ return expectedAssetListAuditJavaObject;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID) {
+
+ // ExpectedExternalAudit expectedExternalArtifactAudit = new
+ // ExpectedExternalAudit();
+
+ ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null);
+ expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater()));
+ expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID("");
+ expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID());
+ expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition));
+ expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts");
+ return expectedExternalArtifactAudit;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultExternalArtifactAuditSuccess(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, String resourceInstanceName) {
+
+ ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditSuccess(assetType, action, artifactDefinition, componentUUID);
+ expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ return expectedExternalArtifactAudit;
+ }
+
+ public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List<String> variables) {
+
+ // ExpectedExternalAudit expectedExternalArtifactAudit = new
+ // ExpectedExternalAudit();
+
+ ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalAuditObject(assetType, action, null);
+ expectedExternalArtifactAudit.setMODIFIER(AuditValidationUtils.getModifierString(artifactDefinition.getUpdaterFullName(), artifactDefinition.getUserIdLastUpdater()));
+ expectedExternalArtifactAudit.setPREV_ARTIFACT_UUID("");
+ expectedExternalArtifactAudit.setCURR_ARTIFACT_UUID(artifactDefinition.getArtifactUUID());
+ expectedExternalArtifactAudit.setARTIFACT_DATA(AuditValidationUtils.buildArtifactDataAudit(artifactDefinition));
+ expectedExternalArtifactAudit.setRESOURCE_URL(expectedExternalArtifactAudit.getRESOURCE_URL() + "/" + componentUUID + "/artifacts");
+ expectedExternalArtifactAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedExternalArtifactAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ return expectedExternalArtifactAudit;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultExternalArtifactAuditFailure(AssetTypeEnum assetType, AuditingActionEnum action, ArtifactDefinition artifactDefinition, String componentUUID, ErrorInfo errorInfo, List<String> variables,
+ String resourceInstanceName) {
+
+ ExpectedExternalAudit expectedExternalArtifactAudit = getDefaultExternalArtifactAuditFailure(assetType, action, artifactDefinition, componentUUID, errorInfo, variables);
+ expectedExternalArtifactAudit.setRESOURCE_URL("/asdc/v1/catalog/" + assetType.getValue() + "/" + componentUUID + "/resourceInstances/" + resourceInstanceName + "/artifacts");
+ return expectedExternalArtifactAudit;
+ }
+
+ public static ExpectedExternalAudit getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum assetType, String query, String category) {
+
+ // ExpectedExternalAudit expectedAssetListAuditJavaObject = new
+ // ExpectedExternalAudit();
+ ExpectedExternalAudit expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_FILTERED_ASSET_LIST, query);
+ expectedAssetListAuditJavaObject.setSTATUS("404");
+ ErrorInfo errorInfo = null;
+ try {
+ errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+ } catch (FileNotFoundException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ String desc = (errorInfo.getMessageId() + ": " + errorInfo.getMessage()).replace("%2", "category").replace("%3", category).replace("%1", "resource");
+ expectedAssetListAuditJavaObject.setDESC(desc);
+
+ return expectedAssetListAuditJavaObject;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultAssetMetadataAudit(AssetTypeEnum assetType, Component component) {
+
+ ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit();
+ expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null);
+ expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + component.getUUID() + "/metadata");
+ expectedAssetListAuditJavaObject.setRESOURCE_NAME(component.getName());
+ expectedAssetListAuditJavaObject.setRESOURCE_TYPE(component.getComponentType().getValue());
+ expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(component.getUUID());
+ return expectedAssetListAuditJavaObject;
+
+ }
+
+ public static ExpectedExternalAudit getDefaultAssetMetadataAuditFailure(AssetTypeEnum assetType, String serviceUuid, String resourceType) {
+
+ ExpectedExternalAudit expectedAssetListAuditJavaObject = new ExpectedExternalAudit();
+ expectedAssetListAuditJavaObject = getDefaultExternalAuditObject(assetType, AuditingActionEnum.GET_ASSET_METADATA, null);
+ expectedAssetListAuditJavaObject.setSTATUS("404");
+ expectedAssetListAuditJavaObject.setDESC("OK");
+ expectedAssetListAuditJavaObject.setRESOURCE_URL(expectedAssetListAuditJavaObject.getRESOURCE_URL() + "/" + serviceUuid + "/metadata");
+ expectedAssetListAuditJavaObject.setRESOURCE_TYPE(resourceType);
+ expectedAssetListAuditJavaObject.setSERVICE_INSTANCE_ID(serviceUuid);
+ return expectedAssetListAuditJavaObject;
+
+ }
+
+ // Category/Subcategory/Group
+ public static CategoryDefinition getDefaultCategory() {
+ CategoryDefinition productCategoryDefinition = new CategoryDefinition();
+ productCategoryDefinition.setName("Category1");
+ return productCategoryDefinition;
+ }
+
+ public static SubCategoryDefinition getDefaultSubCategory() {
+ SubCategoryDefinition productSubCategoryDefinition = new SubCategoryDefinition();
+ productSubCategoryDefinition.setName("SubCategory1");
+ return productSubCategoryDefinition;
+ }
+
+ public static GroupingDefinition getDefaultGroup() {
+ GroupingDefinition productGroupDefinition = new GroupingDefinition();
+ productGroupDefinition.setName("Grouping1");
+ return productGroupDefinition;
+ }
+
+ // Product
+
+ public static ProductReqDetails getDefaultProduct() {
+ return createDefaultProductReqDetails("Product1", null);
+ }
+
+ public static ProductReqDetails getDefaultProduct(String name) {
+ return createDefaultProductReqDetails(name, null);
+ }
+
+ public static ProductReqDetails getDefaultProduct(CategoryDefinition category) {
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ return createDefaultProductReqDetails("CiProduct1", categories);
+ }
+
+ public static ProductReqDetails getDefaultProduct(String name, CategoryDefinition category) {
+ List<CategoryDefinition> categories = new ArrayList<>();
+ categories.add(category);
+ return createDefaultProductReqDetails(name, categories);
+ }
+
+ public static ProductReqDetails getDefaultProduct(List<CategoryDefinition> categories) {
+ return createDefaultProductReqDetails("CiProduct1", categories);
+ }
+
+ public static ProductReqDetails getDefaultProduct(String name, List<CategoryDefinition> categories) {
+ return createDefaultProductReqDetails(name, categories);
+ }
+
+ private static ProductReqDetails createDefaultProductReqDetails(String name, List<CategoryDefinition> categories) {
+ ProductReqDetails product = new ProductReqDetails(name);
+ ArrayList<String> tags = new ArrayList<String>();
+ tags.add(name);
+ product.setTags(tags);
+ product.setProjectCode("12345");
+ product.setIcon("myIcon");
+ ArrayList<String> contacts = new ArrayList<String>();
+ // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST1).getUserId());
+ // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_STRATEGIST2).getUserId());
+ contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER1).getUserId());
+ // contacts.add(ElementFactory.getDefaultUser(UserRoleEnum.PRODUCT_MANAGER2).getUserId());
+ product.setContacts(contacts);
+ product.setCategories(categories);
+ String fullName = "This is my full name: " + name;
+ product.setFullName(fullName);
+ String description = "This is product description";
+ product.setDescription(description);
+ return product;
+ }
+
+ public static RequirementCapabilityRelDef getReqCapRelation(String fromCompInstId, String toCompInstId, String reqOwnerId, String capOwnerId, String capType, String reqCapName, List<CapabilityDefinition> capList,
+ List<RequirementDefinition> reqList) {
+ RequirementCapabilityRelDef requirementDef = new RequirementCapabilityRelDef();
+ requirementDef.setFromNode(fromCompInstId);
+ requirementDef.setToNode(toCompInstId);
+ RequirementAndRelationshipPair pair = new RequirementAndRelationshipPair();
+ pair.setRequirementOwnerId(reqOwnerId);
+ pair.setCapabilityOwnerId(capOwnerId);
+ pair.setRequirement(reqCapName);
+ RelationshipImpl relationship = new RelationshipImpl();
+ relationship.setType(capType);
+ pair.setRelationships(relationship);
+ pair.setCapabilityUid(capList.get(0).getUniqueId());
+ pair.setRequirementUid(reqList.get(0).getUniqueId());
+ List<RequirementAndRelationshipPair> relationships = new ArrayList<>();
+ relationships.add(pair);
+ requirementDef.setRelationships(relationships);
+ return requirementDef;
+ }
+
+ private static String generateUUIDforSufix() {
+
+ String uniqueSufix = UUID.randomUUID().toString();
+ String[] split = uniqueSufix.split("-");
+ return uniqueSufix = split[4];
+ }
+
+ private static String normalizeArtifactLabel(String label) {
+
+ label = label.substring(0, label.indexOf("."));
+ String normalizedLabel = ValidationUtils.normalizeArtifactLabel(label);
+ return normalizedLabel.substring(0, Math.min(25, normalizedLabel.length()));
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
new file mode 100644
index 0000000000..b785563a4d
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileUtils.java
@@ -0,0 +1,136 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import fj.data.Either;
+
+public class FileUtils {
+
+ static Logger logger = LoggerFactory.getLogger(Utils.class.getName());
+
+ public static void writeToFile(String filePath, String content) {
+ try {
+ Files.write(Paths.get(filePath), content.getBytes());
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static String getFileName(String fullyQualified) {
+ String fileName = fullyQualified;
+
+ int i = fullyQualified.lastIndexOf('.');
+ if (i > 0) {
+ fileName = fullyQualified.substring(i + 1);
+ }
+ return fileName;
+
+ }
+
+ public static Either<String, Exception> getFileContentUTF8(String filePath) {
+ Either<String, Exception> eitherResult;
+ try {
+ String content = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
+ eitherResult = Either.left(content);
+ } catch (Exception e) {
+ eitherResult = Either.right(e);
+ }
+ return eitherResult;
+ }
+
+ public static List<String> getFileListFromBaseDirectoryByTestName(String testResourcesPath) {
+
+ File file = new File(testResourcesPath);
+ File[] listFiles = file.listFiles();
+ if (listFiles != null) {
+ List<String> listFileName = new ArrayList<String>();
+ for (File newFile : listFiles) {
+ if (newFile.isFile()) {
+ listFileName.add(newFile.getPath());
+ }
+ }
+ return listFileName;
+ }
+ assertTrue("directory " + testResourcesPath + " is empty", false);
+ return null;
+ }
+
+ public static String getFilePathFromListByPattern(List<String> fileList, String pattern) {
+
+ for (String filePath : fileList) {
+ if (filePath.contains(pattern)) {
+ return filePath;
+ }
+ }
+ return null;
+ }
+
+ public static String loadPayloadFileFromListUsingPosition(List<String> listFileName, String pattern, Boolean isBase64, int positionInList) throws IOException {
+ List<String> newList = new ArrayList<String>(Arrays.asList(listFileName.get(positionInList)));
+ return loadPayloadFile(newList, pattern, isBase64);
+ }
+
+ public static String loadPayloadFile(List<String> listFileName, String pattern, Boolean isBase64) throws IOException {
+ String fileName;
+ String payload = null;
+ fileName = FileUtils.getFilePathFromListByPattern(listFileName, pattern);
+ logger.debug("fileName: {}", fileName);
+
+ if (fileName != null) {
+ payload = Decoder.readFileToString(fileName);
+ if (isBase64) {
+ payload = Decoder.encode(payload.getBytes());
+ }
+ } else {
+ assertTrue("file to upload not found", false);
+ }
+ return payload;
+ }
+
+ public static String getFileNameFromPath(String testResourcesPath) {
+
+ File file = new File(testResourcesPath);
+ String fileName = null;
+ if (file.exists()) {
+ return file.getName();
+ } else {
+ assertTrue("file to upload not found", false);
+ }
+ return fileName;
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
new file mode 100644
index 0000000000..040cdba444
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ImportUtils.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.general;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+
+public class ImportUtils {
+
+ public static ImportReqDetails getImportResourceDetailsByPathAndName(ImportReqDetails importReqDetails, String filePath, String fileName) throws IOException {
+
+ // ImportReqDetails importReqDetails;
+ // User sdncUserDetails;
+ // String testResourcesPath;
+ // ResourceReqDetails resourceDetails;
+ // Config config;
+ // config = Utils.getConfig();
+ //
+ // importReqDetails = ElementFactory.getDefaultImportResource();
+ // User sdncUserDetails =
+ // ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ // ResourceReqDetails resourceDetails =
+ // ElementFactory.getDefaultResource();
+ // String sourceDir = config.getResourceConfigDir();
+ // String testResourcesPath = sourceDir + File.separator + workDir;
+ // final String workDir = "importToscaResourceByCreateUrl";
+
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(filePath);
+ importReqDetails.setPayloadName(fileName);
+ String payloadData = FileUtils.loadPayloadFile(listFileName, fileName, true);
+ importReqDetails.setPayloadData(payloadData);
+
+ return importReqDetails;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
new file mode 100644
index 0000000000..4360621364
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ArtifactRestUtils.java
@@ -0,0 +1,689 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openecomp.sdc.common.util.ValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.AssertJUnit;
+
+import com.google.gson.Gson;
+
+public class ArtifactRestUtils extends BaseRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(ArtifactRestUtils.class.getName());
+
+ // External API
+ // Upload Artifact of the asset
+ public static RestResponse externalAPIUploadArtifactOfTheAsset(Component component, User user, ArtifactReqDetails artifactReqDetails) throws IOException {
+ Config config = Utils.getConfig();
+ String resourceType = null;
+ String resourceUUID = component.getUUID();
+
+ System.out.println(component.getComponentType());
+
+ if (component.getComponentType().toString().toLowerCase().equals("resource")) {
+ resourceType = "resources";
+ } else {
+ resourceType = "services";
+ }
+
+ String url = String.format(Urls.POST_EXTERNAL_API_UPLOAD_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceType, resourceUUID);
+
+ return uploadInformationalArtifact(artifactReqDetails, user, calculateChecksum(artifactReqDetails), url);
+ }
+
+ //
+ // Testing
+ //
+ public static RestResponse getResourceDeploymentArtifactExternalAPI(String resourceUUID, String artifactUUID, User sdncModifierDetails, String resourceType) throws IOException {
+ Config config = Utils.getConfig();
+ String url = null;
+
+ if (resourceType.equals("Service")) {
+ url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
+
+ } else {
+ url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_ASSET, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, artifactUUID);
+ }
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ HttpRequest http = new HttpRequest();
+
+ logger.debug("Send GET request to get Resource Assets: {}", url);
+ System.out.println("Send GET request to get Resource Assets: " + url);
+
+ logger.debug("Request headers: {}", headersMap);
+ System.out.println("Request headers: " + headersMap);
+
+ RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
+
+ return sendGetResourceAssets;
+
+ }
+
+ public static RestResponse getComponentInstanceDeploymentArtifactExternalAPI(String resourceUUID, String componentInstanceUID, String artifactUUID, User sdncModifierDetails, String resourceType) throws IOException {
+ Config config = Utils.getConfig();
+ String url = null;
+
+ if (resourceType.equals("Service")) {
+ url = String.format(Urls.GET_DOWNLOAD_SERVICE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentInstanceUID, artifactUUID);
+
+ } else {
+ url = String.format(Urls.GET_DOWNLOAD_RESOURCE_ARTIFACT_OF_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUUID, componentInstanceUID, artifactUUID);
+ }
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ HttpRequest http = new HttpRequest();
+
+ logger.debug("Send GET request to get Resource Assets: {}", url);
+ System.out.println("Send GET request to get Resource Assets: " + url);
+
+ logger.debug("Request headers: {}", headersMap);
+ System.out.println("Request headers: " + headersMap);
+
+ RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
+
+ return sendGetResourceAssets;
+
+ }
+
+ // *********** SERVICE ****************
+ public static RestResponse getArtifactTypesList() throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ }
+
+ public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid) throws IOException {
+ return addInformationalArtifactToService(artifactDetails, sdncModifierDetails, serviceUid, calculateChecksum(artifactDetails));
+ }
+
+ public static RestResponse addInformationalArtifactToService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String checksum) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.ADD_ARTIFACT_TO_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid);
+
+ return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url);
+ }
+
+ public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception {
+
+ return downloadServiceArtifact(service, artifact, user, addionalHeaders, true);
+ }
+
+ public static RestResponse downloadServiceArtifact(ServiceReqDetails service, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws Exception {
+ Config config = Utils.getConfig();
+ String relativeUrl = encodeUrlForDownload(
+ String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName())));
+ String fullUrl = String.format(Urls.DOWNLOAD_SERVICE_ARTIFACT_FULL_URL, config.getCatalogBeHost(), config.getCatalogBePort(), relativeUrl);
+
+ return downloadArtifact(fullUrl, user, addionalHeaders, addEcompHeader);
+ }
+
+ public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders) throws Exception {
+ return downloadResourceArtifact(service, resource, artifact, user, addionalHeaders, true);
+ }
+
+ public static RestResponse downloadResourceArtifact(ServiceReqDetails service, ResourceReqDetails resource, ArtifactReqDetails artifact, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws Exception {
+ Config config = Utils.getConfig();
+ String relativeUrl = encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_RESOURCE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(service.getName()), service.getVersion(),
+ ValidationUtils.convertToSystemName(resource.getName()), resource.getVersion(), ValidationUtils.normalizeFileName(artifact.getArtifactName())));
+ String fullUrl = String.format(Urls.DOWNLOAD_RESOURCE_ARTIFACT_FULL_URL, config.getCatalogBeHost(), config.getCatalogBePort(), relativeUrl);
+
+ return downloadArtifact(fullUrl, user, addionalHeaders, addEcompHeader);
+ }
+
+ public static RestResponse downloadResourceInstanceArtifact(String serviceUniqueId, String resourceInstanceId, User user, String artifactUniqeId) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DOWNLOAD_COMPONENT_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUniqueId, resourceInstanceId, artifactUniqeId);
+ RestResponse res = sendGet(url, user.getUserId(), null);
+ return res;
+ }
+
+ ////
+
+ // update
+
+ public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod) throws IOException {
+ // TODO Auto-generated method stub
+ return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactUid, sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
+ }
+
+ public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, User sdncModifierDetails, String httpMethod) throws IOException {
+ // TODO Auto-generated method stub
+ return updateInformationalArtifactOfServiceByMethod(artifactReqDetails, serviceUid, artifactReqDetails.getUniqueId(), sdncModifierDetails, httpMethod, calculateChecksum(artifactReqDetails));
+ }
+
+ public static RestResponse downloadResourceArtifactInternalApi(String resourceId, User user, String artifactUniqeId) throws Exception {
+ return downloadComponentArtifactInternalApi(resourceId, user, artifactUniqeId, Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT);
+ }
+
+ public static RestResponse downloadServiceArtifactInternalApi(String componentId, User user, String artifactUniqeId) throws Exception {
+ return downloadComponentArtifactInternalApi(componentId, user, artifactUniqeId, Urls.UI_DOWNLOAD_SERVICE_ARTIFACT);
+ }
+
+ public static RestResponse downloadComponentArtifactInternalApi(String componentId, User user, String artifactUniqeId, String urlTemplate) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(urlTemplate, config.getCatalogBeHost(), config.getCatalogBePort(), componentId, artifactUniqeId);
+ RestResponse res = sendGet(url, user.getUserId(), null);
+ return res;
+ }
+
+ /*
+ * public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException { return
+ * updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true); }
+ *
+ * public static RestResponse updateInformationalArtifactMetadataOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException { return
+ * updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateChecksum(artifactDetails), false); }
+ *
+ * public static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException { Config config =
+ * Utils.getConfig(); Map<String, String> headersMap = getHeadersMap(sdncModifierDetails);
+ *
+ * if (isPayloadUpdate){ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum); }
+ *
+ * Gson gson = new Gson(); String jsonBody = gson.toJson(artifactDetails);
+ *
+ * HttpRequest http = new HttpRequest();
+ *
+ * String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(),config.getCatalogBePort(), serviceUid, artifactUid); RestResponse res = http.httpSendPost(url, jsonBody, headersMap);
+ * System.out.println("update artifact was finished with response: "+ res.getErrorCode()); return res; }
+ */
+
+ public static RestResponse updateInformationalArtifactOfServiceByMethod(ArtifactReqDetails artifactReqDetails, String serviceUid, String artifactUid, User sdncModifierDetails, String httpMethod, String checksum) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = getHeadersMap(sdncModifierDetails);
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(artifactReqDetails);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid, artifactUid);
+ RestResponse updateResourceResponse = http.httpSendByMethod(url, httpMethod, userBodyJson, headersMap);
+ // System.out.println("update artifact was finished with response: "+
+ // updateResourceResponse.getErrorCode());
+
+ return updateResourceResponse;
+ }
+
+ public static Map<String, String> getHeadersMap(User sdncModifierDetails) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptJsonHeader);
+
+ try {
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ } catch (Exception e) {
+
+ }
+
+ return headersMap;
+ }
+
+ // *********** RESOURCE ****************
+ // add
+ public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException {
+ return addInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails));
+ }
+
+ public static RestResponse explicitAddInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException {
+ Config config = Utils.getConfig();
+
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid);
+
+ return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
+ }
+
+ public static RestResponse addInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException {
+ Config config = Utils.getConfig();
+
+ if (artifactDetails.getArtifactGroupType() != null && artifactDetails.getArtifactGroupType().equals(ArtifactGroupTypeEnum.DEPLOYMENT.getType())) {
+ // YANG_XML and OTHER deployment artifact should be added through
+ // this API, not updated
+ String artifactType = artifactDetails.getArtifactType();
+ if (!(ArtifactTypeEnum.YANG_XML.getType().equals(artifactType) || ArtifactTypeEnum.OTHER.getType().equals(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equals(artifactType)
+ || ArtifactTypeEnum.VF_LICENSE.getType().equals(artifactType) || ArtifactTypeEnum.VENDOR_LICENSE.getType().equals(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equals(artifactType)
+ || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equals(artifactType) || ArtifactTypeEnum.APPC_CONFIG.getType().equals(artifactType))) {
+ // return updateInformationalArtifactToResource(artifactDetails,
+ // sdncModifierDetails, resourceUid);
+ }
+ }
+ String url = String.format(Urls.ADD_ARTIFACT_TO_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid);
+
+ return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, checksum, url);
+ }
+
+ // update
+ public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException {
+ return updateInformationalArtifactToResource(artifactDetails, sdncModifierDetails, resourceUid, calculateChecksum(artifactDetails));
+ }
+
+ public static RestResponse updateInformationalArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String checksum) throws IOException {
+ Config config = Utils.getConfig();
+ if (artifactDetails.getArtifactGroupType() != null && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")) {
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid);
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
+ artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
+ artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
+
+ }
+
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
+
+ return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
+ }
+
+ public static RestResponse uploadArtifactToPlaceholderOnResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid, String placeHolderLabel) throws IOException {
+ Config config = Utils.getConfig();
+ if (artifactDetails.getArtifactLabel() != null && !artifactDetails.getArtifactLabel().isEmpty()) {
+ RestResponse resourceGetResponse = ResourceRestUtils.getResource(sdncModifierDetails, resourceUid);
+ Resource resourceRespJavaObject = ResponseParser.convertResourceResponseToJavaObject(resourceGetResponse.getResponse());
+ Map<String, ArtifactDefinition> deploymentArtifacts = resourceRespJavaObject.getDeploymentArtifacts();
+ ArtifactDefinition artifactDefinition = deploymentArtifacts.get(artifactDetails.getArtifactLabel());
+ AssertJUnit.assertNotNull(artifactDefinition);
+ artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
+ artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
+
+ }
+
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
+
+ return uploadInformationalArtifact(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
+ }
+
+ public static RestResponse updateDeploymentArtifactToResource(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceUid) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactDetails.getUniqueId());
+
+ return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
+ }
+
+ public static RestResponse updateArtifactToResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDefinition.getUniqueId());
+ return updateDeploymentArtifact(artifactDefinition, sdncModifierDetails, url);
+ }
+
+ public static RestResponse updateDeploymentArtifactToRI(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE_INSTANCE_HEAT_ENV_PARAMS, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId());
+ return updateDeploymentArtifact(artifactDetails, sdncModifierDetails, url);
+ }
+
+ // delete
+ public static RestResponse deleteArtifactFromResourceInstance(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String resourceUid, String serviceId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceUid, artifactDefinition.getUniqueId());
+ return sendDelete(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, ArtifactReqDetails artifactDetails, User sdncModifierDetails) throws IOException {
+ return deleteInformationalArtifactFromResource(resourceUid, artifactDetails.getUniqueId(), sdncModifierDetails);
+ }
+
+ public static RestResponse deleteInformationalArtifactFromResource(String resourceUid, String artifactId, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceUid, artifactId);
+ return sendDelete(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse deleteServiceApiArtifact(ArtifactReqDetails artifactDetails, String serviceUniqueId, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_DELETE_SERVICE_API_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUniqueId, artifactDetails.getUniqueId());
+ RestResponse res = sendDelete(url, user.getUserId());
+ logger.debug("Deleting api artifact was finished with response: {}", res.getErrorCode());
+ logger.debug("Response body: {}", res.getResponseMessage());
+ return res;
+ }
+
+ // *************** RESOURCE INSTANCE **************
+ /**
+ * Add DCAE artifacts to resource instance.
+ *
+ * @param artifactDetails
+ * @param sdncModifierDetails
+ * @param resourceInstanceId
+ * @param serviceId
+ * @return
+ * @throws IOException
+ */
+ public static RestResponse addArtifactToResourceInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String resourceInstanceId, String serviceId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.ADD_RESOURCE_INSTANCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId, resourceInstanceId, artifactDetails.getUniqueId());
+ return addArtifactToInstance(artifactDetails, sdncModifierDetails, calculateChecksum(artifactDetails), url);
+ }
+
+ // *************** COMPONENT **************
+
+ public static RestResponse uploadDeploymentArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+ Map<String, String> additionalHeaders = null;
+ String checksum = ResponseParser.calculateMD5Header(artifactDetails);
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+
+ ComponentTypeEnum componentType = component.getComponentType();
+
+ String url = null;
+
+ switch (componentType) {
+
+ case RESOURCE: {
+ url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), artifactDetails.getUniqueId());
+
+ break;
+ }
+ case SERVICE: {
+
+ break;
+ }
+
+ case PRODUCT: {
+
+ break;
+ }
+
+ default: {// dummy
+ assertTrue("failed on enum selection", false);
+
+ break;
+ }
+ }
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+ // System.out.println("ArtifactDetails: "+ jsonBody);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
+ if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
+ artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ }
+ // System.out.println("Add artifact was finished with response: "+
+ // res.getErrorCode());
+ return res;
+ }
+
+ public static RestResponse uploadArtifact(ArtifactReqDetails artifactDetails, Component component, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+ List<String> placeHolderlst = Utils.getListOfResPlaceHoldersDepArtTypes();
+ Map<String, String> additionalHeaders = null;
+ String checksum = null;
+ String url = null;
+ //
+ //
+ // if (artifactDetails.getArtifactGroupType() != null
+ // && artifactDetails.getArtifactGroupType().equals("DEPLOYMENT")
+ // && placeHolderlst.contains(artifactDetails.getArtifactType())) {
+ // Map<String, ArtifactDefinition> deploymentArtifacts =
+ // component.getDeploymentArtifacts();
+ // ArtifactDefinition artifactDefinition =
+ // deploymentArtifacts.get(artifactDetails.getArtifactLabel());
+ // artifactDetails.setUniqueId(artifactDefinition.getUniqueId());
+ // artifactDetails.setArtifactLabel(artifactDefinition.getArtifactLabel());
+ // checksum = ResponseParser.calculateMD5Header(artifactDetails);
+ // additionalHeaders = new HashMap<String, String>();
+ // additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(),
+ // checksum);
+ // url = String.format(Urls.UPDATE_ARTIFACT_OF_COMPONENT,
+ // config.getCatalogBeHost(),
+ // config.getCatalogBePort(),
+ // ComponentTypeEnum.findParamByType(component.getComponentType()),
+ // component.getUniqueId(), artifactDetails.getUniqueId());
+ // }
+ //
+ // else {
+ checksum = ResponseParser.calculateMD5Header(artifactDetails);
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+ url = String.format(Urls.UPLOAD_DELETE_ARTIFACT_OF_COMPONENT, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), artifactDetails.getUniqueId());
+ // }
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+ // System.out.println("ArtifactDetails: "+ jsonBody);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
+ if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
+ artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ }
+ // System.out.println("Add artifact was finished with response: "+
+ // res.getErrorCode());
+ return res;
+ }
+
+ // *************** PRIVATE **************
+ private static RestResponse uploadInformationalArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
+ Map<String, String> additionalHeaders = null;
+ if (checksum != null && !checksum.isEmpty()) {
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+ }
+
+ additionalHeaders.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader);
+ additionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ Gson gson = new Gson();
+ // System.out.println("ArtifactDetails: "+ jsonBody);
+ String jsonBody = gson.toJson(artifactDetails);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), acceptHeaderData, additionalHeaders);
+ if ((res.getErrorCode() == STATUS_CODE_SUCCESS) || (res.getErrorCode() == STATUS_CODE_CREATED)) {
+ artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ }
+ // System.out.println("Add artifact was finished with response: "+
+ // res.getErrorCode());
+ return res;
+ }
+
+ private static RestResponse addArtifactToInstance(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String checksum, String url) throws IOException {
+ Map<String, String> additionalHeaders = null;
+ additionalHeaders = new HashMap<String, String>();
+ if (checksum != null && !checksum.isEmpty()) {
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+ }
+ additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
+ additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
+ if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
+ artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ }
+ return res;
+ }
+
+ private static RestResponse updateDeploymentArtifact(ArtifactDefinition artifactDefinition, User sdncModifierDetails, String url) throws IOException {
+ Map<String, String> additionalHeaders = null;
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
+ additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDefinition);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
+ return res;
+ }
+
+ private static RestResponse updateDeploymentArtifact(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String url) throws IOException {
+ Map<String, String> additionalHeaders = null;
+
+ additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json, text/plain, */*");
+ additionalHeaders.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json;charset=UTF-8");
+ // additionalHeaders.put(HttpHeaderEnum..getValue(),
+ // "application/json;charset=UTF-8");
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+ // System.out.println("ArtifactDetails: "+ jsonBody);
+
+ RestResponse res = sendPost(url, jsonBody, sdncModifierDetails.getUserId(), "application/json, text/plain, */*", additionalHeaders);
+ if (res.getErrorCode() == STATUS_CODE_SUCCESS) {
+ artifactDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ }
+ // System.out.println("Add artifact was finished with response: "+
+ // res.getErrorCode());
+ return res;
+ }
+
+ private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders, boolean addEcompHeader) throws IOException {
+ if (addEcompHeader) {
+ addionalHeaders.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), ecomp);
+ }
+ return downloadArtifact(url, user, addionalHeaders, acceptOctetStream);
+ }
+
+ private static RestResponse downloadArtifact(String url, User user, Map<String, String> addionalHeaders, String accept) throws IOException {
+ addionalHeaders.put(HttpHeaderEnum.ACCEPT.getValue(), accept);
+
+ RestResponse res = sendGet(url, user.getUserId(), addionalHeaders);
+ // System.out.println("download artifact was finished with response: "+
+ // res.getErrorCode());
+ // System.out.println("response is: " + res.getResponse());
+ return res;
+ }
+
+ private static Map<String, Map<String, Object>> getArtifactsListFromResponse(String jsonResponse, String fieldOfArtifactList) {
+ JSONObject object = (JSONObject) JSONValue.parse(jsonResponse);
+ Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) object.get(fieldOfArtifactList);
+ return map;
+ }
+
+ public static String calculateChecksum(ArtifactReqDetails artifactDetails) {
+ String checksum = null;
+ if (artifactDetails.getPayload() != null) {
+ checksum = ResponseParser.calculateMD5Header(artifactDetails);
+ }
+ return checksum;
+ }
+
+ public static String encodeUrlForDownload(String url) {
+
+ return url.replaceAll(" ", "%20");
+ }
+
+ public static String getPartialUrlByArtifactName(ServiceReqDetails serviceDetails, String serviceVersion, String artifactName) {
+ return encodeUrlForDownload(String.format(Urls.DISTRIB_DOWNLOAD_SERVICE_ARTIFACT_RELATIVE_URL, ValidationUtils.convertToSystemName(serviceDetails.getName()), serviceVersion, artifactName));
+ }
+
+ public static String getUniqueIdOfArtifact(RestResponse createResponse, String artifactField, String requieredArtifactLabel) throws Exception {
+ Map<String, Object> artifact = getArtifactFromRestResponse(createResponse, artifactField, requieredArtifactLabel);
+ assertNotNull(artifact);
+ return artifact.get("uniqueId").toString();
+ }
+
+ public static Map<String, Object> getArtifactFromRestResponse(RestResponse response, String artifactField, String requieredArtifactLabel) {
+ Map<String, Map<String, Object>> map = getArtifactsListFromResponse(response.getResponse(), artifactField);
+ return map.get(requieredArtifactLabel);
+ }
+
+ public static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid) throws IOException {
+ return updateInformationalArtifactPayloadOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, calculateMD5Header(artifactDetails));
+ }
+
+ private static RestResponse updateInformationalArtifactPayloadOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum) throws IOException {
+ return updateInformationalArtifactOfService(artifactDetails, sdncModifierDetails, serviceUid, artifactUid, checksum, true);
+ }
+
+ private static RestResponse updateInformationalArtifactOfService(ArtifactReqDetails artifactDetails, User sdncModifierDetails, String serviceUid, String artifactUid, String checksum, boolean isPayloadUpdate) throws IOException {
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
+
+ if (isPayloadUpdate) {
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), checksum);
+ }
+
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+
+ HttpRequest http = new HttpRequest();
+
+ String url = String.format(Urls.UPDATE_OR_DELETE_ARTIFACT_OF_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceUid, artifactUid);
+ RestResponse res = http.httpSendPost(url, jsonBody, headersMap);
+ // System.out.println("update artifact was finished with response: "+
+ // res.getErrorCode());
+ return res;
+ }
+
+ public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+ // calculate MD5 for json body
+ return calculateMD5(jsonBody);
+
+ }
+
+ public static String calculateMD5(String data) {
+ String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
+ // encode base-64 result
+ byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
+ String encodeBase64Str = new String(encodeBase64);
+ return encodeBase64Str;
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
new file mode 100644
index 0000000000..51bd2162c0
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/AssetRestUtils.java
@@ -0,0 +1,510 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.AssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceInstanceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public class AssetRestUtils extends BaseRestUtils {
+ static Gson gson = new Gson();
+ static ObjectMapper objectMapper = new ObjectMapper();
+
+ static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
+ static final String contentTypeHeaderData = "application/json";
+ static final String acceptHeaderDate = "application/json";
+ static final String basicAuthentication = "Basic Y2k6MTIzNDU2";
+ // /asdc/v1/catalog/{services/resources}/{componentUUID}/artifacts/{artifactUUID}
+ static final String COMPONENT_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/artifacts/%s";
+ // /asdc/v1/catalog/{services/resources}/{componentUUID}/resourceInstances/{resourceInstanceName}/artifacts/{artifactUUID}
+ static final String RESOURCE_INSTANCE_ARTIFACT_URL = "/asdc/v1/catalog/%s/%s/resourceInstances/%s/artifacts/%s";
+
+ public static HttpResponse getComponentToscaModel(AssetTypeEnum assetType, String uuid) throws IOException {
+ Config config = Utils.getConfig();
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ String url = String.format(Urls.GET_TOSCA_MODEL, config.getCatalogBeHost(), config.getCatalogBePort(),
+ assetType.getValue(), uuid);
+ HttpGet httpGet = new HttpGet(url);
+
+ httpGet.addHeader(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+ httpGet.addHeader(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
+
+ logger.debug("Send GET request to get Tosca model: {}", url);
+
+ return httpclient.execute(httpGet);
+ }
+
+ public static RestResponse getComponentListByAssetType(boolean isBasicAuthentication, AssetTypeEnum assetType,
+ String... filterArrayString) throws IOException {
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ if (isBasicAuthentication) {
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
+ }
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
+ assetType.getValue());
+ if (filterArrayString != null && filterArrayString.length > 0) {
+ url = buildUrlWithFilter(url, filterArrayString);
+ }
+
+ RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
+
+ return sendGetResourceAssets;
+ }
+
+ public static RestResponse getFilteredComponentList(AssetTypeEnum assetType, String query) throws IOException {
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ HttpRequest http = new HttpRequest();
+
+ String url = String.format(Urls.GET_FILTERED_ASSET_LIST, config.getCatalogBeHost(), config.getCatalogBePort(),
+ assetType.getValue(), query);
+
+ logger.debug("Send GET request to get Resource Assets: {}", url);
+ logger.debug("Request headers: {}", headersMap);
+
+ RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
+
+ return sendGetResourceAssets;
+ }
+
+ public static String buildUrlWithFilter(String url, String[] filterArrayString) {
+ StringBuilder sb = new StringBuilder();
+ int length = filterArrayString.length;
+ int count = 0;
+ for (String filterString : filterArrayString) {
+ sb.append(filterString);
+ count++;
+ if (length != count) {
+ sb.append("&");
+ }
+ }
+ return url + "?" + sb;
+ }
+
+ public static RestResponse getAssetMetadataByAssetTypeAndUuid(boolean isBasicAuthentication,
+ AssetTypeEnum assetType, String uuid) throws IOException {
+
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ if (isBasicAuthentication) {
+ headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication);
+ }
+ headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci");
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ASSET_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ assetType.getValue(), uuid);
+
+ logger.debug("Send GET request to get Resource Assets: {}", url);
+ logger.debug("Request headers: {} ", headersMap);
+
+ RestResponse sendGetResourceAssets = http.httpSendGet(url, headersMap);
+
+ return sendGetResourceAssets;
+ }
+
+ public static List<ResourceAssetStructure> getResourceAssetList(RestResponse assetResponse) {
+ List<ResourceAssetStructure> resourceAssetList = new ArrayList<>();
+
+ JsonElement jelement = new JsonParser().parse(assetResponse.getResponse());
+ JsonArray componenetArray = (JsonArray) jelement;
+ for (JsonElement jElement : componenetArray) {
+ ResourceAssetStructure resource = gson.fromJson(jElement, ResourceAssetStructure.class);
+ resourceAssetList.add(resource);
+ }
+ return resourceAssetList;
+ }
+
+ public static ResourceDetailedAssetStructure getResourceAssetMetadata(RestResponse assetResponse) {
+
+ List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
+ List<ArtifactAssetStructure> artifactsList = new ArrayList<>();
+ ResourceDetailedAssetStructure resourceAssetMetadata = new ResourceDetailedAssetStructure();
+ String response = assetResponse.getResponse();
+
+ JsonObject jObject = (JsonObject) new JsonParser().parse(response);
+ resourceAssetMetadata = gson.fromJson(jObject, ResourceDetailedAssetStructure.class);
+
+ setResourceInstanceAssetList(resourcesList, jObject);
+ resourceAssetMetadata.setResources(resourcesList);
+
+ setArtifactAssetList(artifactsList, jObject);
+ resourceAssetMetadata.setArtifacts(artifactsList);
+
+ return resourceAssetMetadata;
+ }
+
+ public static void generalMetadataFieldsValidatior(AssetStructure assetMetadata, Component component) {
+
+ assertTrue("Expected resourceUuid is " + component.getUUID() + " actual: " + assetMetadata.getUuid(),
+ assetMetadata.getUuid().equals(component.getUUID()));
+ assertTrue(
+ "Expected resourceInvariantUuid is " + component.getInvariantUUID() + " actual: "
+ + assetMetadata.getInvariantUUID(),
+ assetMetadata.getInvariantUUID().equals(component.getInvariantUUID()));
+ assertTrue("Expected asset name is " + component.getName() + " actual: " + assetMetadata.getName(),
+ assetMetadata.getName().equals(component.getName()));
+ assertTrue("Expected asset version is " + component.getVersion() + " actual: " + assetMetadata.getVersion(),
+ assetMetadata.getVersion().equals(component.getVersion()));
+ assertTrue(
+ "Expected asset lastUpdaterUserId is " + component.getLastUpdaterUserId() + " actual: "
+ + assetMetadata.getLastUpdaterUserId(),
+ assetMetadata.getLastUpdaterUserId().equals(component.getLastUpdaterUserId()));
+ assertNotNull("Expected asset toscaModel is null", assetMetadata.getToscaModelURL());
+ assertTrue(
+ "Expected asset category is " + component.getCategories().get(0).getName() + " actual: "
+ + assetMetadata.getCategory(),
+ assetMetadata.getCategory().equals(component.getCategories().get(0).getName()));
+ assertTrue(
+ "Expected asset lifeCycleState is " + component.getLifecycleState() + " actual: "
+ + assetMetadata.getLifecycleState(),
+ assetMetadata.getLifecycleState().equals(component.getLifecycleState().toString()));
+
+ }
+
+ public static void resourceMetadataValidatior(ResourceDetailedAssetStructure resourceAssetMetadata,
+ Resource resource, AssetTypeEnum assetType) {
+
+ generalMetadataFieldsValidatior(resourceAssetMetadata, resource);
+ assertTrue(
+ "Expected asset lastUpdaterFullName is " + resource.getLastUpdaterFullName() + " actual: "
+ + resourceAssetMetadata.getLastUpdaterFullName(),
+ resourceAssetMetadata.getLastUpdaterFullName().equals(resource.getLastUpdaterFullName()));
+ assertTrue(
+ "Expected asset subCategory is " + resource.getCategories().get(0).getSubcategories().get(0).getName()
+ + " actual: " + resourceAssetMetadata.getSubCategory(),
+ resourceAssetMetadata.getSubCategory()
+ .equals(resource.getCategories().get(0).getSubcategories().get(0).getName()));
+ assertTrue(
+ "Expected asset toscaResourceName is " + resource.getToscaResourceName() + " actual: "
+ + resourceAssetMetadata.getToscaResourceName(),
+ resourceAssetMetadata.getToscaResourceName().equals(resource.getToscaResourceName()));
+ assertTrue(
+ "Expected asset resourceType is " + resource.getResourceType() + " actual: "
+ + resourceAssetMetadata.getResourceType(),
+ resourceAssetMetadata.getResourceType().equals(resource.getResourceType().toString()));
+ resourceInstanceAssetValidator(resourceAssetMetadata.getResources(), resource, assetType);
+ // resourceInstanceAssetValidator(resourceAssetMetadata.getResources(),
+ // resource);
+ artifactAssetValidator(resourceAssetMetadata.getArtifacts(), resource, assetType);
+
+ }
+
+ public static void serviceMetadataValidatior(ServiceDetailedAssetStructure serviceAssetMetadata, Service service,
+ AssetTypeEnum assetType) {
+
+ generalMetadataFieldsValidatior(serviceAssetMetadata, service);
+ assertTrue(
+ "Expected asset lastUpdaterFullName is " + service.getLastUpdaterFullName() + " actual: "
+ + serviceAssetMetadata.getLastUpdaterFullName(),
+ serviceAssetMetadata.getLastUpdaterFullName().equals(service.getLastUpdaterFullName()));
+ assertTrue(
+ "Expected asset distributionStatus is " + service.getDistributionStatus() + " actual: "
+ + serviceAssetMetadata.getDistributionStatus(),
+ serviceAssetMetadata.getDistributionStatus().equals(service.getDistributionStatus().toString()));
+ resourceInstanceAssetValidator(serviceAssetMetadata.getResources(), service, assetType);
+ // resourceInstanceAssetValidator(serviceAssetMetadata.getResources(),
+ // service);
+ artifactAssetValidator(serviceAssetMetadata.getArtifacts(), service, assetType);
+
+ }
+
+ private static void artifactAssetValidator(List<ArtifactAssetStructure> artifactAssetStructureList,
+ Component component, AssetTypeEnum assetType) {
+ Map<String, ArtifactDefinition> componentDeploymentArtifacts = component.getDeploymentArtifacts();
+ validateArtifactMetadata(componentDeploymentArtifacts, artifactAssetStructureList, component.getUUID(),
+ assetType, null);
+ }
+
+ private static void validateArtifactMetadata(Map<String, ArtifactDefinition> componentDeploymentArtifacts,
+ List<ArtifactAssetStructure> artifactAssetStructureList, String componentUuid, AssetTypeEnum assetType,
+ String resourceInstanceName) {
+
+ for (Entry<String, ArtifactDefinition> componentDeploymentArtifact : componentDeploymentArtifacts.entrySet()) {
+ ArtifactAssetStructure artifactAssetStructure = getArtifactMetadata(artifactAssetStructureList,
+ componentDeploymentArtifact.getValue().getArtifactUUID());
+ ArtifactDefinition componentDeploymentArtifactValue = componentDeploymentArtifact.getValue();
+ if (artifactAssetStructure != null) {
+ assertTrue(
+ "Expected artifact asset artifactName is " + componentDeploymentArtifactValue.getArtifactName()
+ + " actual: " + artifactAssetStructure.getArtifactName(),
+ componentDeploymentArtifactValue.getArtifactName()
+ .equals(artifactAssetStructure.getArtifactName()));
+ assertTrue(
+ "Expected artifact asset Type is " + componentDeploymentArtifactValue.getArtifactType()
+ + " actual: " + artifactAssetStructure.getArtifactType(),
+ componentDeploymentArtifactValue.getArtifactType()
+ .equals(artifactAssetStructure.getArtifactType()));
+ // assertNotNull("Expected artifact asset resourceInvariantUUID
+ // is null",
+ // resourceInstanceAssetStructure.getResourceInvariantUUID());
+ // String expectedArtifactUrl = "/asdc/v1/catalog/" +
+ // assetType.getValue() + "/" + componentUuid + "/artifacts/" +
+ // componentDeploymentArtifactValue.getArtifactUUID();
+ String expectedArtifactUrl = "";
+ if (resourceInstanceName == null) {
+ expectedArtifactUrl = String.format(COMPONENT_ARTIFACT_URL, assetType.getValue(), componentUuid,
+ componentDeploymentArtifactValue.getArtifactUUID());
+ } else {
+ expectedArtifactUrl = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, assetType.getValue(),
+ componentUuid, resourceInstanceName, componentDeploymentArtifactValue.getArtifactUUID());
+ }
+
+ assertTrue(
+ "Expected artifact asset URL is " + expectedArtifactUrl + " actual: "
+ + artifactAssetStructure.getArtifactURL(),
+ artifactAssetStructure.getArtifactURL().equals(expectedArtifactUrl));
+ assertTrue(
+ "Expected artifact asset description is " + componentDeploymentArtifactValue.getDescription()
+ + " actual: " + artifactAssetStructure.getArtifactDescription(),
+ componentDeploymentArtifactValue.getDescription().toString()
+ .equals(artifactAssetStructure.getArtifactDescription()));
+ assertTrue(
+ "Expected artifact asset checkSum is " + componentDeploymentArtifactValue.getArtifactChecksum()
+ + " actual: " + artifactAssetStructure.getArtifactChecksum(),
+ componentDeploymentArtifactValue.getArtifactChecksum()
+ .equals(artifactAssetStructure.getArtifactChecksum()));
+ assertTrue(
+ "Expected artifact asset version is " + componentDeploymentArtifactValue.getArtifactVersion()
+ + " actual: " + artifactAssetStructure.getArtifactVersion(),
+ componentDeploymentArtifactValue.getArtifactVersion()
+ .equals(artifactAssetStructure.getArtifactVersion()));
+ if (componentDeploymentArtifactValue.getTimeout() > 0) {
+ assertTrue(
+ "Expected artifact asset timeout is " + componentDeploymentArtifactValue.getTimeout()
+ + " actual: " + artifactAssetStructure.getArtifactTimeout(),
+ componentDeploymentArtifactValue.getTimeout()
+ .equals(artifactAssetStructure.getArtifactTimeout()));
+ }
+
+ } else {
+ assertTrue("artifact asset with UUID" + componentDeploymentArtifact.getValue().getArtifactUUID()
+ + " not found in get Metadata response", false);
+ }
+ }
+
+ }
+
+ private static ArtifactAssetStructure getArtifactMetadata(List<ArtifactAssetStructure> artifactAssetStructureList,
+ String artifactUUID) {
+ for (ArtifactAssetStructure artifactAssetStructure : artifactAssetStructureList) {
+ if (artifactAssetStructure.getArtifactUUID().equals(artifactUUID)) {
+ return artifactAssetStructure;
+ }
+ }
+ return null;
+ }
+
+ private static void resourceInstanceAssetValidator(
+ List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, Component component,
+ AssetTypeEnum assetType) {
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ if (componentInstances != null) {
+ for (ComponentInstance componentInstance : componentInstances) {
+ ResourceInstanceAssetStructure resourceInstanceAssetStructure = getResourceInstanceMetadata(
+ resourceInstanceAssetStructures, componentInstance.getName());
+ if (resourceInstanceAssetStructure != null) {
+ assertTrue(
+ "Expected RI asset resourceName is " + componentInstance.getComponentName() + " actual: "
+ + resourceInstanceAssetStructure.getResourceName(),
+ componentInstance.getComponentName()
+ .equals(resourceInstanceAssetStructure.getResourceName()));
+ assertTrue(
+ "Expected RI asset Name is " + componentInstance.getName() + " actual: "
+ + resourceInstanceAssetStructure.getResourceInstanceName(),
+ componentInstance.getName()
+ .equals(resourceInstanceAssetStructure.getResourceInstanceName()));
+ assertNotNull("Expected RI asset resourceInvariantUUID is null",
+ resourceInstanceAssetStructure.getResourceInvariantUUID());
+ assertTrue(
+ "Expected RI asset resourceVersion is " + componentInstance.getComponentVersion()
+ + " actual: " + resourceInstanceAssetStructure.getResourceVersion(),
+ componentInstance.getComponentVersion()
+ .equals(resourceInstanceAssetStructure.getResourceVersion()));
+ assertTrue(
+ "Expected RI asset resourceType is " + componentInstance.getOriginType() + " actual: "
+ + resourceInstanceAssetStructure.getResoucreType(),
+ componentInstance.getOriginType().toString()
+ .equals(resourceInstanceAssetStructure.getResoucreType()));
+ assertTrue(
+ "Expected RI asset resourceUUID is " + componentInstance.getComponentUid() + " actual: "
+ + resourceInstanceAssetStructure.getResourceUUID(),
+ componentInstance.getComponentUid()
+ .equals(resourceInstanceAssetStructure.getResourceUUID()));
+ validateArtifactMetadata(componentInstance.getDeploymentArtifacts(),
+ resourceInstanceAssetStructure.getArtifacts(), component.getUUID(), assetType,
+ componentInstance.getNormalizedName());
+ // validateArtifactMetadata(componentInstance.getDeploymentArtifacts(),
+ // resourceInstanceAssetStructure.getArtifacts(),
+ // component.getUUID(), AssetTypeEnum.RESOURCES);
+ } else {
+ assertTrue("resourceInstance asset with UUID" + componentInstance.getComponentUid()
+ + " not found in get Metadata response", false);
+ }
+ }
+ }
+
+ }
+
+ // private static ResourceInstanceAssetStructure
+ // getResourceInstanceMetadata(List<ResourceInstanceAssetStructure>
+ // resourceInstanceAssetStructures, String componentUid) {
+ private static ResourceInstanceAssetStructure getResourceInstanceMetadata(
+ List<ResourceInstanceAssetStructure> resourceInstanceAssetStructures, String name) {
+ for (ResourceInstanceAssetStructure resourceInstanceAssetStructure : resourceInstanceAssetStructures) {
+ if (resourceInstanceAssetStructure.getResourceInstanceName().equals(name)) {
+ return resourceInstanceAssetStructure;
+ }
+ }
+ return null;
+ }
+
+ public static ServiceDetailedAssetStructure getServiceAssetMetadata(RestResponse assetResponse) {
+
+ List<ResourceInstanceAssetStructure> resourcesList = new ArrayList<>();
+ List<ArtifactAssetStructure> artifactsList = new ArrayList<>();
+ ServiceDetailedAssetStructure serviceAssetMetadata;
+
+ JsonObject jObject = (JsonObject) new JsonParser().parse(assetResponse.getResponse());
+ serviceAssetMetadata = gson.fromJson(jObject, ServiceDetailedAssetStructure.class);
+
+ setResourceInstanceAssetList(resourcesList, jObject);
+ serviceAssetMetadata.setResources(resourcesList);
+
+ setArtifactAssetList(artifactsList, jObject);
+ serviceAssetMetadata.setArtifacts(artifactsList);
+
+ return serviceAssetMetadata;
+ }
+
+ public static void setArtifactAssetList(List<ArtifactAssetStructure> artifactsList, JsonObject jObject) {
+ JsonArray artifactsArray = jObject.getAsJsonArray("artifacts");
+ if (artifactsArray != null) {
+ for (JsonElement jElement : artifactsArray) {
+ ArtifactAssetStructure artifact = gson.fromJson(jElement, ArtifactAssetStructure.class);
+ artifactsList.add(artifact);
+ }
+ }
+ }
+
+ public static void setResourceInstanceAssetList(List<ResourceInstanceAssetStructure> resourcesList,
+ JsonObject jObject) {
+ JsonArray resourcesArray = jObject.getAsJsonArray("resources");
+ if (resourcesArray != null) {
+ for (JsonElement jElement : resourcesArray) {
+ ResourceInstanceAssetStructure resource = gson.fromJson(jElement, ResourceInstanceAssetStructure.class);
+ resourcesList.add(resource);
+ }
+ }
+ }
+
+ public static List<ServiceAssetStructure> getServiceAssetList(RestResponse assetResponse) {
+ List<ServiceAssetStructure> serviceAssetList = new ArrayList<>();
+
+ JsonElement jelement = new JsonParser().parse(assetResponse.getResponse());
+ JsonArray componenetArray = (JsonArray) jelement;
+ for (JsonElement jElement : componenetArray) {
+ ServiceAssetStructure service = gson.fromJson(jElement, ServiceAssetStructure.class);
+ serviceAssetList.add(service);
+ }
+ return serviceAssetList;
+ }
+
+ public static List<String> getResourceNamesList(List<ResourceAssetStructure> resourceAssetList) {
+ List<String> assetNamesList = new ArrayList<>();
+ for (ResourceAssetStructure resourceAsset : resourceAssetList) {
+ assetNamesList.add(resourceAsset.getName());
+ }
+ return assetNamesList;
+ }
+
+ public static List<String> getServiceNamesList(List<ServiceAssetStructure> serviceAssetList) {
+ List<String> assetNamesList = new ArrayList<>();
+ for (ServiceAssetStructure serviceAsset : serviceAssetList) {
+ assetNamesList.add(serviceAsset.getName());
+ }
+ return assetNamesList;
+ }
+
+ public static void checkResourceTypeInObjectList(List<ResourceAssetStructure> resourceAssetList,
+ ResourceTypeEnum resourceType) {
+ for (ResourceAssetStructure resourceAsset : resourceAssetList) {
+ assertTrue(
+ "Expected resourceType is " + resourceType.toString() + " actual: "
+ + resourceAsset.getResourceType(),
+ resourceAsset.getResourceType().equals(resourceType.toString()));
+ }
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
new file mode 100644
index 0000000000..9ffe5782e7
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/BaseRestUtils.java
@@ -0,0 +1,256 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.validation.BaseValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class BaseRestUtils extends BaseValidationUtils {
+ public static final String contentTypeHeaderData = "application/json";
+ public static final String acceptHeaderData = "application/json";
+ public static final String acceptJsonHeader = "application/json";
+ public static final String acceptOctetHeader = "application/octet-stream";
+ public static final String authorizationHeader = "Basic " + Base64.encodeBase64String("ci:123456".getBytes());
+ public static final String acceptOctetStream = "application/octet-stream";
+ public static final String ecomp = "ecomp";
+ public static final String authorizationPrefixString = "Basic ";
+
+ public static final String RESOURCE_COMPONENT_TYPE = "resources";
+ public static final String PRODUCT_COMPONENT_TYPE = "products";
+ public static final String SERVICE_COMPONENT_TYPE = "services";
+
+ public static final int STATUS_CODE_SUCCESS = 200;
+ public static final int STATUS_CODE_CREATED = 201;
+ public static final int STATUS_CODE_DELETE = 204;
+ public static final int STATUS_CODE_NOT_FOUND = 404;
+ public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204;
+ public static final int STATUS_CODE_SUCCESS_DELETE = 204;
+ public static final int STATUS_CODE_INVALID_CONTENT = 400;
+ public static final int STATUS_CODE_MISSING_DATA = 400;
+ public static final int STATUS_CODE_MISSING_INFORMATION = 403;
+ public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
+ public static final int STATUS_CODE_ALREADY_EXISTS = 409;
+ public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
+ public static final int STATUS_CODE_COMPONENT_NAME_EXCEEDS_LIMIT = 400;
+ public static final int STATUS_CODE_MISSING_COMPONENT_NAME = 400;
+ public static final int STATUS_CODE_UNSUPPORTED_ERROR = 400;
+ public static final int STATUS_CODE_IMPORT_SUCCESS = 201;
+ public static final int STATUS_CODE_UPDATE_SUCCESS = 200;
+ public static final int RESTRICTED_OPERATION = 409;
+ public static final int STATUS_CODE_GET_SUCCESS = 200;
+
+ public static final String SUCCESS_MESSAGE = "OK";
+ private static Logger logger = LoggerFactory.getLogger(BaseRestUtils.class.getName());
+
+ private static byte[] encodeBase64;
+
+ // ************* PRIVATE METHODS ************************
+
+ 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<String, String>();
+ if (contentTypeHeaderData != null) {
+ 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;
+ }
+
+ // send request
+ // GET
+ protected static RestResponse sendGet(String url, String userId) throws IOException {
+ return sendGet(url, userId, 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;
+ }
+
+ public static RestResponse sendGetAndRemoveHeaders(String url, String userId, List<String> headersToRemove)
+ throws IOException {
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ if (headersToRemove != null) {
+ for (String header : headersToRemove) {
+ headersMap.remove(header);
+ }
+ }
+
+ HttpRequest http = new HttpRequest();
+ RestResponse getResourceResponse = http.httpSendGet(url, headersMap);
+ return getResourceResponse;
+ }
+
+ // PUT
+ 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;
+ }
+
+ // POST
+ public static RestResponse sendPost(String url, String userBodyJson, String userId, String accept)
+ throws IOException {
+ return sendPost(url, userBodyJson, userId, accept, 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;
+ }
+
+ // used form complex requests like import categories..
+ protected static RestResponse sendPost(String url, HttpEntity entity, String userId, String accept)
+ throws IOException {
+ RestResponse postResponse = new RestResponse();
+ CloseableHttpResponse response = null;
+ CloseableHttpClient client = null;
+ try {
+ client = HttpClients.createDefault();
+ HttpPost httpPost = new HttpPost(url);
+
+ httpPost.addHeader("USER_ID", userId);
+ httpPost.setEntity(entity);
+ response = client.execute(httpPost);
+ HttpEntity responseEntity = response.getEntity();
+ int statusCode = response.getStatusLine().getStatusCode();
+
+ postResponse.setErrorCode(statusCode);
+ StringBuffer sb = new StringBuffer();
+ try {
+ BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ sb.append(inputLine);
+ }
+ in.close();
+ } catch (Exception e) {
+ logger.debug("response body is null");
+ }
+ postResponse.setResponse(sb.toString());
+ } finally {
+ try {
+ if (response != null) {
+ response.close();
+ }
+
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
+ }
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (IOException e) {
+ logger.debug("failed to close client or response: ", e);
+ }
+ }
+ return postResponse;
+ }
+
+ // DELETE
+ protected static RestResponse sendDelete(String url, String userId) throws IOException {
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ HttpRequest http = new HttpRequest();
+ RestResponse deleteResourceResponse = http.httpSendDelete(url, headersMap);
+ return deleteResourceResponse;
+ }
+
+ /*
+ * // ------ protected static Boolean checkErrorCode(RestResponse
+ * deleteResponse) { if (deleteResponse.getErrorCode() ==
+ * STATUS_CODE_SUCCESS || deleteResponse.getErrorCode() ==
+ * STATUS_CODE_DELETE) { return true; } return false; }
+ *
+ * // *** STATUS CODE VALIDATION UTIITIES **** public static void
+ * checkStatusCode(RestResponse response, String assertMessage, boolean AND,
+ * int... statuses) { int statusCode = response.getErrorCode(); for (int
+ * status : statuses) { if (AND && statusCode != status) {
+ * Assert.fail(assertMessage + " status: " + statusCode); } else if
+ * (statusCode == status) { return; } } if (!AND) {
+ * Assert.fail(assertMessage + " status: " + statusCode); } }
+ *
+ * public static void checkDeleteResponse(RestResponse response) {
+ * checkStatusCode(response,"delete request failed",false,STATUS_CODE_DELETE
+ * ,STATUS_CODE_NOT_FOUND, STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for
+ * deActivate user }
+ *
+ * public static void checkCreateResponse(RestResponse response) {
+ * checkStatusCode(response, "create request failed", false,
+ * STATUS_CODE_CREATED); }
+ */
+ public static String encodeUrlForDownload(String url) {
+ return url.replaceAll(" ", "%20");
+ }
+
+ public static Map<String, String> addAuthorizeHeader(String userName, String password) {
+ String userCredentials = userName + ":" + password;
+ encodeBase64 = Base64.encodeBase64(userCredentials.getBytes());
+ String encodedUserCredentials = authorizationPrefixString + new String(encodeBase64);
+ Map<String, String> authorizationHeader = new HashMap<String, String>();
+ authorizationHeader.put(HttpHeaderEnum.AUTHORIZATION.getValue(), encodedUserCredentials);
+ return authorizationHeader;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
new file mode 100644
index 0000000000..a265639804
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CatalogRestUtils.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+public class CatalogRestUtils extends BaseRestUtils {
+
+ public static RestResponse getAbstractResources() throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_ABSTRACT_RESOURCES, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+
+ return sendGet(url, UserRoleEnum.DESIGNER.getUserId());
+ }
+
+ public static RestResponse getCatalog() throws IOException {
+ return getCatalog(UserRoleEnum.DESIGNER.getUserId());
+ }
+
+ public static RestResponse getCatalog(String userId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CATALOG_DATA, config.getCatalogBeHost(), config.getCatalogBePort());
+ return sendGet(url, userId);
+ }
+
+ public static RestResponse getAllCategoriesTowardsCatalogBe() throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(),
+ BaseRestUtils.RESOURCE_COMPONENT_TYPE);
+
+ return sendGet(url, UserRoleEnum.DESIGNER.getUserId());
+ }
+
+ public static RestResponse getAllCategoriesTowardsCatalogFeWithUuid(String uuid) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(),
+ BaseRestUtils.RESOURCE_COMPONENT_TYPE);
+
+ Map<String, String> additionalHeaders = new HashMap<String, String>();
+ additionalHeaders.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
+
+ return sendGet(url, UserRoleEnum.DESIGNER.getUserId(), additionalHeaders);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
new file mode 100644
index 0000000000..d9ae91b955
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/CategoryRestUtils.java
@@ -0,0 +1,298 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+public class CategoryRestUtils extends BaseRestUtils {
+
+ private static final int STATUS_CODE_CREATED = 201;
+
+ private static Gson gson = new Gson();
+
+ public static RestResponse createCategory(CategoryDefinition categoryDefinition, User sdncModifierDetails,
+ String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType);
+ String bodyJson = gson.toJson(categoryDefinition);
+ RestResponse addCategoryResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ if (addCategoryResponse.getErrorCode().intValue() == STATUS_CODE_CREATED)
+ categoryDefinition.setUniqueId(
+ ResponseParser.getValueFromJsonResponse(addCategoryResponse.getResponse(), "uniqueId"));
+ return addCategoryResponse;
+ }
+
+ // GET categories
+ public static RestResponse getAllCategories(User sdncModifierDetails, String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType);
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ RestResponse getCategotyResponse = http.httpSendGet(url, headersMap);
+ return getCategotyResponse;
+ }
+
+ public static RestResponse getAllCategoriesTowardsFe(User sdncModifierDetails, String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), categoryType);
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ RestResponse getCategotyResponse = http.httpSendGet(url, headersMap);
+ return getCategotyResponse;
+ }
+
+ // Delete Category
+ public static RestResponse deleteCategory(String categoryId, String psUserId, String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType, categoryId);
+ url = url.replace("#", "%23"); // HEX
+ url = url.replace(" ", "%20"); // HEX
+ RestResponse deleteCategoryResponse = sendDelete(url, psUserId);
+ return deleteCategoryResponse;
+ }
+
+ public static RestResponse createSubCategory(SubCategoryDefinition subCategory, CategoryDefinition parentCategory,
+ User sdncModifierDetails, String categoryType) throws Exception {
+ // categoryType = service/resource/product
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType, parentCategory.getUniqueId());
+ String bodyJson = gson.toJson(subCategory);
+ RestResponse createSubCategoryPost = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ if (createSubCategoryPost.getErrorCode().intValue() == STATUS_CODE_CREATED)
+ subCategory.setUniqueId(
+ ResponseParser.getValueFromJsonResponse(createSubCategoryPost.getResponse(), "uniqueId"));
+
+ return createSubCategoryPost;
+ }
+
+ public static RestResponse deleteSubCategory(String subCategoryId, String categoryId, String psUserId,
+ String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType, categoryId, subCategoryId);
+ url = url.replace("#", "%23"); // HEX
+ url = url.replace(" ", "%20"); // HEX
+ RestResponse deleteSubCategoryResponse = sendDelete(url, psUserId);
+ return deleteSubCategoryResponse;
+ }
+
+ public static RestResponse deleteGrouping(String groupId, String subCategoryId, String categoryId, String psUserId,
+ String categoryType) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType, categoryId, subCategoryId, groupId);
+ url = url.replace("#", "%23"); // HEX
+ url = url.replace(" ", "%20"); // HEX
+ RestResponse deleteGroupResponse = sendDelete(url, psUserId);
+ return deleteGroupResponse;
+ }
+
+ public static RestResponse createServiceCategoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition,
+ User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ SERVICE_COMPONENT_TYPE);
+
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails.getUserId());
+ headersMap.remove("USER_ID");
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(categoryDataDefinition);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse createCatergoryResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ return createCatergoryResponse;
+ }
+
+ public static RestResponse createSubCategoryHttpCspAtuUidIsMissing(SubCategoryDefinition subCategory,
+ CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception {
+ // categoryType = service/resource/product
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_SUB_CATEGORY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ categoryType, parentCategory.getUniqueId());
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ headersMap.remove("USER_ID");
+ Gson gson = new Gson();
+ String subCatJson = gson.toJson(subCategory);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(subCatJson);
+ RestResponse addCategoryResponse = http.httpSendPost(url, subCatJson, headersMap);
+ return addCategoryResponse;
+ }
+
+ public static RestResponse deleteCatergoryHttpCspAtuUidIsMissing(CategoryDefinition categoryDataDefinition, User sdncModifierDetails) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), categoryDataDefinition.getName());
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ headersMap.remove("USER_ID");
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(categoryDataDefinition);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse deleteCategotyResponse = http.httpSendDelete(url, headersMap);
+ return deleteCategotyResponse;
+ }
+
+ public static RestResponse createGrouping(GroupingDefinition grouping, SubCategoryDefinition subCategory,
+ CategoryDefinition parentCategory, User sdncModifierDetails, String categoryType) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_GROUPING, config.getCatalogBeHost(), config.getCatalogBePort(), categoryType, parentCategory.getUniqueId(), subCategory.getUniqueId());
+ String bodyJson = gson.toJson(grouping);
+ RestResponse addGroupingResponse = BaseRestUtils.sendPost(url, bodyJson, sdncModifierDetails.getUserId(), acceptHeaderData);
+ return addGroupingResponse;
+ }
+
+ public static RestResponse importCategories(MultipartEntityBuilder mpBuilder, String userId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.IMPORT_CATEGORIES, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ RestResponse importResponse = BaseRestUtils.sendPost(url, mpBuilder.build(), userId, acceptHeaderData);
+ return importResponse;
+ }
+
+ public static int getMatchingCategoriesNum(RestResponse getAllCategoryRest, CategoryDefinition categoryDefinition) {
+ String response = getAllCategoryRest.getResponse();
+ Gson gson = new Gson();
+ List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
+ new TypeToken<List<CategoryDefinition>>() {
+ }.getType());
+ int categoriesNum = 0;
+ String catName = categoryDefinition.getName();
+ for (CategoryDefinition elem : categoryDefinitions) {
+ if (elem.getName().equals(catName)) {
+ categoryDefinition.setUniqueId(elem.getUniqueId());
+ categoriesNum++;
+ }
+ }
+
+ return categoriesNum;
+ }
+
+ public static int getMatchingSubCategoriesNum(RestResponse getAllCategoryRest, String parentCategoryId,
+ SubCategoryDefinition expectedSubCategoryDefinition) {
+
+ String response = getAllCategoryRest.getResponse();
+ Gson gson = new Gson();
+ List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
+ new TypeToken<List<CategoryDefinition>>() {
+ }.getType());
+ int subCatNum = 0;
+ String subCatName = expectedSubCategoryDefinition.getName();
+ for (CategoryDefinition elem : categoryDefinitions) {
+ if (elem.getUniqueId().equals(parentCategoryId)) {
+ List<SubCategoryDefinition> subCategories = elem.getSubcategories();
+ if (subCategories != null) {
+ for (SubCategoryDefinition subCategoryDataDefinition : subCategories) {
+ if (subCatName.equals(subCategoryDataDefinition.getName())) {
+ expectedSubCategoryDefinition.setUniqueId(subCategoryDataDefinition.getUniqueId());
+ subCatNum++;
+ }
+ }
+ }
+
+ }
+ }
+ return subCatNum;
+ }
+
+ public static int getMatchingGroupingNum(RestResponse getAllCategoryRest, String parentCategoryId,
+ String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
+
+ String response = getAllCategoryRest.getResponse();
+ Gson gson = new Gson();
+ List<CategoryDefinition> categoryDefinitions = gson.fromJson(response,
+ new TypeToken<List<CategoryDefinition>>() {
+ }.getType());
+ int groupingNum = 0;
+ String groupingName = expectedGroupingDefinition.getName();
+ for (CategoryDefinition elem : categoryDefinitions) {
+ if (elem.getUniqueId().equals(parentCategoryId)) {
+ List<SubCategoryDefinition> subCategories = elem.getSubcategories();
+ if (subCategories != null) {
+ for (SubCategoryDefinition subCategoryDataDefinition : subCategories) {
+ // if
+ // (subCategoryId.equals(subCategoryDataDefinition.getUniqueId()))
+ // {
+ if (subCategoryId.equals(subCategoryDataDefinition.getUniqueId())
+ && subCategoryDataDefinition.getGroupings() != null) {
+ List<GroupingDefinition> grouping = subCategoryDataDefinition.getGroupings();
+ for (GroupingDefinition groupingDataDefinition : grouping) {
+ if (groupingName.equals(groupingDataDefinition.getName())) {
+ expectedGroupingDefinition.setUniqueId(groupingDataDefinition.getUniqueId());
+ groupingNum++;
+ }
+ }
+
+ }
+ }
+ }
+
+ }
+ }
+ return groupingNum;
+ }
+
+ public enum CategoryAuditJsonKeysEnum {
+ ACTION("ACTION"), MODIFIER("MODIFIER"), CATEGORY_NAME("CATEGORY_NAME"), SUB_CATEGORY_NAME("SUB_CATEGORY_NAME"), GROUPING_NAME("GROUPING_NAME"), RESOURCE_TYPE("RESOURCE_TYPE"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"),
+ DESCRIPTION("DESCRIPTION"), DETAILS("DETAILS");
+
+ private String auditJsonKeyName;
+
+ private CategoryAuditJsonKeysEnum(String auditJsonKeyName) {
+ this.auditJsonKeyName = auditJsonKeyName;
+ }
+
+ public String getAuditJsonKeyName() {
+ return auditJsonKeyName.toLowerCase();
+ }
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
new file mode 100644
index 0000000000..10587390f2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentInstanceRestUtils.java
@@ -0,0 +1,276 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import com.google.gson.Gson;
+
+public class ComponentInstanceRestUtils extends BaseRestUtils {
+ public static String acceptHeaderDate = "application/json";
+ static Config config = Config.instance();
+ public static Gson gson = new Gson();
+
+ // 'componentType' can be 'services' or 'resources'
+
+ public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
+ User sdncModifierDetails, Component component) throws Exception {
+ return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, component.getUniqueId(),
+ component.getComponentType());
+ }
+
+ public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
+ User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws Exception {
+
+ return createComponentInstance(componentInstanceReqDetails, sdncModifierDetails, componentId,
+ ComponentTypeEnum.findParamByType(componentType));
+ }
+
+ public static RestResponse createComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
+ User sdncModifierDetails, String componentId, String componentType) throws Exception {
+ Config config = Utils.getConfig();
+ String userId = sdncModifierDetails.getUserId();
+ String serviceBodyJson = gson.toJson(componentInstanceReqDetails);
+ String url = String.format(Urls.CREATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ componentType, componentId);
+ RestResponse createResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
+ if (createResourceInstance.getErrorCode().equals(BaseRestUtils.STATUS_CODE_CREATED)) {
+ String uniqueId = ResponseParser.getValueFromJsonResponse(createResourceInstance.getResponse(), "uniqueId");
+ componentInstanceReqDetails.setUniqueId(uniqueId);
+ // Gson gson = new Gson();
+ // ResourceInstanceReqDetails fromJson =
+ // gson.fromJson(createResourceInstance.getResponse(),
+ // ResourceInstanceReqDetails.class);
+ // componentInstanceReqDetails.setUniqueId(fromJson.getUniqueId());
+ }
+ return createResourceInstance;
+ }
+
+ public static RestResponse getComponentInstances(ComponentTypeEnum type, String componentId, User user)
+ throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+
+ String url = String.format(Urls.GET_COMPONENT_INSTANCES, config.getCatalogBeHost(), config.getCatalogBePort(),
+ ComponentTypeEnum.findParamByType(type), componentId);
+
+ RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap);
+
+ return sendGetServerRequest;
+
+ }
+
+ public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId,
+ String resourceInstanceId, ComponentTypeEnum componentType) throws Exception {
+
+ return deleteComponentInstance(sdncModifierDetails, componentId, resourceInstanceId,
+ ComponentTypeEnum.findParamByType(componentType));
+ }
+
+ public static RestResponse deleteComponentInstance(User sdncModifierDetails, String componentId,
+ String resourceInstanceId, String componentTypeString) throws Exception {
+ Config config = Utils.getConfig();
+ String userId = sdncModifierDetails.getUserId();
+ String url = String.format(Urls.DELETE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ componentTypeString, componentId, resourceInstanceId);
+ RestResponse sendCreateUserRequest = sendDelete(url, userId);
+ return sendCreateUserRequest;
+ }
+
+ public static RestResponse updateComponentInstance(ComponentInstanceReqDetails componentInstanceReqDetails,
+ User sdncModifierDetails, String componentId, ComponentTypeEnum componentType) throws IOException {
+
+ Config config = Utils.getConfig();
+ String userId = sdncModifierDetails.getUserId();
+ String serviceBodyJson = gson.toJson(componentInstanceReqDetails);
+ String url = String.format(Urls.UPDATE_COMPONENT_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ ComponentTypeEnum.findParamByType(componentType), componentId,
+ componentInstanceReqDetails.getUniqueId());
+ RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
+ return updateResourceInstance;
+ }
+
+ // TODO Tal CI for New API Multiple Instance Update
+ public static RestResponse updateMultipleComponentInstance(
+ List<ComponentInstanceReqDetails> componentInstanceReqDetailsList, User sdncModifierDetails,
+ String componentId, ComponentTypeEnum componentType) throws IOException {
+ Config config = Utils.getConfig();
+ String userId = sdncModifierDetails.getUserId();
+ String serviceBodyJson = gson.toJson(componentInstanceReqDetailsList.toArray());
+ String url = String.format(Urls.UPDATE_MULTIPLE_COMPONENT_INSTANCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentId);
+ RestResponse updateResourceInstance = sendPost(url, serviceBodyJson, userId, acceptHeaderData);
+ return updateResourceInstance;
+ }
+
+ public static RestResponse associateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails,
+ String componentId, ComponentTypeEnum componentTypeEnum) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ String componentType = "";
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME;
+ break;
+ case SERVICE:
+ componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ break;
+ default:
+ break;
+ }
+ String serviceBodyJson = gson.toJson(relation);
+ String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), componentType, componentId);
+
+ RestResponse associateInstance = sendPost(url, serviceBodyJson, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ return associateInstance;
+
+ }
+
+ public static RestResponse dissociateInstances(RequirementCapabilityRelDef relation, User sdncModifierDetails,
+ String componentId, ComponentTypeEnum componentTypeEnum) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ String componentType = "";
+ switch (componentTypeEnum) {
+ case RESOURCE:
+ componentType = ComponentTypeEnum.RESOURCE_PARAM_NAME;
+ break;
+ case SERVICE:
+ componentType = ComponentTypeEnum.SERVICE_PARAM_NAME;
+ break;
+ default:
+ break;
+ }
+ String serviceBodyJson = gson.toJson(relation);
+ String url = String.format(Urls.DISSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), componentType, componentId);
+
+ RestResponse associateInstance = sendPut(url, serviceBodyJson, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ return associateInstance;
+
+ }
+
+ public static void checkComponentInstanceType(RestResponse response, String expectedComponentType) {
+ String actualComponentType = ResponseParser.getComponentTypeFromResponse(response);
+ assertTrue(expectedComponentType.equals(actualComponentType),
+ "Failed. expected: " + expectedComponentType + ", actual: " + actualComponentType + "/");
+ }
+
+ public static RestResponse updatePropertyValueOnResourceInstance(Component component, ComponentInstance instDetails,
+ User user, ComponentInstanceProperty updatedInstanceProperty) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+
+ String url = String.format(Urls.UPDATE_PROPERTY_TO_RESOURCE_INSTANCE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
+ component.getUniqueId(), instDetails.getUniqueId());
+ String body = gson.toJson(updatedInstanceProperty);
+
+ RestResponse sendGetServerRequest = sendPost(url, body, user.getUserId(), acceptHeaderData);
+ return sendGetServerRequest;
+
+ }
+
+ public static RestResponse changeComponentInstanceVersion(Component container,
+ ComponentInstance componentInstanceToReplace, Component newInstance, User sdncModifierDetails)
+ throws Exception {
+
+ return changeComponentInstanceVersion(container.getUniqueId(), componentInstanceToReplace, newInstance,
+ sdncModifierDetails, container.getComponentType());
+ }
+
+ public static RestResponse changeComponentInstanceVersion(String containerUID,
+ ComponentInstance componentInstanceToReplace, Component component, User sdncModifierDetails,
+ ComponentTypeEnum componentType) throws IOException {
+
+ Config config = Utils.getConfig();
+ String resourceUid = ("{\"componentUid\":\"" + component.getUniqueId() + "\"}");
+ String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), containerUID,
+ componentInstanceToReplace.getUniqueId());
+ RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+
+ if (changeResourceInstanceVersion.getErrorCode() == 200
+ || changeResourceInstanceVersion.getErrorCode() == 201) {
+ Gson gson = new Gson();
+ // ResourceInstanceReqDetails
+ // convertResourceInstanceResponseToJavaObject =
+ // ResponseParser.convertResourceInstanceResponseToJavaObject(createResourceInstance.getResponse());
+ ComponentInstanceReqDetails fromJson = gson.fromJson(changeResourceInstanceVersion.getResponse(),
+ ComponentInstanceReqDetails.class);
+
+ componentInstanceToReplace.setUniqueId(fromJson.getUniqueId());
+
+ }
+
+ return changeResourceInstanceVersion;
+
+ }
+
+ public static RestResponse changeComponentInstanceVersion(String componentUniqueId,
+ String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails,
+ ComponentTypeEnum componentType) throws IOException {
+ Config config = Utils.getConfig();
+ String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
+ String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId,
+ serviceInstanceToReplaceUniqueId);
+ RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ return changeResourceInstanceVersion;
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
new file mode 100644
index 0000000000..dcebe4afa8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ComponentRestUtils.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.CapReqDef;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+public class ComponentRestUtils extends BaseRestUtils {
+ public static RestResponse getComponentRequirmentsCapabilities(User sdncModifierDetails,
+ ComponentReqDetails componentReqDetails) throws IOException {
+ Config config = Utils.getConfig();
+ ComponentTypeEnum componentType = null;
+ if (componentReqDetails instanceof ResourceReqDetails) {
+ componentType = ComponentTypeEnum.RESOURCE;
+ } else if (componentReqDetails instanceof ServiceReqDetails) {
+ componentType = ComponentTypeEnum.SERVICE;
+ } else if (componentReqDetails instanceof ProductReqDetails) {
+ componentType = ComponentTypeEnum.PRODUCT;
+ }
+ String url = String.format(Urls.GET_COMPONENT_REQUIRMENTS_CAPABILITIES, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType),
+ componentReqDetails.getUniqueId());
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static CapReqDef getAndParseComponentRequirmentsCapabilities(User user, ComponentReqDetails componentDetails)
+ throws IOException {
+ RestResponse getComponentReqCap = getComponentRequirmentsCapabilities(user, componentDetails);
+ ResourceRestUtils.checkSuccess(getComponentReqCap);
+ CapReqDef capReqDef = ResponseParser.parseToObject(getComponentReqCap.getResponse(), CapReqDef.class);
+ return capReqDef;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
new file mode 100644
index 0000000000..1b93d8d778
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ConsumerRestUtils.java
@@ -0,0 +1,206 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.util.Map;
+
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import com.google.gson.Gson;
+
+public class ConsumerRestUtils extends BaseRestUtils {
+
+ public static final int STATUS_CODE_SUCCESS = 200;
+ public static final int STATUS_CODE_CREATED = 201;
+ public static final int STATUS_CODE_DELETE = 204;
+ public static final int STATUS_CODE_NOT_FOUND = 404;
+ Utils utils = new Utils();
+ private static Long expectedsLastupdatedtime;
+ private static Long expectedLastAuthenticationTime;
+
+ public static RestResponse createConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ String userId = sdncModifierDetails.getUserId();
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(consumerDataDefinition);
+
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) {
+ ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse);
+ consumerDataDefinition.setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+ consumerDataDefinition.setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
+ consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
+ }
+ return createConsumerResponse;
+ }
+
+ public static RestResponse createConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ headersMap.remove("USER_ID");
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(consumerDataDefinition);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse createConsumerResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ if (createConsumerResponse.getErrorCode() == STATUS_CODE_CREATED) {
+ ConsumerDataDefinition getConsumerDataObject = parseComsumerResp(createConsumerResponse);
+ consumerDataDefinition.setConsumerDetailsLastupdatedtime(getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+ consumerDataDefinition.setConsumerLastAuthenticationTime(getConsumerDataObject.getConsumerLastAuthenticationTime());
+ consumerDataDefinition.setLastModfierAtuid(getConsumerDataObject.getLastModfierAtuid());
+ }
+ return createConsumerResponse;
+ }
+
+ public static RestResponse deleteConsumerHttpCspAtuUidIsMissing(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName());
+
+ String userId = sdncModifierDetails.getUserId();
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ headersMap.remove("USER_ID");
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(consumerDataDefinition);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap);
+ return deleteConsumerResponse;
+ }
+
+ public static ConsumerDataDefinition parseComsumerResp(RestResponse restResponse) throws Exception {
+
+ String bodyToParse = restResponse.getResponse();
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ConsumerDataDefinition component = mapper.readValue(bodyToParse, ConsumerDataDefinition.class);
+ return component;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return null;
+ }
+
+ public static RestResponse deleteConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName());
+
+ String userId = sdncModifierDetails.getUserId();
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ RestResponse deleteConsumerResponse = http.httpSendDelete(url, headersMap);
+ return deleteConsumerResponse;
+ }
+
+ public static RestResponse getConsumer(ConsumerDataDefinition consumerDataDefinition, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CONSUMER, config.getCatalogBeHost(), config.getCatalogBePort(), consumerDataDefinition.getConsumerName());
+
+ String userId = sdncModifierDetails.getUserId();
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ RestResponse getConsumerResponse = http.httpSendGet(url, headersMap);
+ return getConsumerResponse;
+ }
+
+ public static void validateConsumerReqVsResp(ConsumerDataDefinition consumerDefinition, ConsumerDataDefinition getConsumerDataObject) {
+
+ String expected;
+
+ expected = consumerDefinition.getConsumerName();
+ assertEquals("consumer name - ", expected, getConsumerDataObject.getConsumerName());
+
+ expected = consumerDefinition.getConsumerPassword().toLowerCase();
+ assertEquals("consumer password - ", expected, getConsumerDataObject.getConsumerPassword());
+
+ expected = consumerDefinition.getLastModfierAtuid();
+ assertEquals("consumer Last Modfier Atuid - ", expected, getConsumerDataObject.getLastModfierAtuid());
+
+ expected = consumerDefinition.getConsumerSalt();
+ assertEquals("consumer Salt - ", expected, getConsumerDataObject.getConsumerSalt());
+
+ expectedsLastupdatedtime = consumerDefinition.getConsumerDetailsLastupdatedtime();
+ assertEquals("consumer Last updated time - ", expectedsLastupdatedtime, getConsumerDataObject.getConsumerDetailsLastupdatedtime());
+
+ expectedLastAuthenticationTime = consumerDefinition.getConsumerLastAuthenticationTime();
+ assertEquals("consumer Last authentication time - ", expectedLastAuthenticationTime, getConsumerDataObject.getConsumerLastAuthenticationTime());
+ }
+
+ ///// New
+ public enum EcompConsumerAuditJsonKeysEnum {
+ ACTION("ACTION"), MODIFIER("MODIFIER"), ECOMP_USER("ECOMP_USER"), STATUS("STATUS"), DESC("DESCRIPTION");
+ private String auditJsonKeyName;
+
+ private EcompConsumerAuditJsonKeysEnum(String auditJsonKeyName) {
+ this.auditJsonKeyName = auditJsonKeyName;
+ }
+
+ public String getAuditJsonKeyName() {
+ return auditJsonKeyName.toLowerCase();
+ }
+ }
+
+ /*
+ * protected void resourceArtifatAuditSuccess(String action, ArtifactReqDetails artifact, ResourceReqDetails resourceDetails , User user) throws Exception { ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject =
+ * Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), user); String auditAction = action; expectedResourceAuditJavaObject.setAction(auditAction); expectedResourceAuditJavaObject.setPrevState("");
+ * expectedResourceAuditJavaObject.setPrevVersion(""); expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum. NOT_CERTIFIED_CHECKOUT).toString()); expectedResourceAuditJavaObject.setStatus("200");
+ * expectedResourceAuditJavaObject.setDesc("OK"); expectedResourceAuditJavaObject.setArtifactName(artifact.getArtifactName( )); AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null); }
+ */
+
+ /*
+ * protected void resourceArtifatValidateAuditWithErrorMessage(String actionStatus, ResourceReqDetails resourceDetails, String auditAction, String setCurrState, Object ... variables)throws Exception { ErrorInfo errorInfo =
+ * utils.parseYaml(actionStatus); ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = Convertor.constructFieldsForAuditValidation(resourceDetails, resourceDetails.getVersion(), sdncUserDetails);
+ * expectedResourceAuditJavaObject.setAction(auditAction); expectedResourceAuditJavaObject.setPrevState(""); expectedResourceAuditJavaObject.setPrevVersion(""); expectedResourceAuditJavaObject.setCurrState(setCurrState);
+ * expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString()) ; expectedResourceAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables) ); expectedResourceAuditJavaObject.setArtifactName("");
+ * AuditUtils.validateAudit(expectedResourceAuditJavaObject, auditAction, null); }
+ */
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
new file mode 100644
index 0000000000..a71711dde6
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/EcompUserRestUtils.java
@@ -0,0 +1,255 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.portalsdk.core.restful.domain.EcompRole;
+import org.openecomp.portalsdk.core.restful.domain.EcompUser;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.run.StartTest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+public class EcompUserRestUtils extends BaseRestUtils {
+
+ static Gson gson = new Gson();
+
+ static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
+ static String contentTypeHeaderData = "application/json";
+ static String acceptHeaderDate = "application/json";
+ static String ecompUsername = "12345";
+ static String ecompPassword = "12345";
+
+ public EcompUserRestUtils() {
+ super();
+
+ StartTest.enableLogger();
+ }
+
+ public static RestResponse pushUser(EcompUser ecompUser) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ String userBodyJson = gson.toJson(ecompUser);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_PUSH_USER, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ logger.debug("Send POST request to create user: {}", url);
+ logger.debug("User body: {}", userBodyJson);
+ logger.debug("User headers: {}", headersMap);
+
+ RestResponse sendPushUserResponse = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return sendPushUserResponse;
+ }
+
+ /*
+ * loginId - equals to userId
+ */
+ public static RestResponse editUser(String loginId, EcompUser ecompUser) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ String userBodyJson = gson.toJson(ecompUser);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_EDIT_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId);
+
+ logger.debug("Send POST request to edit user: {}", url);
+ logger.debug("User body: {}", userBodyJson);
+ logger.debug("User headers: {}", headersMap);
+
+ RestResponse sendEditUserResponse = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return sendEditUserResponse;
+ }
+
+ /*
+ * loginId - equals to userId
+ */
+ public static RestResponse getUser(String loginId) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(), loginId);
+
+ logger.debug("Send GET request to get user: {}", url);
+ logger.debug("User headers: {}", headersMap);
+
+ RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
+
+ return sendGetUserRequest;
+ }
+
+ public static RestResponse getAllUsers() throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ logger.debug("Send POST request to get all users: {}", url);
+ logger.debug("User headers: {}" , headersMap);
+
+ RestResponse sendGetAllUsersRequest = http.httpSendGet(url, headersMap);
+
+ return sendGetAllUsersRequest;
+ }
+
+ public static RestResponse getAllAvailableRoles() throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_GET_ALL_AVAILABLE_ROLES, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+
+ logger.debug("Send GET request to get all available roles: {}", url);
+ logger.debug("User headers: {}", headersMap);
+
+ RestResponse sendUpdateUserRequest = http.httpSendGet(url, headersMap);
+
+ return sendUpdateUserRequest;
+ }
+
+ /*
+ * loginId - equals to userId
+ */
+ public static RestResponse pushUserRoles(String loginId, List<EcompRole> roles) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ String roleBodyJson = gson.toJson(roles);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_PUSH_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
+ loginId);
+
+ logger.debug("Send POST request to push user role: {}", url);
+ logger.debug("Roles body: {}", roleBodyJson);
+ logger.debug("Request headers: {}", headersMap);
+
+ RestResponse sendpushUserRolesResponse = http.httpSendPost(url, roleBodyJson, headersMap);
+
+ return sendpushUserRolesResponse;
+ }
+
+ /*
+ * loginId - equals to userId
+ */
+ public static RestResponse getUserRoles(String loginId) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.ECOMP_USERNAME.getValue(), ecompUsername);
+ headersMap.put(HttpHeaderEnum.ECOMP_PASSWORD.getValue(), ecompPassword);
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.ECOMP_GET_USER_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
+ loginId);
+
+ logger.debug("Send GET request to get user roles: {}", url);
+ logger.debug("User headers: {}", headersMap);
+
+ RestResponse sendGetUserRolesRequest = http.httpSendGet(url, headersMap);
+
+ return sendGetUserRolesRequest;
+ }
+
+ // TODO !!!!!!!!!!!!!!
+ /*
+ * Ask Eli if implementation of users is needed DELETE ECOMP USER
+ */
+
+ /*
+ * public static void main(String[] args) { EcompUser ecompUser = new
+ * EcompUser(); ecompUser.setFirstName("Test");
+ * ecompUser.setLastName("Testovich");
+ * ecompUser.setEmail("ttes@intl.sdc.com"); ecompUser.setLoginId("tt0004");
+ * ecompUser.setActive(true);
+ *
+ * EcompRole roleToUpdate = new EcompRole(); roleToUpdate.setId(new
+ * Long(6)); roleToUpdate.setName("PRODUCT_STRATEGIST"); List<EcompRole>
+ * listOfRoles = new LinkedList<>(); listOfRoles.add(roleToUpdate);
+ *
+ * try {
+ * System.out.println("\n-----------------------------\n Testing pushUser");
+ * System.out.println(pushUser(ecompUser));
+ * System.out.println("\n-----------------------------\n Testing editUser");
+ * // System.out.println(editUser("tt0001", ecompUser));
+ * System.out.println("\n-----------------------------\n Testing getUser");
+ * // System.out.println(getUser(ecompUser.getLoginId())); System.out.
+ * println("\n-----------------------------\n Testing getAllUsers"); //
+ * System.out.println(getAllUsers()); System.out.
+ * println("\n-----------------------------\n Testing getAllAvailableRoles"
+ * ); // System.out.println(getAllAvailableRoles().toString()); System.out.
+ * println("\n-----------------------------\n Testing pushUserRoles"); //
+ * System.out.println(pushUserRoles("tt0001", listOfRoles)); System.out.
+ * println("\n-----------------------------\n Testing getUserRoles"); //
+ * System.out.println(getUserRoles("tt0001")); } catch (IOException e) { //
+ * TODO Auto-generated catch block e.printStackTrace(); } }
+ */
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
new file mode 100644
index 0000000000..d79c8e002c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/GroupRestUtils.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import com.google.gson.Gson;
+
+public class GroupRestUtils extends BaseRestUtils {
+ public static String acceptHeaderDate = "application/json";
+ static Config config = Config.instance();
+ public static Gson gson = new Gson();
+
+ public static RestResponse getGroupById(Component component, String groupId, User user) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+
+ String url = String.format(Urls.GET_GROUP_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(),
+ ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), groupId);
+
+ RestResponse sendGetServerRequest = sendGet(url, user.getUserId(), headersMap);
+
+ return sendGetServerRequest;
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
new file mode 100644
index 0000000000..3ce48962fd
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ImportRestUtils.java
@@ -0,0 +1,339 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.entity.mime.content.FileBody;
+import org.apache.http.entity.mime.content.StringBody;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.codehaus.jettison.json.JSONException;
+import org.openecomp.sdc.be.dao.rest.HttpRestClient;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ImportTestTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ImportRestUtils extends BaseRestUtils {
+
+ private static Logger log = LoggerFactory.getLogger(ImportRestUtils.class.getName());
+ private static Properties downloadCsarHeaders = new Properties();
+
+ static {
+ downloadCsarHeaders.put("Accept", "application/octet-stream");
+ }
+
+ @SuppressWarnings("unused")
+ private static Integer importNormativeResource(NormativeTypesEnum resource, UserRoleEnum userRole) throws IOException {
+ Config config = Utils.getConfig();
+ CloseableHttpResponse response = null;
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), ContentType.APPLICATION_JSON));
+
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ httpPost.addHeader("USER_ID", userRole.getUserId());
+ httpPost.setEntity(mpBuilder.build());
+ response = client.execute(httpPost);
+ return response.getStatusLine().getStatusCode();
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+ }
+
+ public static RestResponse importResourceByName(ResourceReqDetails resourceDetails, User importer) throws Exception {
+ Config config = Utils.getConfig();
+ CloseableHttpResponse response = null;
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceDetails.getName())));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceDetails.getName(), resourceDetails.getName() + ".json"), ContentType.APPLICATION_JSON));
+
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ RestResponse restResponse = new RestResponse();
+ httpPost.addHeader("USER_ID", importer.getUserId());
+ httpPost.setEntity(mpBuilder.build());
+ response = client.execute(httpPost);
+ HttpEntity entity = response.getEntity();
+ String responseBody = null;
+ if (entity != null) {
+ InputStream instream = entity.getContent();
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(instream, writer);
+ responseBody = writer.toString();
+ try {
+
+ } finally {
+ instream.close();
+ }
+ }
+
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+ restResponse.setResponse(responseBody);
+
+ if (restResponse.getErrorCode() == STATUS_CODE_CREATED) {
+ resourceDetails.setUUID(ResponseParser.getUuidFromResponse(restResponse));
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse));
+ resourceDetails.setVersion(ResponseParser.getVersionFromResponse(restResponse));
+ resourceDetails.setCreatorUserId(importer.getUserId());
+ resourceDetails.setCreatorFullName(importer.getFullName());
+ }
+
+ return restResponse;
+
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+
+ }
+
+ public static RestResponse importNewResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
+ Config config = Utils.getConfig();
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
+ HttpEntity requestEntity = mpBuilder.build();
+ String url = String.format(Urls.IMPORT_USER_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+ Map<String, String> headers = new HashMap<String, String>();
+ headers.put("USER_ID", userRole.getUserId());
+
+ return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
+ }
+
+ public static RestResponse importNormativeResourceByName(String resourceName, UserRoleEnum userRole) throws IOException {
+ Config config = Utils.getConfig();
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resourceName)));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resourceName, resourceName + ".json"), ContentType.APPLICATION_JSON));
+ HttpEntity requestEntity = mpBuilder.build();
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort());
+ Map<String, String> headers = new HashMap<String, String>();
+ headers.put("USER_ID", userRole.getUserId());
+
+ return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
+ }
+
+ public static RestResponse importTestResource(ImportTestTypesEnum resource, UserRoleEnum userRole) throws IOException {
+ Config config = Utils.getConfig();
+ CloseableHttpResponse response = null;
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("resourceZip", new FileBody(getTestZipFile(resource.getFolderName())));
+ mpBuilder.addPart("resourceMetadata", new StringBody(getTestJsonStringOfFile(resource.getFolderName(), resource.getFolderName() + ".json"), ContentType.APPLICATION_JSON));
+
+ String url = String.format(Urls.IMPORT_RESOURCE_NORMATIVE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ CloseableHttpClient client = HttpClients.createDefault();
+ try {
+ HttpPost httpPost = new HttpPost(url);
+ RestResponse restResponse = new RestResponse();
+ httpPost.addHeader("USER_ID", UserRoleEnum.ADMIN.getUserId());
+ httpPost.setEntity(mpBuilder.build());
+ response = client.execute(httpPost);
+ HttpEntity entity = response.getEntity();
+ String responseBody = null;
+ if (entity != null) {
+ InputStream instream = entity.getContent();
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(instream, writer);
+ responseBody = writer.toString();
+ try {
+
+ } finally {
+ instream.close();
+ }
+ }
+
+ restResponse.setErrorCode(response.getStatusLine().getStatusCode());
+ // restResponse.setResponse(response.getEntity().toString());
+ restResponse.setResponse(responseBody);
+ return restResponse;
+ } finally {
+ closeResponse(response);
+ closeHttpClient(client);
+
+ }
+ }
+
+ public static Boolean removeNormativeTypeResource(NormativeTypesEnum current) throws FileNotFoundException, IOException, ClientProtocolException {
+ User user = new User(UserRoleEnum.ADMIN.getFirstName(), UserRoleEnum.ADMIN.getLastName(), UserRoleEnum.ADMIN.getUserId(), null, null, null);
+ RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(user, current.getNormativeName(), "1.0");
+ if (deleteResponse.getErrorCode() == 200) {
+ return true;
+ }
+ return false;
+ }
+
+ public static void validateImportTestTypesResp(ImportTestTypesEnum currResource, RestResponse restResponse) throws IOException, JSONException {
+
+ // assertTrue( status != ResourceUtils.STATUS_CODE_IMPORT_SUCCESS );
+
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(currResource.getActionStatus().name());
+
+ assertNotNull("check response object is not null after create service", restResponse);
+ assertNotNull("check error code exists in response after create service", restResponse.getErrorCode());
+ assertEquals("Check response code after create service", errorInfo.getCode(), restResponse.getErrorCode());
+
+ // validate create service response vs actual
+ List<String> variables = (currResource.getErrorParams() != null ? currResource.getErrorParams() : new ArrayList<String>());
+ if (restResponse.getErrorCode() != 200) {
+ ErrorValidationUtils.checkBodyResponseOnError(currResource.getActionStatus().name(), variables, restResponse.getResponse());
+ }
+ }
+
+ private static String getTestJsonStringOfFile(String folderName, String fileName) throws IOException {
+ // String sourceDir = "src/test/resources/CI/importResourceTests";
+ Config config = Utils.getConfig();
+ String sourceDir = config.getImportResourceTestsConfigDir();
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + folderName, fileName);
+ byte[] fileContent = Files.readAllBytes(filePath);
+ String content = new String(fileContent);
+ return content;
+ }
+
+ private static File getTestZipFile(String elementName) throws IOException {
+ Config config = Utils.getConfig();
+ String sourceDir = config.getImportResourceTestsConfigDir();
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, "normative-types-new-" + elementName + ".zip");
+ return filePath.toFile();
+ }
+
+ private static void closeHttpClient(CloseableHttpClient client) {
+ try {
+ if (client != null) {
+ client.close();
+ }
+ } catch (IOException e) {
+ log.debug("failed to close client or response: ", e);
+ }
+ }
+
+ private static void closeResponse(CloseableHttpResponse response) {
+ try {
+ if (response != null) {
+ response.close();
+ }
+ } catch (IOException e) {
+ log.debug("failed to close client or response: {}", e);
+ }
+ }
+
+ public static RestResponseAsByteArray getCsar(String csarUid, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_CSAR_USING_SIMULATOR, config.getCatalogBeHost(), config.getCatalogBePort(), csarUid);
+
+ String userId = sdncModifierDetails.getUserId();
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ // Gson gson = new Gson();
+ // String userBodyJson = gson.toJson(resourceDetails);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+
+ HttpRestClient httpRestClient = new HttpRestClient();
+
+ for (Map.Entry<String, String> mapEntry : headersMap.entrySet()) {
+
+ downloadCsarHeaders.put(mapEntry.getKey(), mapEntry.getValue());
+ }
+ RestResponseAsByteArray doGetAsByteArray = httpRestClient.doGetAsByteArray(url, downloadCsarHeaders);
+ // RestResponse getCsar = http.httpSendGet(url, headersMap);
+
+ return doGetAsByteArray;
+
+ }
+
+ private static File getGroupTypeZipFile(String elementName) throws IOException {
+ Config config = Utils.getConfig();
+ String sourceDir = config.getImportResourceTestsConfigDir();
+ sourceDir += File.separator + ".." + File.separator + "importTypesTest" + File.separator;
+ java.nio.file.Path filePath = FileSystems.getDefault().getPath(sourceDir + File.separator + elementName, elementName + ".zip");
+ return filePath.toFile();
+ }
+
+ public static RestResponse importNewGroupTypeByName(String groupTypeName, UserRoleEnum userRole) throws IOException {
+ Config config = Utils.getConfig();
+
+ MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create();
+
+ mpBuilder.addPart("groupTypesZip", new FileBody(getGroupTypeZipFile(groupTypeName)));
+ HttpEntity requestEntity = mpBuilder.build();
+ String url = String.format(Urls.IMPORT_GROUP_TYPE, config.getCatalogBeHost(), config.getCatalogBePort());
+ Map<String, String> headers = new HashMap<String, String>();
+ headers.put("USER_ID", userRole.getUserId());
+
+ return HttpRequest.sendHttpPostWithEntity(requestEntity, url, headers);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
new file mode 100644
index 0000000000..de7be077d1
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InputsRestUtils.java
@@ -0,0 +1,122 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstInputsMap;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+/**
+ * RestUtils for inputs
+ *
+ * @author il0695
+ *
+ */
+public class InputsRestUtils extends BaseRestUtils {
+
+ @SuppressWarnings("unused")
+ private static Logger logger = LoggerFactory.getLogger(InputsRestUtils.class.getName());
+
+ /**
+ * Add inputs to service
+ *
+ * @param component
+ * @param inputs
+ * @param userRole
+ * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
+ * @throws Exception
+ */
+ public static RestResponse addInput(Component component, ComponentInstInputsMap inputs, UserRoleEnum userRole) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.ADD_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId());
+ String json = new Gson().toJson(inputs);
+ return sendPost(url, json, userRole.getUserId(), acceptHeaderData);
+ }
+
+ /**
+ * Get all Component inputs
+ *
+ * @param component
+ * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
+ * @throws Exception
+ */
+ public static RestResponse getComponentInputs(Component component) throws Exception {
+ Config config = Utils.getConfig();
+ //services/{componentId}/inputs
+ String url = String.format(Urls.GET_COMPONENT_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId());
+ return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ }
+
+ /**
+ * Get all inputs of component instance
+ *
+ * @param parentComponent
+ * @param componentInstance
+ * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
+ * @throws Exception
+ */
+ public static RestResponse getComponentInstanceInputs(Component parentComponent, ComponentInstance componentInstance) throws Exception {
+ Config config = Utils.getConfig();
+ //{componentType}/{componentId}/componentInstances/{instanceId}/{originComonentUid}/inputs
+ String url = String.format(Urls.GET_COMPONENT_INSTANCE_INPUTS, config.getCatalogBeHost(), config.getCatalogBePort(), ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), componentInstance.getUniqueId(), componentInstance.getComponentUid());
+ return sendGet(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ }
+
+ /**
+ * Delete input from component
+ *
+ * @param parentComponent
+ * @param inputId
+ * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
+ * @throws Exception
+ */
+ public static RestResponse deleteInputFromComponent(Component parentComponent, String inputId) throws Exception {
+ return deleteInputFromComponent(ComponentTypeEnum.findParamByType(parentComponent.getComponentType()), parentComponent.getUniqueId(), inputId);
+ }
+
+ /**
+ * Delete input from component
+ *
+ * @param componentType
+ * @param componentId
+ * @param inputUniqueId
+ * @return {@link org.openecomp.sdc.ci.tests.datatypes.http.RestResponse}
+ * @throws Exception
+ */
+ public static RestResponse deleteInputFromComponent(String componentType, String componentId, String inputUniqueId) throws Exception {
+ Config config = Utils.getConfig();
+ //{componentType}/{componentId}/delete/{inputId}/input
+ String url = String.format(Urls.DELETE_INPUT_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, componentId, inputUniqueId);
+ return sendDelete(url, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER).getUserId());
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
new file mode 100644
index 0000000000..34651c1b7a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/LifecycleRestUtils.java
@@ -0,0 +1,360 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.json.simple.JSONObject;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LifecycleRestUtils extends BaseRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(LifecycleRestUtils.class.getName());
+ public static final String COMMENT = "comment";
+
+ public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
+ String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
+ return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum,
+ createLifecycleCommentJson(COMMENT));
+ }
+
+ public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
+ String version, LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException {
+
+ return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum, LifecycleChangeInfo);
+
+ }
+
+ public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
+
+ return changeResourceState(resourceDetails, sdncModifierDetails, LifeCycleStatesEnum,
+ createLifecycleCommentJson(COMMENT));
+
+ }
+
+ public static RestResponse changeResourceState(ResourceReqDetails resourceDetails, String modifierUserId,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws IOException {
+ User user = new User();
+ user.setUserId(modifierUserId);
+ return changeResourceState(resourceDetails, user, LifeCycleStatesEnum, createLifecycleCommentJson(COMMENT));
+ }
+
+ private static RestResponse changeResourceState(ResourceReqDetails resourceDetails, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum, String LifecycleChangeInfo) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CHANGE_RESOURCE_LIFECYCLE_STATE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), resourceDetails.getUniqueId(), LifeCycleStatesEnum);
+ // System.out.println("url: " + url);
+
+ RestResponse LifeCycleStatesEnumResourceResponse = sendPost(url, LifecycleChangeInfo,
+ sdncModifierDetails.getUserId(), acceptHeaderData);
+ if (LifeCycleStatesEnumResourceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
+ String stateFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumResourceResponse.getResponse(), "lifecycleState");
+ resourceDetails.setVersion(ResponseParser.getVersionFromResponse(LifeCycleStatesEnumResourceResponse));
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(LifeCycleStatesEnumResourceResponse));
+ if (stateFromJsonResponse != null) {
+ resourceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse));
+ }
+ }
+ return LifeCycleStatesEnumResourceResponse;
+ }
+
+ public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
+ String version, LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
+ {
+ return changeServiceState(serviceDetails, sdncModifierDetails, version, LifeCycleStatesEnum,
+ createLifecycleCommentJson(COMMENT));
+ }
+ }
+
+ public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
+ {
+ return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum,
+ createLifecycleCommentJson(COMMENT));
+ }
+ }
+
+ public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
+ {
+ return changeServiceState(serviceDetails, sdncModifierDetails, null, LifeCycleStatesEnum,
+ lifecycleChangeInfo);
+ }
+ }
+
+ public static RestResponse changeServiceState(ServiceReqDetails serviceDetails, User sdncModifierDetails,
+ String version, LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
+
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CHANGE_SERVICE_LIFECYCLE_STATE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), serviceDetails.getUniqueId(), LifeCycleStatesEnum);
+ // System.out.println("url: " + url);
+ RestResponse LifeCycleStatesEnumServiceResponse = http.httpSendPost(url, lifecycleChangeInfo, headersMap);
+ if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
+ String serviceUniqueId = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
+ serviceDetails.setUniqueId(serviceUniqueId);
+ String serviceVersion = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
+ serviceDetails.setVersion(serviceVersion);
+ String stateFromJsonResponse = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
+ serviceDetails.setLifecycleState(LifecycleStateEnum.valueOf(stateFromJsonResponse));
+ }
+ return LifeCycleStatesEnumServiceResponse;
+ }
+
+ public static RestResponse changeProductState(Product product, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
+ {
+ return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, lifecycleChangeInfo);
+ }
+ }
+
+ public static RestResponse changeProductState(Product product, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
+ {
+ return _changeProductState(product, sdncModifierDetails, LifeCycleStatesEnum, COMMENT);
+ }
+ }
+
+ public static RestResponse changeProductState(ProductReqDetails productDetails, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), productDetails.getUniqueId(), LifeCycleStatesEnum);
+ RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
+ sdncModifierDetails.getUserId(), acceptHeaderData);
+ if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
+ String productUniqueId = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
+ productDetails.setUniqueId(productUniqueId);
+ String productVersion = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
+ productDetails.setVersion(productVersion);
+ String newLifecycleState = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
+ productDetails.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
+ }
+ return LifeCycleStatesEnumServiceResponse;
+
+ }
+
+ public static RestResponse changeComponentState(Component component, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CHANGE_COMPONENT_LIFECYCLE_STATE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(component.getComponentType()),
+ component.getUniqueId(), LifeCycleStatesEnum);
+ RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(COMMENT),
+ sdncModifierDetails.getUserId(), acceptHeaderData);
+ if (LifeCycleStatesEnumServiceResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
+ String productUniqueId = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "uniqueId");
+ component.setUniqueId(productUniqueId);
+ String productVersion = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "version");
+ component.setVersion(productVersion);
+ String newLifecycleState = ResponseParser
+ .getValueFromJsonResponse(LifeCycleStatesEnumServiceResponse.getResponse(), "lifecycleState");
+ component.setLifecycleState(LifecycleStateEnum.valueOf(newLifecycleState));
+ }
+ return LifeCycleStatesEnumServiceResponse;
+
+ }
+
+ public static RestResponse certifyResource(ResourceReqDetails resourceDetails) throws Exception {
+ RestResponse restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ // if (restResponseResource.getErrorCode() == 200){
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ // }else
+ // return restResponseResource;
+ User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ if (restResponseResource.getErrorCode() == 200) {
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails,
+ LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponseResource;
+ if (restResponseResource.getErrorCode() == 200) {
+ restResponseResource = LifecycleRestUtils.changeResourceState(resourceDetails, testerDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponseResource.getErrorCode() == 200) {
+ String newVersion = ResponseParser.getVersionFromResponse(restResponseResource);
+ resourceDetails.setVersion(newVersion);
+ resourceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ resourceDetails.setLastUpdaterUserId(testerDetails.getUserId());
+ resourceDetails.setLastUpdaterFullName(testerDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseResource);
+ resourceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponseResource;
+ }
+
+ public static RestResponse certifyService(ServiceReqDetails serviceDetails) throws Exception {
+ RestResponse restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CHECKIN);
+ // if (restResponseService.getErrorCode() == 200){
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), LifeCycleStatesEnum.CERTIFICATIONREQUEST);
+ // }else
+ // return restResponseService;
+ if (restResponseService.getErrorCode() == 200) {
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.TESTER), LifeCycleStatesEnum.STARTCERTIFICATION);
+ } else
+ return restResponseService;
+ if (restResponseService.getErrorCode() == 200) {
+ User testerDetails = ElementFactory.getDefaultUser(UserRoleEnum.TESTER);
+ restResponseService = LifecycleRestUtils.changeServiceState(serviceDetails, testerDetails,
+ LifeCycleStatesEnum.CERTIFY);
+ if (restResponseService.getErrorCode() == 200) {
+ String newVersion = ResponseParser.getVersionFromResponse(restResponseService);
+ serviceDetails.setVersion(newVersion);
+ serviceDetails.setLifecycleState(LifecycleStateEnum.CERTIFIED);
+ serviceDetails.setLastUpdaterUserId(testerDetails.getUserId());
+ serviceDetails.setLastUpdaterFullName(testerDetails.getFullName());
+ String uniqueIdFromRresponse = ResponseParser.getUniqueIdFromResponse(restResponseService);
+ serviceDetails.setUniqueId(uniqueIdFromRresponse);
+ }
+ }
+ return restResponseService;
+ }
+
+ private static RestResponse _changeProductState(Product product, User sdncModifierDetails,
+ LifeCycleStatesEnum LifeCycleStatesEnum, String lifecycleChangeInfo) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CHANGE_PRODUCT_LIFECYCLE_STATE, config.getCatalogBeHost(),
+ config.getCatalogBePort(), product.getUniqueId(), LifeCycleStatesEnum);
+ RestResponse LifeCycleStatesEnumServiceResponse = sendPost(url, createLifecycleCommentJson(lifecycleChangeInfo),
+ sdncModifierDetails.getUserId(), acceptHeaderData);
+
+ return LifeCycleStatesEnumServiceResponse;
+ }
+
+ public static String createLifecycleCommentJson(String commentContent) {
+ String res = null;
+ if (commentContent != null) {
+ res = "{\"userRemarks\": \"" + commentContent + "\"}";
+ }
+ return res;
+ }
+
+ public static void checkLCS_Response(RestResponse response) {
+ checkStatusCode(response, "change lifecycle request failed", false, STATUS_CODE_SUCCESS);
+ }
+
+ private static Map<String, String> prepareHeadersMap(User sdncModifierDetails) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ return headersMap;
+ }
+
+ public static RestResponse changeDistributionStatus(ServiceReqDetails serviceDetails, String version, User user,
+ String userRemarks, DistributionStatusEnum reqDistributionStatus) throws Exception {
+ String uniqueId = serviceDetails.getUniqueId();
+ if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_APPROVED) {
+ return sendApproveDistribution(user, uniqueId, userRemarks);
+ } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTION_REJECTED) {
+ return rejectDistribution(user, userRemarks, uniqueId);
+ } else if (reqDistributionStatus == DistributionStatusEnum.DISTRIBUTED) {
+ Config config = Utils.getConfig();
+ // String url =
+ // String.format("http://%s:%s/sdc2/rest/v1/catalog/services/%s/tempUrlToBeDeleted",
+ // config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
+ String url = String.format(Urls.ACTIVATE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
+ uniqueId, "PROD");
+ return sendDistrState(user, userRemarks, url);
+ } else
+ return null;
+
+ }
+
+ public static RestResponse sendApproveDistribution(User sdncModifierDetails, String uniqueId, String userRemarks)
+ throws FileNotFoundException, IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.APPROVE_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
+ uniqueId);
+ return sendDistrState(sdncModifierDetails, userRemarks, url);
+ }
+
+ public static RestResponse rejectDistribution(ServiceReqDetails serviceDetails, String version, User user,
+ String userRemarks) throws Exception {
+ return rejectDistribution(user, userRemarks, serviceDetails.getUniqueId());
+ }
+
+ public static RestResponse rejectDistribution(User user, String userRemarks, String uniqueId)
+ throws FileNotFoundException, IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
+ uniqueId);
+ return sendDistrState(user, userRemarks, url);
+ }
+
+ private static RestResponse sendDistrState(User user, String userRemarks, String url) throws IOException {
+ Map<String, String> headersMap = prepareHeadersMap(user);
+ Map<String, String> userRemarksMap = new HashMap<String, String>();
+ userRemarksMap.put("userRemarks", userRemarks);
+
+ String serviceBodyJson = new JSONObject().toJSONString(userRemarksMap);
+
+ HttpRequest httpRequest = new HttpRequest();
+ logger.debug(url);
+ logger.debug("Send POST request to create service: {}", url);
+ logger.debug("Service body: {}", serviceBodyJson);
+ logger.debug("Service headers: {}", headersMap);
+ RestResponse rejectDistributionResponse = httpRequest.httpSendPost(url, serviceBodyJson, headersMap);
+
+ return rejectDistributionResponse;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
new file mode 100644
index 0000000000..8e617ed75c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ProductRestUtils.java
@@ -0,0 +1,185 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ProductReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+public class ProductRestUtils extends BaseRestUtils {
+ private static Gson gson = new Gson();
+ private static Logger logger = LoggerFactory.getLogger(ProductRestUtils.class.getName());
+
+ public static RestResponse createProduct(ProductReqDetails product, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
+ String serviceBodyJson = gson.toJson(product);
+
+ logger.debug("Send POST request to create service: {}", url);
+ logger.debug("Service body: {}", serviceBodyJson);
+
+ RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
+ if (res.getErrorCode() == STATUS_CODE_CREATED) {
+ product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ product.setVersion(ResponseParser.getVersionFromResponse(res));
+ product.setUUID(ResponseParser.getUuidFromResponse(res));
+ // Creator details never change after component is created - Ella,
+ // 12/1/2016
+ product.setCreatorUserId(user.getUserId());
+ product.setCreatorFullName(user.getFullName());
+ product.setLastUpdaterFullName(user.getFullName());
+ product.setLastUpdaterUserId(user.getUserId());
+ product.setLastUpdaterFullName(user.getFullName());
+ product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ product.setVersion("0.1");
+ String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate");
+ product.setLastUpdateDate(Long.parseLong(lastUpdate, 10));
+ product.setCreationDate(Long.parseLong(lastUpdate, 10));
+ }
+ return res;
+ }
+
+ public static RestResponse updateProduct(ProductReqDetails product, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(),
+ product.getUniqueId());
+ String serviceBodyJson = gson.toJson(product);
+
+ logger.debug("Send POST request to create service: {}", url);
+ logger.debug("Service body: {}", serviceBodyJson);
+
+ RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
+ if (res.getErrorCode() == STATUS_CODE_CREATED) {
+ product.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ product.setVersion(ResponseParser.getVersionFromResponse(res));
+ product.setUUID(ResponseParser.getUuidFromResponse(res));
+ // Creator details never change after component is created - Ella,
+ // 12/1/2016
+ product.setCreatorUserId(user.getUserId());
+ product.setCreatorFullName(user.getFullName());
+ product.setLastUpdaterFullName(user.getFullName());
+ product.setLastUpdaterUserId(user.getUserId());
+ product.setLastUpdaterFullName(user.getFullName());
+ product.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
+ String valueFromJsonResponse = ResponseParser.getValueFromJsonResponse(res.getResponse(), "version");
+ product.setVersion(valueFromJsonResponse);
+ String lastUpdate = ResponseParser.getValueFromJsonResponse(res.getResponse(), "lastUpdateDate");
+ product.setLastUpdateDate(Long.parseLong(lastUpdate, 10));
+ product.setCreationDate(Long.parseLong(lastUpdate, 10));
+ }
+ return res;
+ }
+
+ public static RestResponse createProduct_Invalid_Json(String userId) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ RestResponse res = sendPost(url, "kukumuku", userId, acceptHeaderData);
+ return res;
+ }
+
+ public static RestResponse deleteProduct(String id, String userId) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), id);
+ return sendDelete(url, userId);
+ }
+
+ public static RestResponse getProduct(String productId, String userId) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), productId);
+ logger.debug("Send GET request to get product: {}", url);
+
+ return sendGet(url, userId);
+ }
+
+ public static RestResponse getFollowed(String userId) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
+ logger.debug("Send GET request to get user followed page: {}", url);
+ return sendGet(url, userId);
+
+ }
+
+ public static RestResponse changeProductLifeCycle(Product product, User userModifier, LifeCycleStatesEnum lifeCycle)
+ throws Exception {
+ String checkinComment = "my comment";
+ RestResponse changeLifeCycleResponse = LifecycleRestUtils.changeProductState(product, userModifier, lifeCycle,
+ checkinComment);
+ if (changeLifeCycleResponse.getErrorCode() == STATUS_CODE_SUCCESS) {
+ product.setLastUpdaterUserId(userModifier.getUserId());
+ product.setLastUpdaterFullName(userModifier.getFullName());
+ String latestVersion = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
+ "version");
+ product.setVersion(latestVersion);
+ String lifecycleState = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
+ "lifecycleState");
+ product.setLifecycleState((LifecycleStateEnum.valueOf(lifecycleState)));
+ String uniqueId = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
+ "uniqueId");
+ product.setUniqueId(uniqueId);
+ String lastUpdate = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(),
+ "lastUpdateDate");
+ product.setLastUpdateDate((Long.parseLong(lastUpdate, 10)));
+ String uuid = ResponseParser.getValueFromJsonResponse(changeLifeCycleResponse.getResponse(), "uuid");
+ product.setUUID(uuid);
+ }
+ return changeLifeCycleResponse;
+ }
+
+ public static RestResponse changeServiceInstanceVersion(String componentUniqueId,
+ String serviceInstanceToReplaceUniqueId, String serviceUniqueId, User sdncModifierDetails,
+ ComponentTypeEnum componentType) throws IOException {
+ Config config = Utils.getConfig();
+ String resourceUid = ("{\"componentUid\":\"" + serviceUniqueId + "\"}");
+ String url = String.format(Urls.CHANGE__RESOURCE_INSTANCE_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), ComponentTypeEnum.findParamByType(componentType), componentUniqueId,
+ serviceInstanceToReplaceUniqueId);
+ RestResponse changeResourceInstanceVersion = sendPost(url, resourceUid, sdncModifierDetails.getUserId(),
+ acceptHeaderData);
+ return changeResourceInstanceVersion;
+
+ }
+
+ public static RestResponse getProductByNameAndVersion(String productName, String productVersion, String userId)
+ throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_PRODUCT_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), productName, productVersion);
+ logger.debug("Send GET request to get product by name and version: {}", url);
+ return sendGet(url, userId);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
new file mode 100644
index 0000000000..56ff5ec12b
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/PropertyRestUtils.java
@@ -0,0 +1,310 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.PropertyDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class PropertyRestUtils extends BaseRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(PropertyRestUtils.class.getName());
+
+ public static RestResponse createProperty(String resourceId, String body, User user) throws Exception {
+ Config config = Config.instance();
+ String url = String.format(Urls.CREATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId);
+
+ return sendPost(url, body, user.getUserId(), acceptHeaderData);
+ }
+
+ public static RestResponse updateProperty(String resourceId, String propertyId, String body, User user)
+ throws Exception {
+ Config config = Config.instance();
+
+ String url = String.format(Urls.UPDATE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId, propertyId);
+ return sendPut(url, body, user.getUserId(), acceptHeaderData);
+ }
+
+ public static RestResponse getProperty(String resourceId, String propertyId, User user) throws Exception {
+ Config config = Config.instance();
+ String url = String.format(Urls.GET_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId,
+ propertyId);
+ return sendGet(url, user.getUserId());
+ }
+
+ public static RestResponse deleteProperty(String resourceId, String propertyId, User user) throws Exception {
+ Config config = Config.instance();
+ String url = String.format(Urls.DELETE_PROPERTY, config.getCatalogBeHost(), config.getCatalogBePort(),
+ resourceId, propertyId);
+
+ return sendDelete(url, user.getUserId());
+ }
+
+ public static ComponentInstanceProperty getPropFromListByPropNameAndType(List<ComponentInstanceProperty> propList,
+ String propNameToUpdate, String propTypeToUpdate) {
+ for (ComponentInstanceProperty componentInstanceProperty : propList) {
+ if (componentInstanceProperty.getName().equals(propNameToUpdate)
+ && componentInstanceProperty.getType().equals(propTypeToUpdate)) {
+ return componentInstanceProperty;
+ }
+ }
+ return null;
+ }
+
+ public static ComponentInstanceProperty getPropFromListByPropNameTypeAndPath(
+ List<ComponentInstanceProperty> propList, String propNameToUpdate, String propTypeToUpdate,
+ List<String> path) {
+ for (ComponentInstanceProperty componentInstanceProperty : propList) {
+ if (componentInstanceProperty.getPath() == null) {
+ return getPropFromListByPropNameAndType(propList, propNameToUpdate, propTypeToUpdate);
+ }
+ if (componentInstanceProperty.getName().equals(propNameToUpdate)
+ && componentInstanceProperty.getType().equals(propTypeToUpdate)
+ && path.containsAll(componentInstanceProperty.getPath())) {
+ return componentInstanceProperty;
+ }
+ }
+ return null;
+ }
+
+ public static ComponentInstanceProperty getPropFromListByPropIdAndPath(List<ComponentInstanceProperty> propList,
+ String propId, List<String> path) {
+
+ for (ComponentInstanceProperty componentInstanceProperty : propList) {
+ if (path != null) {
+ if (componentInstanceProperty.getUniqueId().equals(propId)
+ && componentInstanceProperty.getPath().equals(path)) {
+ return componentInstanceProperty;
+ }
+ } else {
+ if (componentInstanceProperty.getUniqueId().equals(propId)) {
+ return componentInstanceProperty;
+ }
+ }
+ }
+ return null;
+ }
+
+ public static void comparePropertyLists(List<ComponentInstanceProperty> expectedList,
+ List<ComponentInstanceProperty> actualList, Boolean isUpdate) {
+
+ assertTrue(
+ "list size are not equals, expected size is: " + expectedList.size() + " ,actual: " + actualList.size(),
+ expectedList.size() == actualList.size());
+ Boolean flag = false;
+ for (ComponentInstanceProperty expectedcompInstProp : expectedList) {
+ for (ComponentInstanceProperty actualcompInstProp : actualList) {
+ flag = comparePropertyObjects(expectedcompInstProp, actualcompInstProp, isUpdate);
+ if (flag) {
+ break;
+ }
+ }
+ }
+ // System.out.println("expected: " + expectedList + ", actual: " +
+ // actualList);
+ logger.debug("expected: {}, actual: {}", expectedList, actualList);
+ assertTrue("actual lists does not contain all uniqeIds", flag);
+ }
+
+ public static Boolean comparePropertyObjects(ComponentInstanceProperty expectedCompInstProp,
+ ComponentInstanceProperty actualCompInstProp, Boolean isUpdate) {
+ String uniqueId = expectedCompInstProp.getUniqueId();
+ String type = expectedCompInstProp.getType();
+ String defaulValue = expectedCompInstProp.getDefaultValue();
+ if (actualCompInstProp.getUniqueId().equals(uniqueId)
+ && actualCompInstProp.getPath().equals(expectedCompInstProp.getPath())) {
+ assertTrue("expected type is: " + type + " ,actual: " + actualCompInstProp.getType(),
+ actualCompInstProp.getType().equals(type));
+ if (defaulValue == null) {
+ assertTrue(
+ "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(),
+ actualCompInstProp.getDefaultValue() == defaulValue);
+ } else {
+ assertTrue(
+ "expected defaulValue is: " + defaulValue + " ,actual: " + actualCompInstProp.getDefaultValue(),
+ actualCompInstProp.getDefaultValue().equals(defaulValue));
+ }
+ if (isUpdate) {
+ assertTrue(
+ "actual [Value] parameter " + actualCompInstProp.getName()
+ + "should equal to expected [Value]: " + actualCompInstProp.getValue() + " ,Value: "
+ + actualCompInstProp.getValue(),
+ actualCompInstProp.getValue().equals(expectedCompInstProp.getValue()));
+ assertNotNull("valueId is null", actualCompInstProp.getValueUniqueUid());
+ } else {
+ if (defaulValue == null) {
+ assertTrue(
+ "actual [Value] parameter " + actualCompInstProp.getName()
+ + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue()
+ + " ,defaultValue: " + actualCompInstProp.getDefaultValue(),
+ actualCompInstProp.getValue() == expectedCompInstProp.getDefaultValue());
+ } else {
+ assertTrue(
+ "actual [Value] parameter " + actualCompInstProp.getName()
+ + "should equal to expected [defaultValue]: " + actualCompInstProp.getValue()
+ + " ,defaultValue: " + actualCompInstProp.getDefaultValue(),
+ actualCompInstProp.getValue().equals(expectedCompInstProp.getDefaultValue()));
+ }
+ assertNull("valueId is not null", actualCompInstProp.getValueUniqueUid());
+ }
+ return true;
+ }
+ return false;
+ }
+
+ public static List<ComponentInstanceProperty> addResourcePropertiesToList(Resource resource,
+ List<ComponentInstanceProperty> listToFill) {
+ for (PropertyDefinition prop : resource.getProperties()) {
+ listToFill.add(new ComponentInstanceProperty(prop, null, null));
+ }
+ return listToFill;
+ }
+
+ public static List<ComponentInstanceProperty> addComponentInstPropertiesToList(Component component,
+ List<ComponentInstanceProperty> listToFill, String componentId) {
+
+ if (componentId != null) {
+ List<ComponentInstanceProperty> list = component.getComponentInstancesProperties().get(componentId);
+ for (ComponentInstanceProperty prop : list) {
+ ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null, null);
+ componentInstanceProperty.setPath(prop.getPath());
+ componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid());
+ componentInstanceProperty.setValue(prop.getValue());
+ listToFill.add(componentInstanceProperty);
+ }
+ } else {
+ Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component
+ .getComponentInstancesProperties();
+ for (Map.Entry<String, List<ComponentInstanceProperty>> componentInstanceProperties : componentInstancesProperties
+ .entrySet()) {
+ for (ComponentInstanceProperty prop : componentInstanceProperties.getValue()) {
+ ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(prop, null,
+ null);
+ componentInstanceProperty.setPath(prop.getPath());
+ componentInstanceProperty.setValueUniqueUid(prop.getValueUniqueUid());
+ componentInstanceProperty.setValue(prop.getValue());
+ listToFill.add(componentInstanceProperty);
+ }
+ }
+ }
+
+ if (component.getComponentType().getValue().equals("Resource")) {
+ for (PropertyDefinition prop : ((Resource) component).getProperties()) {
+ listToFill.add(new ComponentInstanceProperty(prop, null, null));
+ }
+ }
+ return listToFill;
+ }
+
+ public static ComponentInstanceProperty getCompPropInstListByInstIdAndPropName(Component component,
+ ComponentInstance componentInstanceDetails, String name, String type) {
+ List<ComponentInstanceProperty> propList = component.getComponentInstancesProperties()
+ .get(componentInstanceDetails.getUniqueId());
+ if (propList != null) {
+ return getPropFromListByPropNameAndType(propList, name, type);
+ }
+ return null;
+ }
+
+ private static void updatePropertyListWithPathParameter(Resource resource, List<String> path,
+ List<ComponentInstanceProperty> expectedPropertyList) {
+ List<PropertyDefinition> propertyList = resource.getProperties();
+ for (PropertyDefinition propertyDefinition : propertyList) {
+ ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameAndType(
+ expectedPropertyList, propertyDefinition.getName(), propertyDefinition.getType());
+ ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove;
+ propDetailsToAdd.setPath(path);
+ expectedPropertyList.remove(propDetailsToRemove);
+ expectedPropertyList.add(propDetailsToAdd);
+ }
+ }
+
+ private static void updatePropertyListWithPathParameterOnCompInst(Service service, List<String> path,
+ List<ComponentInstanceProperty> expectedPropertyList) {
+ List<ComponentInstanceProperty> servicePropertyList = new ArrayList<>();
+ servicePropertyList = PropertyRestUtils.addComponentInstPropertiesToList(service, servicePropertyList,
+ path.get(0));
+
+ for (ComponentInstanceProperty serviceCompInstProperty : servicePropertyList) {
+ ComponentInstanceProperty propDetailsToRemove = PropertyRestUtils.getPropFromListByPropNameTypeAndPath(
+ expectedPropertyList, serviceCompInstProperty.getName(), serviceCompInstProperty.getType(),
+ serviceCompInstProperty.getPath());
+ ComponentInstanceProperty propDetailsToAdd = propDetailsToRemove;
+ List<String> tempPathList = new ArrayList<String>();
+ for (String tempPath : path) {
+ tempPathList.add(tempPath);
+ }
+ // path parameter can not contain the same service unique ID twice
+ if (propDetailsToAdd.getPath() != null
+ && !propDetailsToAdd.getPath().get(0).contains(service.getUniqueId())) {
+ if (!propDetailsToAdd.getPath().containsAll(tempPathList)) {
+ tempPathList.addAll(propDetailsToAdd.getPath());
+ }
+ }
+ propDetailsToAdd.setPath(tempPathList);
+ expectedPropertyList.remove(propDetailsToRemove);
+ expectedPropertyList.add(propDetailsToAdd);
+ }
+ }
+
+ public static void updatePropertyListWithPathOnResource(ComponentInstance componentInstDetails, Resource resource,
+ List<ComponentInstanceProperty> list, Component container) {
+ List<String> path = new ArrayList<>();
+ if (container != null) {
+ List<ComponentInstance> componentInstances = container.getComponentInstances();
+ for (ComponentInstance componentInstance : componentInstances) {
+ if (componentInstance.getNormalizedName().equals(componentInstDetails.getNormalizedName())) {
+ path.add(componentInstance.getUniqueId());
+ break;
+ }
+ }
+
+ } else {
+ path.add(componentInstDetails.getUniqueId());
+ }
+ updatePropertyListWithPathParameter(resource, path, list);
+ }
+
+ public static void updatePropertyListWithPathOnComponentInstance(ComponentInstance componentInstDetails,
+ Service service, List<ComponentInstanceProperty> list) {
+ List<String> path = new ArrayList<>();
+ path.add(componentInstDetails.getUniqueId());
+ updatePropertyListWithPathParameterOnCompInst(service, path, list);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
new file mode 100644
index 0000000000..16ffd2f9e2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java
@@ -0,0 +1,575 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.http.client.ClientProtocolException;
+import org.json.JSONException;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
+import org.openecomp.sdc.be.model.CapabilityDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.RequirementDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.RelationshipInstData;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.common.util.GeneralUtility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+public class ResourceRestUtils extends BaseRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(ResourceRestUtils.class.getName());
+
+ // ****** CREATE *******
+
+ public static RestResponse createResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws Exception {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ String userId = sdncModifierDetails.getUserId();
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson);
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(userBodyJson);
+ RestResponse createResourceResponse = http.httpSendPost(url, userBodyJson, headersMap);
+ if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
+ resourceDetails.setUUID(ResponseParser.getUuidFromResponse(createResourceResponse));
+ resourceDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
+ String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterUserId");
+ resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
+ String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(createResourceResponse.getResponse(), "lastUpdaterFullName");
+ resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
+ // Creator details never change after component is created - Ella,
+ // 12/1/2016
+ resourceDetails.setCreatorUserId(userId);
+ resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
+ }
+ return createResourceResponse;
+
+ }
+
+ public static RestResponse createImportResource(ImportReqDetails importReqDetails, User sdncModifierDetails, Map<String, String> additionalHeaders) throws JSONException, IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort());
+ String userId = sdncModifierDetails.getUserId();
+
+ Gson gson = new Gson();
+ String resourceImportBodyJson = gson.toJson(importReqDetails);
+ HttpRequest http = new HttpRequest();
+ // System.out.println(url);
+ // System.out.println(resourceImportBodyJson);
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+ if (additionalHeaders != null) {
+ headersMap.putAll(additionalHeaders);
+ } else {
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), ArtifactRestUtils.calculateMD5(resourceImportBodyJson));
+ }
+
+ RestResponse createResourceResponse = http.httpSendPost(url, resourceImportBodyJson, headersMap);
+ if (createResourceResponse.getErrorCode() == STATUS_CODE_CREATED) {
+ importReqDetails.setVersion(ResponseParser.getVersionFromResponse(createResourceResponse));
+ importReqDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(createResourceResponse));
+ // Creator details never change after component is created - Ella,
+ // 12/1/2016
+ importReqDetails.setCreatorUserId(userId);
+ importReqDetails.setCreatorFullName(sdncModifierDetails.getFullName());
+ importReqDetails.setToscaResourceName(ResponseParser.getToscaResourceNameFromResponse(createResourceResponse));
+ importReqDetails.setDerivedList(ResponseParser.getDerivedListFromJson(createResourceResponse));
+ }
+ return createResourceResponse;
+
+ }
+
+ // ***** DELETE ****
+ public static RestResponse deleteResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, String version) throws IOException {
+
+ if (resourceDetails.getUniqueId() != null) {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceDetails.getName(), version);
+ return sendDelete(url, sdncModifierDetails.getUserId());
+ } else {
+ return null;
+ }
+
+ }
+
+ public static RestResponse markResourceToDelete(String resourceId, String userId) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ RestResponse sendDelete = sendDelete(url, userId);
+
+ return sendDelete;
+
+ }
+
+ public static RestResponse deleteResource(String resourceId, String userId) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ RestResponse sendDelete = sendDelete(url, userId);
+
+ deleteMarkedResources(userId);
+
+ return sendDelete;
+
+ }
+
+ public static void deleteMarkedResources(String userId) throws IOException {
+ String url;
+ Config config = Utils.getConfig();
+ url = String.format(Urls.DELETE_MARKED_RESOURCES, config.getCatalogBeHost(), config.getCatalogBePort());
+ sendDelete(url, userId);
+ }
+
+ public static RestResponse deleteResourceByNameAndVersion(User sdncModifierDetails, String resourceName, String resourceVersion) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceName, resourceVersion);
+ RestResponse sendDelete = sendDelete(url, sdncModifierDetails.getUserId());
+
+ deleteMarkedResources(sdncModifierDetails.getUserId());
+
+ return sendDelete;
+ }
+
+ public static Boolean deleteResourceByNameAndVersion(String resourceName, String resourceVersion) throws IOException {
+ RestResponse deleteResponse = ResourceRestUtils.deleteResourceByNameAndVersion(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceName, resourceVersion);
+ return checkErrorCode(deleteResponse);
+ }
+
+ public static Boolean removeResource(String resourceId) throws FileNotFoundException, IOException, ClientProtocolException {
+ RestResponse response = deleteResource(resourceId, ElementFactory.getDefaultUser(UserRoleEnum.ADMIN).getUserId());
+ return checkErrorCode(response);
+ }
+
+ // ************** GET *************
+ public static RestResponse getResource(User sdncModifierDetails, String uniqueId) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse getModule(User sdncModifierDetails, String componentId, String moduleId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_MODULE_BY_ID, config.getCatalogBeHost(), config.getCatalogBePort(), componentId, moduleId);
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse getLatestResourceFromCsarUuid(User sdncModifierDetails, String csarUuid) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_RESOURCE_BY_CSAR_UUID, config.getCatalogBeHost(), config.getCatalogBePort(), csarUuid);
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse getResource(ResourceReqDetails resourceDetails, User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceDetails.getUniqueId());
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static RestResponse getResourceByNameAndVersion(String userId, String resourceName, String resourceVersion) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_RESOURCE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), resourceName, resourceVersion);
+
+ return sendGet(url, userId);
+ }
+
+ public static RestResponse getResourceList(User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ return sendGet(url, sdncModifierDetails.getUserId());
+
+ }
+
+ public static RestResponse getResource(String resourceId) throws ClientProtocolException, IOException {
+ return getResource(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), resourceId);
+ }
+
+ public static RestResponse getLatestResourceFromCsarUuid(String csarUuid) throws ClientProtocolException, IOException {
+ return getLatestResourceFromCsarUuid(ElementFactory.getDefaultUser(UserRoleEnum.ADMIN), csarUuid);
+ }
+
+ public static RestResponse getResourceLatestVersionList(User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_RESOURCE_lATEST_VERSION, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ return sendGet(url, sdncModifierDetails.getUserId());
+
+ }
+
+ public static RestResponse putAllCategoriesTowardsCatalogFeWithUuidNotAllowed(String uuid) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), BaseRestUtils.RESOURCE_COMPONENT_TYPE);
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), uuid);
+ HttpRequest http = new HttpRequest();
+
+ logger.debug("Send PUT request to get all categories (should be 405): {}", url);
+ return http.httpSendByMethod(url, "PUT", null, headersMap);
+ }
+
+ public static RestResponse getAllTagsTowardsCatalogBe() throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ALL_TAGS, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+
+ // logger.debug("Send GET request to get all tags: {}", url);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ public static RestResponse getAllPropertyScopesTowardsCatalogBe() throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_PROPERTY_SCOPES_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
+
+ // logger.debug("Send GET request to get all property scopes: {}", url);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ public static RestResponse getAllArtifactTypesTowardsCatalogBe() throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ALL_ARTIFACTS, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
+
+ // logger.debug("Send GET request to get all property scopes: {}", url);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ public static RestResponse getConfigurationTowardsCatalogBe() throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_CONFIGURATION, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), "cs0008");
+
+ // logger.debug("Send GET request to get all property scopes: {}", url);
+ return http.httpSendGet(url, headersMap);
+
+ }
+
+ public static RestResponse sendOptionsTowardsCatalogFeWithUuid() throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_ALL_CATEGORIES_FE, config.getCatalogFeHost(), config.getCatalogFePort(), BaseRestUtils.RESOURCE_COMPONENT_TYPE);
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderData);
+ HttpRequest http = new HttpRequest();
+
+ logger.debug("Send OPTIONS request for categories: {}", url);
+ return http.httpSendByMethod(url, "OPTIONS", null, headersMap);
+ }
+
+ // ********** UPDATE *************
+ public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, String uniqueId, String encoding) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
+
+ String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(updatedResourceDetails);
+ String userId = sdncModifierDetails.getUserId();
+
+ RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
+
+ updatedResourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
+ updatedResourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
+
+ return updateResourceResponse;
+ }
+
+ public static RestResponse updateResourceTEST(Resource resource, User sdncModifierDetails, String uniqueId, String encoding) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), uniqueId);
+
+ String ContentTypeString = String.format("%s;%s", contentTypeHeaderData, encoding);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resource);
+ String userId = sdncModifierDetails.getUserId();
+
+ RestResponse updateResourceResponse = sendPut(url, userBodyJson, userId, ContentTypeString);
+ return updateResourceResponse;
+ }
+
+ public static RestResponse updateResourceMetadata(ResourceReqDetails updatedResourceDetails, User sdncModifierDetails, String uniqueId) throws Exception {
+ return updateResourceMetadata(updatedResourceDetails, sdncModifierDetails, uniqueId, "");
+ }
+
+ public static RestResponse updateResourceMetadata(String json, User sdncModifierDetails, String resourceId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+ String userId = sdncModifierDetails.getUserId();
+ RestResponse updateResourceResponse = sendPut(url, json, userId, contentTypeHeaderData);
+ return updateResourceResponse;
+ }
+
+ public static RestResponse updateResource(ResourceReqDetails resourceDetails, User sdncModifierDetails, String resourceId) throws IOException {
+ String userId = sdncModifierDetails.getUserId();
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_RESOURCE, config.getCatalogBeHost(), config.getCatalogBePort(), resourceId);
+
+ Map<String, String> headersMap = prepareHeadersMap(userId);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(resourceDetails);
+ String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson);
+ headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5);
+ HttpRequest http = new HttpRequest();
+ RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap);
+ if (updateResourceResponse.getErrorCode() == STATUS_CODE_UPDATE_SUCCESS) {
+ resourceDetails.setUUID(ResponseParser.getUuidFromResponse(updateResourceResponse));
+ resourceDetails.setVersion(ResponseParser.getVersionFromResponse(updateResourceResponse));
+ resourceDetails.setUniqueId(ResponseParser.getUniqueIdFromResponse(updateResourceResponse));
+ String lastUpdaterUserId = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterUserId");
+ resourceDetails.setLastUpdaterUserId(lastUpdaterUserId);
+ String lastUpdaterFullName = ResponseParser.getValueFromJsonResponse(updateResourceResponse.getResponse(), "lastUpdaterFullName");
+ resourceDetails.setLastUpdaterFullName(lastUpdaterFullName);
+ resourceDetails.setCreatorUserId(userId);
+ resourceDetails.setCreatorFullName(sdncModifierDetails.getFullName());
+ }
+ return updateResourceResponse;
+ }
+
+ public static RestResponse createResourceInstance(ResourceReqDetails resourceDetails, User modifier, String vfResourceUniqueId) throws Exception {
+ ComponentInstanceReqDetails resourceInstanceReqDetails = ElementFactory.getComponentResourceInstance(resourceDetails);
+ RestResponse createResourceInstanceResponse = ComponentInstanceRestUtils.createComponentInstance(resourceInstanceReqDetails, modifier, vfResourceUniqueId, ComponentTypeEnum.RESOURCE);
+ ResourceRestUtils.checkCreateResponse(createResourceInstanceResponse);
+ return createResourceInstanceResponse;
+ }
+
+ public static RestResponse associateResourceInstances(JSONObject body, User sdncModifierDetails, Component component) throws IOException {
+
+ Config config = Utils.getConfig();
+ Gson gson = new Gson();
+ String bodyJson = gson.toJson(body);
+ component.getComponentType();
+ String componentType = ComponentTypeEnum.findParamByType(component.getComponentType());
+ String url = String.format(Urls.ASSOCIATE__RESOURCE_INSTANCE, config.getCatalogBeHost(), config.getCatalogBePort(), componentType, component.getUniqueId());
+ return sendPost(url, bodyJson, sdncModifierDetails.getUserId(), null);
+
+ }
+
+ public static RestResponse getFollowedList(User sdncModifierDetails) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
+ return sendGet(url, sdncModifierDetails.getUserId());
+ }
+
+ public static List<Resource> restResponseToResourceObjectList(String restResponse) {
+ JsonElement jelement = new JsonParser().parse(restResponse);
+ JsonArray jsonArray = jelement.getAsJsonArray();
+ List<Resource> restResponseArray = new ArrayList<>();
+ Resource resource = null;
+ for (int i = 0; i < jsonArray.size(); i++) {
+ String resourceString = (String) jsonArray.get(i).toString();
+ resource = ResponseParser.convertResourceResponseToJavaObject(resourceString);
+ restResponseArray.add(resource);
+ }
+
+ return restResponseArray;
+
+ }
+
+ public static Resource getResourceObjectFromResourceListByUid(List<Resource> resourceList, String uid) {
+ if (resourceList != null && resourceList.size() > 0) {
+ for (Resource resource : resourceList) {
+ if (resource.getUniqueId().equals(uid))
+ return resource;
+ }
+ } else
+ return null;
+ return null;
+ }
+
+ // =======================================resource
+ // associate==================================================
+ public static RestResponse associate2ResourceInstances(Component container, ComponentInstance fromNode, ComponentInstance toNode, String assocType, User sdncUserDetails) throws IOException {
+ return associate2ResourceInstances(container, fromNode.getUniqueId(), toNode.getUniqueId(), assocType, sdncUserDetails);
+ }
+
+ public static RestResponse associate2ResourceInstances(Component component, String fromNode, String toNode, String assocType, User sdncUserDetails) throws IOException {
+
+ RelationshipInstData relationshipInstData = new RelationshipInstData();
+ Map<String, List<CapabilityDefinition>> capabilitiesMap = component.getCapabilities();
+ Map<String, List<RequirementDefinition>> requirementMap = component.getRequirements();
+ List<CapabilityDefinition> capabilitiesList = capabilitiesMap.get(assocType);
+ List<RequirementDefinition> requirementList = requirementMap.get(assocType);
+
+ RequirementDefinition requirementDefinitionFrom = getRequirementDefinitionByOwnerId(requirementList, fromNode);
+ CapabilityDefinition capabilityDefinitionTo = getCapabilityDefinitionByOwnerId(capabilitiesList, toNode);
+ relationshipInstData.setCapabilityOwnerId(capabilityDefinitionTo.getOwnerId());
+ relationshipInstData.setCapabiltyId(capabilityDefinitionTo.getUniqueId());
+ relationshipInstData.setRequirementOwnerId(requirementDefinitionFrom.getOwnerId());
+ relationshipInstData.setRequirementId(requirementDefinitionFrom.getUniqueId());
+
+ JSONObject assocBody = assocBuilder(relationshipInstData, capabilityDefinitionTo, requirementDefinitionFrom, toNode, fromNode);
+ return ResourceRestUtils.associateResourceInstances(assocBody, sdncUserDetails, component);
+
+ }
+
+ private static JSONObject assocBuilder(RelationshipInstData relationshipInstData, CapabilityDefinition capabilityDefinitionTo, RequirementDefinition requirementDefinitionFrom, String toNode, String fromNode) {
+
+ String type = capabilityDefinitionTo.getType();
+ String requirement = requirementDefinitionFrom.getName();
+ String capability = requirementDefinitionFrom.getName();
+
+ JSONObject wrapper = new JSONObject();
+ JSONArray relationshipsArray = new JSONArray();
+ JSONObject relationship = new JSONObject();
+ JSONObject simpleObject = new JSONObject();
+
+ relationship.put("type", type);
+ simpleObject.put("relationship", relationship);
+ simpleObject.put("requirement", requirement);
+ simpleObject.put("capability", capability);
+ simpleObject.put("capabilityUid", relationshipInstData.getCapabiltyId());
+ simpleObject.put("capabilityOwnerId", relationshipInstData.getCapabilityOwnerId());
+ simpleObject.put("requirementOwnerId", relationshipInstData.getRequirementOwnerId());
+ simpleObject.put("requirementUid", relationshipInstData.getRequirementId());
+ relationshipsArray.add(simpleObject);
+
+ ArrayList<Object> relationships = new ArrayList<Object>(relationshipsArray);
+ wrapper.put("fromNode", fromNode);
+ wrapper.put("toNode", toNode);
+ wrapper.put("relationships", relationships);
+ return wrapper;
+
+ }
+
+ private static CapabilityDefinition getCapabilityDefinitionByOwnerId(List<CapabilityDefinition> capabilityDefinitionList, String ownerId) {
+
+ for (CapabilityDefinition capabilityDefinition : capabilityDefinitionList) {
+ if (capabilityDefinition.getOwnerId().equals(ownerId)) {
+ return capabilityDefinition;
+ }
+ }
+ return null;
+ }
+
+ private static RequirementDefinition getRequirementDefinitionByOwnerId(List<RequirementDefinition> requirementDefinitionList, String ownerId) {
+
+ for (RequirementDefinition requirementDefinition : requirementDefinitionList) {
+ if (requirementDefinition.getOwnerId().equals(ownerId)) {
+ return requirementDefinition;
+ }
+ }
+ return null;
+ }
+
+ public static String getRiUniqueIdByRiName(Component component, String resourceInstanceName) {
+
+ List<ComponentInstance> componentInstances = component.getComponentInstances();
+ String name = null;
+ for (ComponentInstance componentInstance : componentInstances) {
+ if (componentInstance.getName().equals(resourceInstanceName)) {
+ name = componentInstance.getUniqueId();
+ break;
+ }
+ }
+ return name;
+ }
+
+ public static Resource convertResourceGetResponseToJavaObject(ResourceReqDetails resourceDetails) throws IOException {
+ RestResponse response = ResourceRestUtils.getResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertEquals("Check response code after get resource", 200, response.getErrorCode().intValue());
+ return ResponseParser.convertResourceResponseToJavaObject(response.getResponse());
+ }
+
+ public static RestResponse changeResourceInstanceVersion(String containerUniqueId, String instanceToReplaceUniqueId, String newResourceUniqueId, User sdncModifierDetails, ComponentTypeEnum componentType) throws IOException {
+ return ProductRestUtils.changeServiceInstanceVersion(containerUniqueId, instanceToReplaceUniqueId, newResourceUniqueId, sdncModifierDetails, componentType);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
new file mode 100644
index 0000000000..dfcb9c2736
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java
@@ -0,0 +1,541 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+import org.codehaus.jackson.Version;
+import org.codehaus.jackson.map.JsonDeserializer;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.module.SimpleModule;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.model.ComponentInstanceProperty;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.PropertyConstraint;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.operations.impl.PropertyOperation.PropertyConstraintJacksonDeserialiser;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public class ResponseParser {
+
+ private static final String INVARIANT_UUID = "invariantUUID";
+ public static final String UNIQUE_ID = "uniqueId";
+ public static final String VERSION = "version";
+ public static final String UUID = "uuid";
+ public static final String NAME = "name";
+ public static final String ORIGIN_TYPE = "originType";
+ public static final String TOSCA_RESOURCE_NAME = "toscaResourceName";
+
+ static Logger logger = Logger.getLogger(ResponseParser.class.getName());
+
+ 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;
+ }
+
+ }
+
+ public static String getUniqueIdFromResponse(RestResponse response) {
+ return getValueFromJsonResponse(response.getResponse(), UNIQUE_ID);
+ }
+
+ public static String getInvariantUuid(RestResponse response) {
+ return getValueFromJsonResponse(response.getResponse(), INVARIANT_UUID);
+ }
+
+ public static String getUuidFromResponse(RestResponse response) {
+ return getValueFromJsonResponse(response.getResponse(), UUID);
+ }
+
+ public static String getNameFromResponse(RestResponse response) {
+ return getValueFromJsonResponse(response.getResponse(), NAME);
+ }
+
+ public static String getVersionFromResponse(RestResponse response) {
+ return ResponseParser.getValueFromJsonResponse(response.getResponse(), VERSION);
+ }
+
+ public static String getComponentTypeFromResponse(RestResponse response) {
+ return ResponseParser.getValueFromJsonResponse(response.getResponse(), ORIGIN_TYPE);
+ }
+
+ public static String getToscaResourceNameFromResponse(RestResponse response) {
+ return getValueFromJsonResponse(response.getResponse(), TOSCA_RESOURCE_NAME);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static ResourceRespJavaObject parseJsonListReturnResourceDetailsObj(RestResponse restResponse,
+ String resourceType, String searchPattern, String expectedResult) throws Exception {
+
+ // Gson gson = new Gson;
+
+ JsonElement jElement = new JsonParser().parse(restResponse.getResponse());
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonArray arrayOfObjects = (JsonArray) jObject.get(resourceType);
+ Gson gson = new Gson();
+ Map<String, Object> map = new HashMap<String, Object>();
+ ResourceRespJavaObject jsonToJavaObject = new ResourceRespJavaObject();
+
+ for (int counter = 0; counter < arrayOfObjects.size(); counter++) {
+ JsonObject jHitObject = (JsonObject) arrayOfObjects.get(counter);
+
+ map = (Map<String, Object>) gson.fromJson(jHitObject.toString(), map.getClass());
+ if (map.get(searchPattern).toString().contains(expectedResult)) {
+
+ jsonToJavaObject = gson.fromJson(jObject, ResourceRespJavaObject.class);
+ break;
+ }
+ }
+ return jsonToJavaObject;
+
+ }
+
+ public static Resource convertResourceResponseToJavaObject(String response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ final SimpleModule module = new SimpleModule("customerSerializationModule",
+ new Version(1, 0, 0, "static version"));
+ JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
+ addDeserializer(module, PropertyConstraint.class, desrializer);
+
+ mapper.registerModule(module);
+ Resource resource = null;
+ try {
+ resource = mapper.readValue(response, Resource.class);
+ logger.debug(resource.toString());
+ } catch (IOException e) {
+ try {
+ List<Resource> resources = Arrays.asList(mapper.readValue(response.toString(), Resource[].class));
+ resource = resources.get(0);
+ } catch (Exception e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ }
+
+ return resource;
+ }
+
+ public static ComponentInstanceProperty convertPropertyResponseToJavaObject(String response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ final SimpleModule module = new SimpleModule("customerSerializationModule",
+ new Version(1, 0, 0, "static version"));
+ JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
+ addDeserializer(module, PropertyConstraint.class, desrializer);
+
+ mapper.registerModule(module);
+ ComponentInstanceProperty propertyDefinition = null;
+ try {
+ propertyDefinition = mapper.readValue(response, ComponentInstanceProperty.class);
+ logger.debug(propertyDefinition.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return propertyDefinition;
+ }
+
+ // public static ResourceInstanceReqDetails
+ // convertResourceInstanceResponseToJavaObject(String response) {
+ //
+ // ObjectMapper mapper = new ObjectMapper();
+ // final SimpleModule module = new
+ // SimpleModule("customerSerializationModule", new Version(1, 0, 0, "static
+ // version"));
+ // JsonDeserializer<PropertyConstraint> desrializer = new
+ // PropertyConstraintJacksonDeserialiser();
+ // addDeserializer(module, PropertyConstraint.class, desrializer);
+ //
+ // mapper.registerModule(module);
+ // ResourceInstanceReqDetails resourceInstanceReqDetails = null;
+ // try {
+ // resourceInstanceReqDetails = mapper.readValue(response,
+ // ResourceInstanceReqDetails.class);
+ // logger.debug(resourceInstanceReqDetails.toString());
+ // } catch (IOException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ //
+ // return resourceInstanceReqDetails;
+ // }
+ public static String toJson(Object object) {
+ Gson gson = new Gson();
+ return gson.toJson(object);
+ }
+
+ public static ArtifactDefinition convertArtifactDefinitionResponseToJavaObject(String response) {
+ ObjectMapper mapper = new ObjectMapper();
+ ArtifactDefinition artifactDefinition = null;
+ try {
+
+ artifactDefinition = mapper.readValue(response, ArtifactDefinition.class);
+ logger.debug(artifactDefinition.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return artifactDefinition;
+
+ }
+
+ public static ArtifactReqDetails convertArtifactReqDetailsToJavaObject(String response) {
+
+ ArtifactReqDetails artifactReqDetails = null;
+ // try {
+ //
+ // artifactDefinition = mapper.readValue(response,
+ // ArtifactReqDetails.class);
+ // logger.debug(artifactDefinition.toString());
+ // } catch (IOException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ //
+ // return artifactDefinition;
+ Gson gson = new Gson();
+ artifactReqDetails = gson.fromJson(response, ArtifactReqDetails.class);
+ return artifactReqDetails;
+ }
+
+ public static <T> T parseToObject(String json, Class<T> clazz) {
+ Gson gson = new Gson();
+ T object;
+ try {
+ object = gson.fromJson(json, clazz);
+ } catch (Exception e) {
+ object = parseToObjectUsingMapper(json, clazz);
+ }
+ return object;
+ }
+
+ public static <T> T parseToObjectUsingMapper(String json, Class<T> clazz) {
+ // Generic convert
+ ObjectMapper mapper = new ObjectMapper();
+ T object = null;
+ final SimpleModule module = new SimpleModule("customerSerializationModule",
+ new Version(1, 0, 0, "static version"));
+ JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
+ addDeserializer(module, PropertyConstraint.class, desrializer);
+ mapper.registerModule(module);
+ try {
+ object = mapper.readValue(json, clazz);
+ // System.out.println("Class: "+clazz.getSimpleName()+", json:
+ // "+json);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return object;
+ }
+
+ public static ArtifactReqDetails convertArtifactDefinitionToArtifactReqDetailsObject(
+ ArtifactDefinition artifactDefinition) {
+
+ ArtifactReqDetails artifactReqDetails = null;
+ // try {
+ //
+ // artifactDefinition = mapper.readValue(response,
+ // ArtifactReqDetails.class);
+ // logger.debug(artifactDefinition.toString());
+ // } catch (IOException e) {
+ // // TODO Auto-generated catch block
+ // e.printStackTrace();
+ // }
+ //
+ // return artifactDefinition;
+ Gson gson = new Gson();
+ String artDef = gson.toJson(artifactDefinition);
+ artifactReqDetails = gson.fromJson(artDef, ArtifactReqDetails.class);
+ return artifactReqDetails;
+ }
+
+ public static <T> void addDeserializer(SimpleModule module, Class<T> clazz,
+ final JsonDeserializer<T> deserializer) {
+ module.addDeserializer(clazz, deserializer);
+ }
+
+ public static Service convertServiceResponseToJavaObject(String response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ final SimpleModule module = new SimpleModule("customerSerializationModule",
+ new Version(1, 0, 0, "static version"));
+ JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
+ addDeserializer(module, PropertyConstraint.class, desrializer);
+
+ mapper.registerModule(module);
+ Service service = null;
+ try {
+ service = mapper.readValue(response, Service.class);
+ logger.debug(service.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return service;
+ }
+
+ public static Product convertProductResponseToJavaObject(String response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ Product product = null;
+ try {
+ product = mapper.readValue(response, Product.class);
+ logger.debug(product.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return product;
+ }
+
+ public static ComponentInstance convertComponentInstanceResponseToJavaObject(String response) {
+
+ ObjectMapper mapper = new ObjectMapper();
+ final SimpleModule module = new SimpleModule("customerSerializationModule",
+ new Version(1, 0, 0, "static version"));
+ JsonDeserializer<PropertyConstraint> desrializer = new PropertyConstraintJacksonDeserialiser();
+ addDeserializer(module, PropertyConstraint.class, desrializer);
+
+ mapper.registerModule(module);
+ ComponentInstance componentInstance = null;
+ try {
+ componentInstance = mapper.readValue(response, ComponentInstance.class);
+ logger.debug(componentInstance.toString());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ return componentInstance;
+ }
+
+ public static List<String> getValuesFromJsonArray(RestResponse message) throws Exception {
+ List<String> artifactTypesArrayFromApi = new ArrayList<String>();
+
+ org.json.JSONObject responseObject = new org.json.JSONObject(message.getResponse());
+ JSONArray jArr = responseObject.getJSONArray("artifactTypes");
+
+ for (int i = 0; i < jArr.length(); i++) {
+ org.json.JSONObject jObj = jArr.getJSONObject(i);
+ String value = jObj.get("name").toString();
+
+ artifactTypesArrayFromApi.add(value);
+ }
+ return artifactTypesArrayFromApi;
+ }
+
+ public static String calculateMD5Header(ArtifactReqDetails artifactDetails) {
+ Gson gson = new Gson();
+ String jsonBody = gson.toJson(artifactDetails);
+ // calculate MD5 for json body
+ return calculateMD5(jsonBody);
+
+ }
+
+ public static String calculateMD5(String data) {
+ String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
+ // encode base-64 result
+ byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
+ String encodeBase64Str = new String(encodeBase64);
+ return encodeBase64Str;
+
+ }
+
+ public static List<Map<String, Object>> getAuditFromMessage(Map auditingMessage) {
+ List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
+ // JsonElement jElement = new JsonParser().parse(auditingMessage);
+ // JsonObject jObject = jElement.getAsJsonObject();
+ // JsonObject hitsObject = (JsonObject) jObject.get("hits");
+ // JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
+ //
+ // Iterator<JsonElement> hitsIterator = hitsArray.iterator();
+ // while(hitsIterator.hasNext())
+ // {
+ // JsonElement nextHit = hitsIterator.next();
+ // JsonObject jHitObject = nextHit.getAsJsonObject();
+ // JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
+ //
+ // Gson gson=new Gson();
+ // String auditUnparsed = jSourceObject.toString();
+ //
+ // Map<String,Object> map = new HashMap<String,Object>();
+ // map = (Map<String,Object>) gson.fromJson(auditUnparsed,
+ // map.getClass());
+
+ auditList.add(auditingMessage);
+ // }
+ return auditList;
+ }
+
+ public static List<CategoryDefinition> parseCategories(RestResponse getAllCategoriesRest) {
+
+ List<CategoryDefinition> categories = new ArrayList<>();
+ try {
+ JsonElement jElement = new JsonParser().parse(getAllCategoriesRest.getResponse());
+ JsonArray cagegories = jElement.getAsJsonArray();
+ Iterator<JsonElement> iter = cagegories.iterator();
+ while (iter.hasNext()) {
+ JsonElement next = iter.next();
+ CategoryDefinition category = ResponseParser.parseToObject(next.toString(), CategoryDefinition.class);
+ categories.add(category);
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return categories;
+ }
+
+ public static JSONArray getListFromJson(RestResponse res, String field) throws JSONException {
+ String valueFromJsonResponse = getValueFromJsonResponse(res.getResponse(), field);
+ JSONArray jArr = new JSONArray(valueFromJsonResponse);
+
+ return jArr;
+ }
+
+ public static List<String> getDerivedListFromJson(RestResponse res) throws JSONException {
+ JSONArray listFromJson = getListFromJson(res, "derivedList");
+ List<String> lst = new ArrayList<String>();
+ for (int i = 0; i < listFromJson.length(); i++) {
+ lst.add(listFromJson.getString(i));
+ }
+
+ return lst;
+ }
+
+ public static Map<String, Object> convertStringToMap(String obj) {
+ Map<String, Object> object = (Map<String, Object>) JSONValue.parse(obj);
+ return object;
+ }
+
+ public static List<Map<String, Object>> getListOfMapsFromJson(RestResponse res, String field) throws Exception {
+ List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
+ JSONArray listFromJson = getListFromJson(res, field);
+ for (int i = 0; i < listFromJson.length(); i++) {
+ Map<String, Object> convertStringToMap = convertStringToMap(listFromJson.getString(i));
+ list.add(convertStringToMap);
+ }
+ return list;
+
+ }
+
+ public static Map<String, Object> getJsonValueAsMap(RestResponse response, String key) {
+ String valueField = getValueFromJsonResponse(response.getResponse(), key);
+ Map<String, Object> convertToMap = convertStringToMap(valueField);
+ return convertToMap;
+ }
+
+ public static String getJsonObjectValueByKey(String metadata, String key) {
+ JsonElement jelement = new JsonParser().parse(metadata);
+
+ JsonObject jobject = jelement.getAsJsonObject();
+ Object obj = jobject.get(key);
+ if (obj == null) {
+ return null;
+ } else {
+ return obj.toString();
+ }
+ }
+
+ public static Map<String, ArrayList<Component>> convertCatalogResponseToJavaObject(String response) {
+
+ Map<String, ArrayList<Component>> map = new HashMap<String, ArrayList<Component>>();
+
+ JsonElement jElement = new JsonParser().parse(response);
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonArray jArrReousrces = jObject.getAsJsonArray("resources");
+ JsonArray jArrServices = jObject.getAsJsonArray("services");
+ JsonArray jArrProducts = jObject.getAsJsonArray("products");
+
+ //////// RESOURCE/////////////////////////////
+ ArrayList<Component> restResponseArray = new ArrayList<>();
+ Component component = null;
+ for (int i = 0; i < jArrReousrces.size(); i++) {
+ String resourceString = (String) jArrReousrces.get(i).toString();
+ component = ResponseParser.convertResourceResponseToJavaObject(resourceString);
+ restResponseArray.add(component);
+ }
+
+ map.put("resources", restResponseArray);
+
+ ///////// SERVICE/////////////////////////////
+
+ restResponseArray = new ArrayList<>();
+ component = null;
+ for (int i = 0; i < jArrServices.size(); i++) {
+ String resourceString = (String) jArrServices.get(i).toString();
+ component = ResponseParser.convertServiceResponseToJavaObject(resourceString);
+ restResponseArray.add(component);
+ }
+
+ map.put("services", restResponseArray);
+
+ ///////// PRODUCT/////////////////////////////
+ restResponseArray = new ArrayList<>();
+ component = null;
+ for (int i = 0; i < jArrProducts.size(); i++) {
+ String resourceString = (String) jArrProducts.get(i).toString();
+ component = ResponseParser.convertProductResponseToJavaObject(resourceString);
+ restResponseArray.add(component);
+ }
+
+ map.put("products", restResponseArray);
+
+ return map;
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
new file mode 100644
index 0000000000..d62c74c3d2
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ServiceRestUtils.java
@@ -0,0 +1,262 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+public class ServiceRestUtils extends BaseRestUtils {
+ private static Logger logger = LoggerFactory.getLogger(ServiceRestUtils.class.getName());
+ private final static String cacheControl = "no-cache";
+ private final static String contentTypeHeaderData = "application/json";
+ private final static String acceptHeaderDate = "application/json";
+ // ****** CREATE *******
+
+ private static Gson gson = new Gson();
+
+ public static RestResponse deleteService(String serviceName, String version, User sdncModifierDetails) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(), config.getCatalogBePort(), serviceName, version);
+ String userId = sdncModifierDetails.getUserId();
+ RestResponse sendDelete = sendDelete(url, userId);
+ deleteMarkedServices(userId);
+ return sendDelete;
+ }
+
+ public static RestResponse deleteServiceById(String serviceId, String userId) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.DELETE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
+ RestResponse sendDelete = sendDelete(url, userId);
+ deleteMarkedServices(userId);
+ return sendDelete;
+ }
+
+ public static void deleteMarkedServices(String userId) throws IOException {
+ String url;
+ Config config = Utils.getConfig();
+ url = String.format(Urls.DELETE_MARKED_SERVICES, config.getCatalogBeHost(), config.getCatalogBePort());
+ sendDelete(url, userId);
+ }
+
+ public static RestResponse createService(ServiceReqDetails service, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.CREATE_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort());
+ String serviceBodyJson = gson.toJson(service);
+
+ logger.debug("Send POST request to create service: {]", url);
+ logger.debug("Service body: {}", serviceBodyJson);
+
+ RestResponse res = sendPost(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
+ if (res.getErrorCode() == STATUS_CODE_CREATED) {
+ service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ service.setVersion(ResponseParser.getVersionFromResponse(res));
+ service.setUUID(ResponseParser.getUuidFromResponse(res));
+ // Creator details never change after component is created - Ella,
+ // 12/1/2016
+ service.setCreatorUserId(user.getUserId());
+ service.setCreatorFullName(user.getFullName());
+ }
+
+ return res;
+ }
+
+ public static RestResponse updateService(ServiceReqDetails service, User user) throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.UPDATE_SERVICE_METADATA, config.getCatalogBeHost(), config.getCatalogBePort(),
+ service.getUniqueId());
+ String serviceBodyJson = gson.toJson(service);
+
+ logger.debug("Send PUT request to create service: {}", url);
+ logger.debug("Service body: {}", serviceBodyJson);
+
+ RestResponse res = sendPut(url, serviceBodyJson, user.getUserId(), acceptHeaderData);
+ if (res.getErrorCode() == STATUS_CODE_CREATED) {
+ service.setUniqueId(ResponseParser.getUniqueIdFromResponse(res));
+ service.setVersion(ResponseParser.getVersionFromResponse(res));
+ }
+
+ return res;
+ }
+
+ public static RestResponse getService(ServiceReqDetails serviceReqDetails, User sdncModifierDetails)
+ throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ serviceReqDetails.getUniqueId());
+ return getServiceFromUrl(url, sdncModifierDetails, false);
+ }
+
+ public static RestResponse getService(String serviceId, User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SERVICE, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
+ return getServiceFromUrl(url, sdncModifierDetails, false);
+ }
+
+ public static RestResponse getServiceByNameAndVersion(User sdncModifierDetails, String serviceName,
+ String serviceVersion) throws IOException {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), serviceName, serviceVersion);
+ return getServiceFromUrl(url, sdncModifierDetails, false);
+ }
+
+ public static RestResponse getServiceFromUrl(String url, User sdncModifierDetails, boolean isCached)
+ throws IOException {
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, isCached);
+ HttpRequest http = new HttpRequest();
+ logger.debug("Send GET request to create service: {}", url);
+ logger.debug("Service headers: {}", headersMap);
+ RestResponse sendGetServerRequest = http.httpSendGet(url, headersMap);
+
+ return sendGetServerRequest;
+ }
+
+ public static Map<String, String> prepareHeadersMap(User sdncModifierDetails, boolean isCached) {
+ Map<String, String> headersMap = new HashMap<String, String>();
+ if (isCached)
+ headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), cacheControl);
+
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ return headersMap;
+ }
+
+ public static RestResponse approveServiceDistribution(String serviceId, String userId) throws Exception {
+ return changeServiceDistributionState(serviceId, userId, Urls.APPROVE_DISTRIBUTION);
+ }
+
+ public static RestResponse rejectServiceDistribution(String serviceId, String userId) throws Exception {
+ return changeServiceDistributionState(serviceId, userId, Urls.REJECT_DISTRIBUTION);
+ }
+
+ // Benny
+ public static RestResponse rejectServiceDistribution(String serviceId, String userId, String comment)
+ throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.REJECT_DISTRIBUTION, config.getCatalogBeHost(), config.getCatalogBePort(),
+ serviceId);
+ String userBodyJson = gson.toJson(comment);
+ return sendPost(url, userBodyJson, userId, acceptHeaderData);
+
+ }
+
+ private static RestResponse changeServiceDistributionState(String serviceId, String userId, String distributionUrl)
+ throws Exception {
+ Config config = Utils.getConfig();
+ String url = String.format(distributionUrl, config.getCatalogBeHost(), config.getCatalogBePort(), serviceId);
+ String defComment = "{ userRemarks : \"this is an test\" }";
+ String userBodyJson = gson.toJson(defComment);
+ return sendPost(url, userBodyJson, userId, acceptHeaderData);
+
+ }
+
+ public static RestResponse getServiceLatestVersionList(User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+ String url = String.format(Urls.GET_SERVICE_lATEST_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort());
+
+ return sendGet(url, sdncModifierDetails.getUserId());
+
+ }
+
+ public static RestResponse createServiceByHttpMethod(ServiceReqDetails serviceDetails, User sdncModifierDetails,
+ String method, String urls) throws IOException {
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true);
+
+ Config config = Utils.getConfig();
+ String serviceBodyJson = gson.toJson(serviceDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(urls, config.getCatalogBeHost(), config.getCatalogBePort());
+ // TODO: ADD AUTHENTICATION IN REQUEST
+ logger.debug(url);
+ logger.debug("Send {} request to create user: {}", method, url);
+ logger.debug("User body: {}", serviceBodyJson);
+ logger.debug("User headers: {}", headersMap);
+ RestResponse sendCreateUserRequest = http.httpSendByMethod(url, method, serviceBodyJson, headersMap);
+
+ return sendCreateUserRequest;
+
+ }
+
+ public static RestResponse deleteServiceByNameAndVersion(User sdncModifierDetails, String serviceName,
+ String serviceVersion) throws IOException {
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = prepareHeadersMap(sdncModifierDetails, true);
+
+ HttpRequest http = new HttpRequest();
+
+ String url = String.format(Urls.DELETE_SERVICE_BY_NAME_AND_VERSION, config.getCatalogBeHost(),
+ config.getCatalogBePort(), serviceName, serviceVersion);
+ RestResponse deleteResponse = http.httpSendDelete(url, headersMap);
+
+ return deleteResponse;
+ }
+
+ public static RestResponse getFollowed(User user) throws Exception {
+ Config config = Utils.getConfig();
+
+ HttpRequest httpRequest = new HttpRequest();
+
+ String url = String.format(Urls.GET_FOLLWED_LIST, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), user.getUserId());
+
+ RestResponse getResourceNotAbstarctResponse = httpRequest.httpSendGet(url, headersMap);
+
+ return getResourceNotAbstarctResponse;
+ }
+
+ public static JSONArray getListArrayFromRestResponse(RestResponse restResponse) {
+ String json = restResponse.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray servicesArray = (JSONArray) jsonResp.get("services");
+
+ logger.debug("services = {}", servicesArray);
+
+ return servicesArray;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
new file mode 100644
index 0000000000..a8f39b9ad8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/UserRestUtils.java
@@ -0,0 +1,282 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.rest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.run.StartTest;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.gson.Gson;
+
+public class UserRestUtils extends BaseRestUtils {
+
+ static Gson gson = new Gson();
+
+ static Logger logger = LoggerFactory.getLogger(UserRestUtils.class.getName());
+ static String contentTypeHeaderData = "application/json";
+ static String acceptHeaderDate = "application/json";
+
+ public UserRestUtils() {
+ super();
+
+ StartTest.enableLogger();
+ }
+
+ public static RestResponse createUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ String userBodyJson = gson.toJson(sdncUserDetails);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.CREATE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
+
+ logger.debug("Send POST request to create user: {}", url);
+ logger.debug("User body: {}", userBodyJson);
+ logger.debug("User headers: {}", headersMap);
+ RestResponse sendCreateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return sendCreateUserRequest;
+
+ }
+
+ public static RestResponse deactivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
+ return deleteUser(sdncUserDetails, sdncModifierDetails, true);
+ }
+
+ public static RestResponse deActivateUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
+ return deleteUser(sdncUserDetails, sdncModifierDetails, false);
+ }
+
+ public static RestResponse deleteUser(User sdncUserDetails, User sdncModifierDetails, boolean isForceDelete)
+ throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ if (isForceDelete) {
+ headersMap.put(User.FORCE_DELETE_HEADER_FLAG, User.FORCE_DELETE_HEADER_FLAG);
+ }
+
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.DELETE_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ sdncUserDetails.getUserId());
+ RestResponse sendDeleteUserRequest = http.httpSendDelete(url, headersMap);
+ return sendDeleteUserRequest;
+
+ }
+
+ public static RestResponse updateUser(User sdncUserDetails, User sdncModifierDetails)
+ throws IOException, CloneNotSupportedException {
+
+ Config config = Utils.getConfig();
+ User user = new User(sdncModifierDetails);
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ user.setUserId(StringUtils.EMPTY);
+ user.setRole(StringUtils.EMPTY);
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(user);
+ logger.debug("userBodyJson: {}", userBodyJson);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ sdncModifierDetails.getUserId());
+ RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return sendUpdateUserRequest;
+ }
+
+ /// Benny
+ public static RestResponse updateUserRole(User sdncUserDetails, User sdncModifierDetails, String userIdToUpdate)
+ throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ Gson gson = new Gson();
+ String userBodyJson = gson.toJson(sdncUserDetails);
+ logger.debug("userBodyJson: {}", userBodyJson);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.UPDATE_USER_ROLE, config.getCatalogBeHost(), config.getCatalogBePort(),
+ userIdToUpdate);
+ RestResponse sendUpdateUserRequest = http.httpSendPost(url, userBodyJson, headersMap);
+
+ return sendUpdateUserRequest;
+
+ }
+
+ public static RestResponse getUser(User sdncUserDetails, User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_USER, config.getCatalogBeHost(), config.getCatalogBePort(),
+ sdncUserDetails.getUserId());
+ RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
+ return sendGetUserRequest;
+
+ }
+
+ public static RestResponse getAllAdminUsers(User sdncModifierDetails) throws IOException {
+
+ Config config = Utils.getConfig();
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ // Gson gson = new Gson();
+ // String userBodyJson = gson.toJson(sdncModifierDetails);
+ // System.out.println(userBodyJson);
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_ALL_ADMIN_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
+ logger.debug("Send following url: {} and headers: {}", url, headersMap.toString());
+ RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
+
+ return sendGetUserRequest;
+
+ }
+
+ // US571255
+ public static RestResponse getUsersByRoles(User sdncModifierDetails, String roles) throws IOException {
+
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+
+ HttpRequest http = new HttpRequest();
+ String url;
+ if (roles == "/") {
+ url = String.format(Urls.GET_ALL_USERS, config.getCatalogBeHost(), config.getCatalogBePort());
+ } else {
+ url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(), roles);
+
+ }
+ logger.debug("Send following url: {} and headers: {}", url, headersMap.toString());
+ RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
+ return sendGetUserRequest;
+ }
+
+ public static RestResponse getUsersByRolesHttpCspAtuUidIsMissing(User sdncModifierDetails, String roles)
+ throws Exception {
+
+ Config config = Utils.getConfig();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), contentTypeHeaderData);
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate);
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncModifierDetails.getUserId());
+ headersMap.remove("USER_ID");
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.GET_USERS_BY_ROLES, config.getCatalogBeHost(), config.getCatalogBePort(),
+ roles);
+ logger.debug(
+ "Send following url without USER_ID header : " + url + " headers: " + headersMap.toString());
+
+ RestResponse sendGetUserRequest = http.httpSendGet(url, headersMap);
+ return sendGetUserRequest;
+ }
+
+ public static RestResponse authorizedUserTowardsCatalogBe(User sdncUserDetails) throws IOException {
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ if (sdncUserDetails.getFirstName() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName());
+ }
+ if (sdncUserDetails.getLastName() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName());
+ }
+ if (sdncUserDetails.getEmail() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
+ }
+
+ logger.debug("headersMap: {}", headersMap.toString());
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
+ logger.debug("Send GET request to login as seal user : {}", url);
+ return http.httpSendGet(url, headersMap);
+ }
+
+ public static RestResponse authorizedUserTowardsCatalogBeQA(User sdncUserDetails) throws IOException {
+
+ Map<String, String> headersMap = new HashMap<String, String>();
+ headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json");
+ headersMap.put(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ if (sdncUserDetails.getFirstName() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_FIRSTNAME.getValue(), sdncUserDetails.getFirstName());
+ }
+ if (sdncUserDetails.getLastName() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_LASTNAME.getValue(), sdncUserDetails.getLastName());
+ }
+ if (sdncUserDetails.getEmail() != null) {
+ headersMap.put(HttpHeaderEnum.HTTP_CSP_EMAIL.getValue(), sdncUserDetails.getEmail());
+ }
+
+ logger.debug("headersMap: {}", headersMap.toString());
+
+ Config config = Utils.getConfig();
+ HttpRequest http = new HttpRequest();
+ String url = String.format(Urls.AUTHORIZE_USER, config.getCatalogBeHost(), config.getCatalogBePort());
+ logger.debug("Send GET request to login as seal user : {}", url);
+ return http.httpSendGet(url, headersMap);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
new file mode 100644
index 0000000000..21b520c97a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ArtifactValidationUtils.java
@@ -0,0 +1,228 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jackson.JsonParseException;
+import org.codehaus.jackson.JsonProcessingException;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.Component;
+import org.openecomp.sdc.be.model.ComponentInstance;
+import org.openecomp.sdc.be.resources.data.ESArtifactData;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Decoder;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.FileUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
+
+public class ArtifactValidationUtils {
+
+ private static String desc = "description";
+ private static String artifactType = "artifactType";
+ private static String artifactName = "artifactName";
+ private static String artifactChecksum = "artifactChecksum";
+ private static String uniqueId = "uniqueId";
+ protected Utils utils;
+
+ public static void validateInformationalArtifact(ArtifactReqDetails expectedArtifact,
+ Map<String, Object> actualArtifact) {
+ assertTrue("description is not as expected",
+ expectedArtifact.getDescription().equals(actualArtifact.get(desc).toString()));
+ assertTrue("artifactType is not as expected",
+ expectedArtifact.getArtifactType().toUpperCase().equals(actualArtifact.get(artifactType).toString()));
+ assertTrue("artifactName is not as expected",
+ expectedArtifact.getArtifactName().equals(actualArtifact.get(artifactName).toString()));
+ assertTrue("uniqueId is not as expected",
+ expectedArtifact.getUniqueId().equals(actualArtifact.get(uniqueId).toString()));
+ assertTrue("description is not as expected", expectedArtifact.getArtifactLabel().toLowerCase()
+ .equals(actualArtifact.get("artifactLabel").toString()));
+ }
+
+ public static void validateArtifactsNumberInComponent(Component component, ArtifactGroupTypeEnum artifactGroupType,
+ ArtifactTypeEnum artifactType, int expectedNumber) {
+ Map<String, ArtifactDefinition> deploymentArtifacts;
+ int counter = 0;
+ if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ deploymentArtifacts = component.getDeploymentArtifacts();
+ } else {
+ deploymentArtifacts = component.getArtifacts();
+ }
+ if (deploymentArtifacts != null) {
+ for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) {
+ if (artifactDefinition.getArtifactType().equals(artifactType.getType())) {
+ counter++;
+ }
+ }
+ }
+ assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber,
+ counter);
+ }
+
+ // Benny
+ public static void validateArtifactsNumberInComponentInstance(ComponentInstance componentInstance,
+ ArtifactGroupTypeEnum artifactGroupType, ArtifactTypeEnum artifactType, int expectedNumber) {
+ Map<String, ArtifactDefinition> deploymentArtifacts = null;
+ int counter = 0;
+ if (artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
+ deploymentArtifacts = componentInstance.getDeploymentArtifacts();
+ }
+ if (deploymentArtifacts != null) {
+ for (ArtifactDefinition artifactDefinition : deploymentArtifacts.values()) {
+ if (artifactDefinition.getArtifactType().equals(artifactType.getType())) {
+ counter++;
+ }
+ }
+ }
+ assertEquals("Unexpected number of " + artifactGroupType.getType() + " artifacts in component", expectedNumber,
+ counter);
+ }
+
+ public static ESArtifactData parseArtifactRespFromES(RestResponse resResponse)
+ throws JsonParseException, JsonProcessingException, Exception {
+ String bodyToParse = resResponse.getResponse();
+ JsonElement jElement = new JsonParser().parse(bodyToParse);
+ JsonElement jsourceElement = jElement.getAsJsonObject().get("_source");
+
+ ObjectMapper mapper = new ObjectMapper();
+ ESArtifactData esArtifactObject = mapper.readValue(jsourceElement.toString(), ESArtifactData.class);
+
+ // logger.debug("got artifact details from ElasticSearch as json");
+
+ return esArtifactObject;
+
+ }
+
+ public static void validateArtifactReqVsResp(ArtifactReqDetails expectedArtifactDetails,
+ ArtifactDefinition actualArtifactJavaObject) {
+ String expected;
+
+ expected = expectedArtifactDetails.getArtifactName();
+ if (expected == null)
+ expected = "";
+ assertEquals("artifact name is not correct ", expected, actualArtifactJavaObject.getArtifactName());
+
+ expected = expectedArtifactDetails.getArtifactType();
+ if (expected == null)
+ expected = "";
+ assertEquals("artifact type is not correct ", expected, actualArtifactJavaObject.getArtifactType());
+
+ expected = expectedArtifactDetails.getDescription();
+ if (expected == null)
+ expected = "";
+ assertEquals("artifact description is not correct ", expected, actualArtifactJavaObject.getDescription());
+
+ expected = expectedArtifactDetails.getArtifactLabel();
+ if (expected == null || expected == "") {
+ expected = expectedArtifactDetails.getArtifactName().toLowerCase().substring(0,
+ expectedArtifactDetails.getArtifactName().lastIndexOf("."));
+ // expected = tmp.substring(0,
+ // artifactInfo.getArtifactName().lastIndexOf("."));
+ }
+ assertEquals("artifact label is not correct ", expected, actualArtifactJavaObject.getArtifactLabel());
+
+ expected = expectedArtifactDetails.getUrl();
+ if (expected != "") {
+ assertEquals(expected, actualArtifactJavaObject.getApiUrl());
+ assertEquals(expectedArtifactDetails.getArtifactDisplayName(),
+ actualArtifactJavaObject.getArtifactDisplayName());
+ }
+
+ // assertEquals(validChecksum,
+ // actualArtifactJavaObject.getArtifactChecksum());
+
+ // expected = expectedArtifactDetails.getArtifactDisplayName();
+ // if (expected != "")
+ // {
+ // assertEquals(expected,
+ // actualArtifactJavaObject.getArtifactDisplayName());
+ // }
+
+ boolean actual = actualArtifactJavaObject.getMandatory();
+ assertEquals(expectedArtifactDetails.isMandatory(), actual);
+
+ if (actualArtifactJavaObject.getServiceApi()) {
+
+ boolean actual2 = actualArtifactJavaObject.getServiceApi();
+ assertEquals(expectedArtifactDetails.isServiceApi(), actual2);
+ }
+
+ }
+
+ public static void validateEsArtifactReqVsResp(ArtifactReqDetails expectedArtifactInfo,
+ ESArtifactData esArtifactData) throws Exception {
+ String expectedArtifactUid = expectedArtifactInfo.getUniqueId();
+ if (expectedArtifactUid == null)
+ expectedArtifactUid = "";
+ assertEquals("artifact name is not correct ", expectedArtifactUid, esArtifactData.getId());
+
+ String actualPayload = Decoder.encode(esArtifactData.getData().array());
+ assertEquals("artifact payloadData is not correct ", expectedArtifactInfo.getPayload(), actualPayload);
+ }
+
+ public static List<String> getListOfArtifactFromFolder(String folderName) throws IOException, Exception {
+ Config config = Utils.getConfig();
+ String sourceDir = config.getResourceConfigDir();
+ String testResourcesPath = sourceDir + File.separator + folderName;
+ List<String> listofFiles = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ return listofFiles;
+ }
+
+ public static ArtifactReqDetails replaceDefaultArtWithArtFromList_(ArtifactReqDetails heatArtifactDetails,
+ String heatExtension, String folderName, int positionInlist) throws IOException, Exception {
+
+ Config config = Utils.getConfig();
+ String ext = heatExtension;
+ String sourceDir = config.getResourceConfigDir();
+ String testResourcesPath = sourceDir + File.separator + folderName;
+ List<String> listFileName = FileUtils.getFileListFromBaseDirectoryByTestName(testResourcesPath);
+ // logger.debug("listFileName: {}", listFileName.get(positionInlist));
+ String payload = FileUtils.loadPayloadFile(listFileName, ext, true);
+ heatArtifactDetails.setPayload(payload);
+ heatArtifactDetails.setArtifactName(listFileName.get(positionInlist) + "." + ext);
+ return heatArtifactDetails;
+ }
+
+ public static ArtifactReqDetails replaceDefaultArtWithArtFromList(ArtifactReqDetails heatArtifactDetails,
+ String heatExtension, String folderName, int positionInlist) throws IOException, Exception {
+ List<String> listOfArtifactFromFolder = getListOfArtifactFromFolder(folderName);
+ // logger.debug("listFileName: {}", listOfArtifactFromFolder.get(positionInlist));
+ String payload = FileUtils.loadPayloadFileFromListUsingPosition(listOfArtifactFromFolder, heatExtension, true,
+ positionInlist);
+ heatArtifactDetails.setPayload(payload);
+ heatArtifactDetails.setArtifactName(heatArtifactDetails.getArtifactType()
+ + listOfArtifactFromFolder.get(positionInlist) + "." + heatExtension);
+ return heatArtifactDetails;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
new file mode 100644
index 0000000000..882498a63c
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/AuditValidationUtils.java
@@ -0,0 +1,1328 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.javatuples.Pair;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AuditEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.AuditJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ComponentType;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedAuthenticationAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedCategoryAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedDistDownloadAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedEcomConsumerAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedGetUserListAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedProductAudit;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedUserCRUDAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.run.StartTest;
+import org.openecomp.sdc.ci.tests.utils.ArtifactUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils.CategoryAuditJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.utils.rest.ConsumerRestUtils.EcompConsumerAuditJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.common.api.Constants;
+import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
+
+import com.datastax.driver.core.ColumnDefinitions;
+import com.datastax.driver.core.Row;
+
+public class AuditValidationUtils {
+ protected static Logger logger = Logger.getLogger(AuditValidationUtils.class.getName());
+ private static final String auditKeySpaceName = "sdcaudit";
+
+ public AuditValidationUtils() {
+ super();
+
+ StartTest.enableLogger();
+ logger = Logger.getLogger(AuditValidationUtils.class.getName());
+
+ }
+
+ public static String buildAuditDescription(ErrorInfo errorInfo, List<String> variables) {
+
+ String auditDesc = errorInfo.getMessageId() + ": " + errorInfo.getMessage();
+ for (int i = 0; i < variables.size(); i++) {
+ if (auditDesc.contains("%" + (i + 1))) {
+ auditDesc = auditDesc.replace("%" + (i + 1), variables.get(i));
+ }
+ }
+
+ // logger.debug("audit description - {}", auditDesc);
+ return auditDesc;
+ }
+
+ public static String getModifierString(String userName, String uid) {
+
+ if (userName.isEmpty() && uid.isEmpty())
+ return "(UNKNOWN)";
+
+ StringBuilder sb = new StringBuilder();
+ sb.append(userName).append("(").append(uid).append(")");
+ return sb.toString();
+
+ }
+
+ public static void validateAuditDownloadExternalAPI(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
+ String action, String body, boolean checkAllFields) throws Exception {
+ Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
+ // Andrey's comment
+ // actualAuditRecords = parseAuditResourceByAction(action, body);
+ actualAuditRecords = parseAuditResourceByAction(action, null);
+
+ // List<Map<String, Object>> actualAuditRecords = new
+ // ArrayList<Map<String, Object>>();
+ // actualAuditRecords = parseAuditResourceByActionToList(action, body);
+
+ validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+
+ validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getStatus());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDesc());
+
+ // validateField(actualAuditRecords,
+ // AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
+ // resourceAuditJavaObject.getCONSUMER_ID());
+ // validateField(actualAuditRecords,
+ // AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
+ // resourceAuditJavaObject.getRESOURCE_URL());
+
+ }
+
+ public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action,
+ String body, boolean checkAllFields) throws Exception {
+ Map<String, Object> actualAuditRecords = new HashMap<String, Object>();
+ // Andrey's comment
+ // actualAuditRecords = parseAuditResourceByAction(action, body);
+ actualAuditRecords = parseAuditResourceByAction(action, null);
+
+ if ((resourceAuditJavaObject.getModifierName() != null) && (resourceAuditJavaObject.getModifierUid() != null)) {
+ resourceAuditJavaObject.setModifierUid(getModifierString(resourceAuditJavaObject.getModifierName(),
+ resourceAuditJavaObject.getModifierUid()));
+ }
+
+ validateField(actualAuditRecords, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getPrevVersion());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+
+ validateField(actualAuditRecords, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getModifierUid());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getPrevState());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrState());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getStatus());
+ // validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ // Double.parseDouble(resourceAuditJavaObject.getStatus()));
+ validateField(actualAuditRecords, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDesc());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getComment());
+ // validateField(map2,
+ // AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
+ // resourceAuditJavaObject.getArtifactData());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.TOSCA_NODE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getToscaNodeType());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrArtifactUuid());
+ validateField(actualAuditRecords, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getPrevArtifactUuid());
+
+ validateAtifactDataField(actualAuditRecords, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getArtifactData(), checkAllFields);
+ }
+
+ public static void validateExternalAudit(ExpectedExternalAudit externalAuditObject, String action,
+ Map<AuditingFieldsKeysEnum, String> body) throws Exception {
+
+ Map<String, Object> actualAuditRecord = new HashMap<String, Object>();
+ actualAuditRecord = parseAuditResourceByAction(action, body);
+
+ validateField(actualAuditRecord, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(actualAuditRecord, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
+ externalAuditObject.getCONSUMER_ID());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
+ externalAuditObject.getRESOURCE_URL());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ externalAuditObject.getRESOURCE_NAME());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(),
+ externalAuditObject.getSERVICE_INSTANCE_ID());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ externalAuditObject.getRESOURCE_TYPE());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ externalAuditObject.getSTATUS());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ externalAuditObject.getDESC());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ externalAuditObject.getMODIFIER());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.PREV_ARTIFACT_UUID.getAuditJsonKeyName(),
+ externalAuditObject.getPREV_ARTIFACT_UUID());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.CURR_ARTIFACT_UUID.getAuditJsonKeyName(),
+ externalAuditObject.getCURR_ARTIFACT_UUID());
+ validateField(actualAuditRecord, AuditJsonKeysEnum.ARTIFACT_DATA.getAuditJsonKeyName(),
+ externalAuditObject.getARTIFACT_DATA());
+
+ }
+
+ public enum ArtifactDataFieldEnum {
+ attGroup, artLable, artType, artName, artTimeout, artPayloadUUID, artVersion, artUUID
+ }
+
+ private static void validateAtifactDataField(Map<String, Object> map, String auditJsonKeyName,
+ String expectedArtifactData, boolean checkAllFields) {
+ Map<ArtifactDataFieldEnum, String> expectedArtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
+ Map<ArtifactDataFieldEnum, String> actualAtifactDataFileds = new HashMap<ArtifactDataFieldEnum, String>();
+ if (expectedArtifactData != null) {
+ String[] expected = expectedArtifactData.split(",");
+
+ assertTrue("Audit field " + auditJsonKeyName + " not found", map.containsKey(auditJsonKeyName));
+ String actualValue = (String) map.get(auditJsonKeyName);
+ String[] actual = actualValue.split(",");
+
+ if (expected.length == 1 && actual.length == 1) {
+ assertEquals(expectedArtifactData, actualValue);
+ return;
+ }
+
+ assertEquals(ArtifactDataFieldEnum.values().length, expected.length);
+ assertEquals(ArtifactDataFieldEnum.values().length, actual.length);
+
+ for (ArtifactDataFieldEnum field : ArtifactDataFieldEnum.values()) {
+
+ expectedArtifactDataFileds.put(field, expected[field.ordinal()]);
+ actualAtifactDataFileds.put(field, actual[field.ordinal()]);
+ }
+ for (Map.Entry<ArtifactDataFieldEnum, String> entry : expectedArtifactDataFileds.entrySet()) {
+ ArtifactDataFieldEnum field = entry.getKey();
+ if (checkAllFields || (!field.equals(ArtifactDataFieldEnum.artVersion)
+ && !field.equals(ArtifactDataFieldEnum.artUUID))) {
+ assertTrue("Audit field ArtifactData dosn't containt " + field,
+ actualAtifactDataFileds.containsKey(field));
+ assertEquals("Audit field ArtifactData dosn't equal " + field,
+ expectedArtifactDataFileds.get(field), actualAtifactDataFileds.get(field));
+ }
+
+ }
+ }
+ }
+
+ // //Benny
+ public static void validateEcompConsumerAudit(ExpectedEcomConsumerAudit ecompConsumerAuditJavaObject, String action)
+ throws Exception {
+
+ String fixedAction = BaseRestUtils.encodeUrlForDownload(action);
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(fixedAction, null);
+
+ validateField(map2, EcompConsumerAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ ecompConsumerAuditJavaObject.getModifier());
+ validateField(map2, EcompConsumerAuditJsonKeysEnum.ECOMP_USER.getAuditJsonKeyName(),
+ ecompConsumerAuditJavaObject.getEcomUser());
+ validateField(map2, EcompConsumerAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ ecompConsumerAuditJavaObject.getStatus());
+ validateField(map2, EcompConsumerAuditJsonKeysEnum.DESC.getAuditJsonKeyName(),
+ ecompConsumerAuditJavaObject.getDesc());
+ validateField(map2, EcompConsumerAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ }
+
+ public static void ecompConsumerAuditSuccess(String action, ConsumerDataDefinition consumerDataDefinition,
+ User user, int status) throws Exception {
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(action);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(
+ consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase()
+ + "," + consumerDataDefinition.getConsumerPassword().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(String.valueOf(status));
+ expectedEcomConsumerAuditJavaObject.setDesc("OK");
+ expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
+ }
+
+ public static void createEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition,
+ User user, ActionStatus errorMessage, Object... variables) throws Exception {
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ expectedEcomConsumerAuditJavaObject.setAction(action);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(
+ consumerDataDefinition.getConsumerName() + "," + consumerDataDefinition.getConsumerSalt().toLowerCase()
+ + "," + consumerDataDefinition.getConsumerPassword().toLowerCase());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
+ }
+
+ public static void deleteEcompConsumerAuditFailure(String action, ConsumerDataDefinition consumerDataDefinition,
+ User user, ActionStatus errorMessage, Object... variables) throws Exception {
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
+ ExpectedEcomConsumerAudit expectedEcomConsumerAuditJavaObject = new ExpectedEcomConsumerAudit();
+ // String auditAction = ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION;
+ expectedEcomConsumerAuditJavaObject.setAction(action);
+ expectedEcomConsumerAuditJavaObject.setEcomUser(consumerDataDefinition.getConsumerName());
+ expectedEcomConsumerAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ expectedEcomConsumerAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ expectedEcomConsumerAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ AuditValidationUtils.validateEcompConsumerAudit(expectedEcomConsumerAuditJavaObject, action);
+ }
+
+ ////////////////////// US571255
+ public static void GetListOfUsersByRolesAuditFailure(String action, String roles, int status, User userModifier,
+ ActionStatus errorMessage, Object... variables) throws Exception {
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
+ ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit(); // String
+ // auditAction
+ // =
+ // ADD_ECOMP_USER_CREDENTIALS_AUDIT_ACTION;
+ expectedGetListOfUsersAuditJavaObject.setAction(action);
+ expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
+ expectedGetListOfUsersAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+
+ expectedGetListOfUsersAuditJavaObject.setDetails(roles);
+ if (errorMessage == ActionStatus.USER_INACTIVE || errorMessage == ActionStatus.MISSING_INFORMATION) {
+ expectedGetListOfUsersAuditJavaObject.setModifier("(UNKNOWN)");
+ } else {
+ expectedGetListOfUsersAuditJavaObject
+ .setModifier(userModifier.getFullName() + "(" + userModifier.getUserId() + ")");
+ }
+ AuditValidationUtils.validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
+ }
+
+ public static void GetListOfUsersByRolesAuditSuccess(String action, String roles, User user, int status)
+ throws Exception {
+ ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit();
+ expectedGetListOfUsersAuditJavaObject.setAction(action);
+ expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
+ expectedGetListOfUsersAuditJavaObject.setDesc("OK");
+ expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ expectedGetListOfUsersAuditJavaObject.setDetails(roles);
+ validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
+ }
+
+ public static void validateAuditGetListOfUsersByRoles(ExpectedGetUserListAudit GetListOfUsersAuditJavaObject,
+ String action) throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), GetListOfUsersAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ GetListOfUsersAuditJavaObject.getModifier());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ GetListOfUsersAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(),
+ GetListOfUsersAuditJavaObject.getDetails());
+ }
+
+ public static void validateAuditImport(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
+ throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ resourceAuditJavaObject.setModifierUid(
+ getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getPrevVersion());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
+ validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+
+ }
+
+ public static void validateAuditDistribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
+ throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ resourceAuditJavaObject.setModifierUid(
+ getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
+ validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDprevStatus());
+ validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDcurrStatus());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
+ validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
+
+ }
+
+ // Benny
+ public static void validateAudit_Distribution(ExpectedResourceAuditJavaObject resourceAuditJavaObject,
+ String action) throws Exception {
+
+ List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
+ Map<String, Object> map2 = actionToList.get(0);
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
+ validateField(map2, AuditJsonKeysEnum.DPREV_STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDprevStatus());
+ validateField(map2, AuditJsonKeysEnum.DCURR_STATUS.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getDcurrStatus());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
+
+ }
+
+ public void validateAuditNotification(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
+ throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ resourceAuditJavaObject.setModifierUid(
+ getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
+ validateField(map2, AuditJsonKeysEnum.TOPIC_NAME.getAuditJsonKeyName(), resourceAuditJavaObject.getTopicName());
+
+ }
+
+ public static void validateAudit(ExpectedDistDownloadAudit expectedDistDownloadAudit, String action)
+ throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), expectedDistDownloadAudit.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), expectedDistDownloadAudit.getDesc());
+ validateField(map2, AuditJsonKeysEnum.CONSUMER_ID.getAuditJsonKeyName(),
+ expectedDistDownloadAudit.getConsumerId());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_URL.getAuditJsonKeyName(),
+ expectedDistDownloadAudit.getResourceUrl());
+ }
+
+ public void validateAuditDeploy(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
+ throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ resourceAuditJavaObject.setModifierUid(
+ getModifierString(resourceAuditJavaObject.getModifierName(), resourceAuditJavaObject.getModifierUid()));
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getModifierUid());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.DID.getAuditJsonKeyName(), resourceAuditJavaObject.getDistributionId());
+
+ }
+
+ public static void validateAuditProduct(ExpectedProductAudit productExpectedAudit, String action,
+ AuditJsonKeysEnum... additionalFields) throws Exception {
+
+ Map<String, Object> map2 = new HashMap<String, Object>();
+ map2 = parseAuditResourceByAction(action, null);
+
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ productExpectedAudit.getRESOURCE_NAME());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ productExpectedAudit.getRESOURCE_TYPE());
+ validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
+ productExpectedAudit.getPREV_VERSION());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ productExpectedAudit.getCURR_VERSION());
+ validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), productExpectedAudit.getPREV_STATE());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), productExpectedAudit.getCURR_STATE());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), productExpectedAudit.getMODIFIER());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), productExpectedAudit.getSTATUS());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), productExpectedAudit.getDESC());
+ validateField(map2, AuditJsonKeysEnum.SERVICE_INSTANCE_ID.getAuditJsonKeyName(),
+ productExpectedAudit.getSERVICE_INSTANCE_ID());
+ if (additionalFields != null) {
+ List<AuditJsonKeysEnum> fieldsList = Arrays.asList(additionalFields);
+ if (fieldsList.contains(AuditJsonKeysEnum.COMMENT)) {
+ validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), productExpectedAudit.getCOMMENT());
+ }
+ }
+ }
+
+ private static List<Map<String, Object>> getAuditListByAction(String action, int expectedNumOfAudit)
+ throws Exception {
+ List<Map<String, Object>> actionToList = parseAuditResourceByActionToList(action, null);
+ assertEquals("recieved different audits number than expected", expectedNumOfAudit, actionToList.size());
+ return actionToList;
+ }
+
+ public static void validateAuthenticationAudit(ExpectedAuthenticationAudit expectedAudit) throws Exception {
+ List<Map<String, Object>> actionToList = getAuditListByAction(expectedAudit.getAction(), 1);
+ assertEquals("expected number of ES action is 1", 1, actionToList.size());
+
+ Map<String, Object> map = actionToList.get(0);
+ validateField(map, AuditEnum.ACTION.getValue(), expectedAudit.getAction());
+ validateField(map, AuditEnum.URL.getValue(), expectedAudit.getUrl());
+ validateField(map, AuditEnum.USER.getValue(), expectedAudit.getUser());
+ validateField(map, AuditEnum.AUTH_STATUS.getValue(), expectedAudit.getAuthStatus());
+ validateField(map, AuditEnum.REALM.getValue(), expectedAudit.getRealm());
+
+ }
+
+ private static void validateField(Map<String, Object> actualAuditRecord, String jsonField, Object expectedValue) {
+ if (expectedValue == null) {
+ // || changed to &&
+ if (actualAuditRecord.containsKey(jsonField)) {
+ assertTrue("Audit field " + jsonField + ": expected null, actual " + actualAuditRecord.get(jsonField),
+ actualAuditRecord.get(jsonField).toString().equals("null")
+ || actualAuditRecord.get(jsonField).toString().equals(Constants.EMPTY_STRING));
+ }
+
+ } else {
+ assertTrue("Audit field " + jsonField + " not found in actual", actualAuditRecord.containsKey(jsonField));
+ Object foundValue = actualAuditRecord.get(jsonField);
+ compareElements(expectedValue, foundValue);
+ }
+ }
+
+ private static void compareElements(Object expectedValue, Object foundValue) {
+ if (expectedValue instanceof String) {
+ assertTrue("Actual value " + foundValue + " is not string", foundValue instanceof String);
+ assertTrue("Expected " + expectedValue + " not equal to actual " + foundValue,
+ foundValue.equals(expectedValue));
+ }
+ /*
+ * else if( expectedValue instanceof Number){ assertTrue(foundValue
+ * instanceof Number); assertTrue(foundValue == expectedValue); }
+ */
+ else if (expectedValue instanceof Boolean) {
+ assertTrue(foundValue instanceof Boolean);
+ assertTrue(foundValue == expectedValue);
+ } else if (expectedValue instanceof Map) {
+ assertTrue(foundValue instanceof Map);
+ Map<String, Object> foundMap = (Map<String, Object>) foundValue;
+ Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
+ assertTrue(foundMap.size() == excpectedMap.size());
+ Iterator<String> foundkeyItr = foundMap.keySet().iterator();
+ while (foundkeyItr.hasNext()) {
+ String foundKey = foundkeyItr.next();
+ assertTrue(excpectedMap.containsKey(foundKey));
+ compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey));
+ }
+
+ } else if (expectedValue instanceof List) {
+ assertTrue(foundValue instanceof List);
+ List<Object> foundList = (List<Object>) foundValue;
+ List<Object> excpectedList = (List<Object>) expectedValue;
+ assertTrue(foundList.size() == excpectedList.size());
+ for (int i = 0; i < foundList.size(); i++) {
+ compareElements(excpectedList.get(i), foundList.get(i));
+ }
+
+ } else {
+ assertTrue(foundValue.equals(expectedValue));
+ }
+ }
+
+ // public static Map<String, Object> parseAuditResourceByAction(String
+ // action, String body) throws Exception {
+ //
+ // Map auditingMessage = null;
+ // auditingMessage = retrieveAuditMessagesByPattern(action, null);
+ //
+ // return auditingMessage;
+ //
+ // }
+
+ public static Map<String, Object> parseAuditResourceByAction(String action,
+ Map<AuditingFieldsKeysEnum, String> body) throws Exception {
+
+ Map auditingMessage = null;
+ auditingMessage = retrieveAuditMessagesByPattern(action, body);
+
+ return auditingMessage;
+
+ }
+
+ // public static List<Map<String, Object>>
+ // parseAuditResourceByActionToList(String action, String body) throws
+ // Exception {
+ //
+ // List<Map<String, Object>> auditList = new ArrayList<Map<String,
+ // Object>>();
+ //
+ //// String auditingMessage = null;
+ //
+ // Map auditingMessage = null;
+ // auditingMessage = retrieveAuditMessagesByPattern(action);
+ //
+ // if (body == null) {
+ //// String pattern = "/_search?q=ACTION:\"" + action + "\"";
+ //// auditingMessage = retrieveAuditMessagesByPattern(action);
+ //// auditingMessage = retrieveAuditMessagesByPattern(pattern);
+ // } else {
+ //// auditingMessage = retrieveAuditMessagesUsingBody(body);
+ // }
+ //
+ // return ResponseParser.getAuditFromMessage(auditingMessage);
+ //
+ // }
+
+ public static List<Map<String, Object>> parseAuditResourceByActionToList(String action,
+ Map<AuditingFieldsKeysEnum, String> body) throws Exception {
+
+ List<Map<String, Object>> auditList = new ArrayList<Map<String, Object>>();
+
+ // String auditingMessage = null;
+
+ Map auditingMessage = null;
+
+ if (body == null || body.isEmpty()) {
+ auditingMessage = retrieveAuditMessagesByPattern(action, null);
+ // String pattern = "/_search?q=ACTION:\"" + action + "\"";
+ // auditingMessage = retrieveAuditMessagesByPattern(action);
+ // auditingMessage = retrieveAuditMessagesByPattern(pattern);
+ } else {
+ auditingMessage = retrieveAuditMessagesByPattern(action, body);
+ // auditingMessage = retrieveAuditMessagesUsingBody(body);
+ }
+
+ return ResponseParser.getAuditFromMessage(auditingMessage);
+
+ }
+
+ public JSONObject buildElasticQueryStringObject(String defaultField, String queryValue) throws JSONException {
+
+ JSONObject query_string = new JSONObject();
+ JSONObject jSONObject = new JSONObject();
+ jSONObject.put("default_field", defaultField);
+ jSONObject.put("query", queryValue);
+
+ query_string.put("query_string", jSONObject);
+
+ return query_string;
+ }
+
+ public static JSONObject buildElasticQueryBody(List<JSONObject> listObjects) throws JSONException {
+
+ JSONObject query = new JSONObject();
+ JSONObject bool = new JSONObject();
+ JSONObject must = new JSONObject();
+ JSONArray mustA = new JSONArray();
+
+ for (int i = 0; i < listObjects.size(); i++) {
+ JSONObject match = new JSONObject();
+ match.put("match", listObjects.get(i));
+ mustA.put(match);
+
+ }
+
+ must.put("must", mustA);
+ bool.put("bool", must);
+ query.put("query", bool);
+
+ return query;
+ }
+
+ public static String retrieveAuditMessagesUsingBody(String query_string) throws IOException {
+
+ Config config = Utils.getConfig();
+ HttpRequest getAuditingMessage = new HttpRequest();
+ Map<String, String> headersMap = new HashMap<String, String>();
+ String body = query_string;
+
+ String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, config.getEsHost(), config.getEsPort(), "_search");
+ RestResponse restResponse = getAuditingMessage.httpSendPost(url, body, headersMap);
+
+ return restResponse.getResponse();
+ }
+
+ public static Map retrieveAuditMessagesByPattern(String action, Map<AuditingFieldsKeysEnum, String> body)
+ throws IOException {
+
+ // get cassandra table name by action
+ String esType = AuditingActionEnum.getActionByName(action).getAuditingEsType();
+
+ List<Pair<AuditingFieldsKeysEnum, String>> myFields = new ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
+ Pair<AuditingFieldsKeysEnum, String> myPair = new Pair<AuditingFieldsKeysEnum, String>(
+ AuditingFieldsKeysEnum.AUDIT_ACTION, action);
+ myFields.add(0, myPair);
+ if (body != null && !body.isEmpty()) {
+ for (Map.Entry<AuditingFieldsKeysEnum, String> mapElement : body.entrySet()) {
+ myFields.add(new Pair<AuditingFieldsKeysEnum, String>(mapElement.getKey(), mapElement.getValue()));
+ }
+ }
+
+ List<Row> fetchFromTable = CassandraUtils.fetchFromTable(auditKeySpaceName, esType, myFields);
+ assertTrue("expected on fetching from data base one record only, actual: " + fetchFromTable.size(),
+ fetchFromTable.size() == 1);
+ Row row = fetchFromTable.get(0);
+
+ ColumnDefinitions columnDefinitions = row.getColumnDefinitions();
+
+ Map<String, String> resultsMap = new HashMap<String, String>();
+
+ for (int i = 0; i < columnDefinitions.size(); i++) {
+ resultsMap.put(columnDefinitions.getName(i), row.getObject(columnDefinitions.getName(i)) == null ? "null"
+ : row.getObject(columnDefinitions.getName(i)).toString());
+ }
+
+ return resultsMap;
+ }
+
+ // public static Map retrieveAuditMessagesByPattern(String pattern) throws
+ // IOException {
+ //
+ //// Config config = Utils.getConfig();
+ //// HttpRequest getAuditingMessage = new HttpRequest();
+ //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES,
+ // config.getEsHost(), config.getEsPort(), pattern);
+ //// RestResponse restResponse = getAuditingMessage.httpSendGet(url, null);
+ //
+ //// get cassandra table name by action
+ // String esType =
+ // AuditingActionEnum.getActionByName(pattern).getAuditingEsType();
+ //// AuditingActionEnum actionByName =
+ // AuditingActionEnum.getActionByName(pattern);
+ //
+ //// Map<AuditingFieldsKeysEnum, String> myFields= new
+ // HashMap<AuditingFieldsKeysEnum, String>();
+ //// myFields.put(AuditingFieldsKeysEnum.AUDIT_ACTION , pattern);
+ //
+ // List<Pair<AuditingFieldsKeysEnum, String>> myFields = new
+ // ArrayList<Pair<AuditingFieldsKeysEnum, String>>();
+ // Pair<AuditingFieldsKeysEnum, String> myPair = new
+ // Pair<AuditingFieldsKeysEnum, String>(AuditingFieldsKeysEnum.AUDIT_ACTION
+ // , pattern);
+ // myFields.add(0, myPair);
+ //
+ //
+ // List<Row> fetchFromTable = CassandraUtils.fetchFromTable("sdcaudit",
+ // esType, myFields);
+ // Row row = fetchFromTable.get(0);
+ //
+ //
+ // ColumnDefinitions columnDefinitions = row.getColumnDefinitions();
+ //// String string = row.getString(columnDefinitions.getName(1));
+ //
+ //// String metaData = row.getColumnDefinitions().toString();
+ //// metaData =metaData.replaceAll("\\((.*?)\\)|\\[|\\]|Columns", "");
+ //// List<String> metaDataList = new
+ // ArrayList<String>(Arrays.asList(metaData.split(", ")));
+ //
+ //
+ //
+ // Map<String, String> resultsMap = new HashMap<String, String>();
+ //
+ //
+ // for (int i=0 ; i < columnDefinitions.size() ; i++){
+ // resultsMap.put(columnDefinitions.getName(i) ,
+ // row.getObject(columnDefinitions.getName(i)) == null ? "null" :
+ // row.getObject(columnDefinitions.getName(i)).toString());
+ // }
+ //// for (String string : metaDataList) {
+ //// resultsMap.put(string , row.getString(string));
+ //// }
+ ////
+ //
+ //// String dataString = fetchFromTable.toString();
+ //// dataString = dataString.replaceAll("\\[|\\]|Row", "");
+ //// List<String> dataArray = new
+ // ArrayList<String>(Arrays.asList(dataString.split(", ")));
+ ////
+ ////
+ //// Map<String, String> resultsMap = new HashMap<String, String>();
+ //// for (int i=0 ; i<metaDataList.size() ; i++) {
+ //// resultsMap.put(metaDataList.get(i), dataArray.get(i));
+ //// }
+ ////
+ //// return restResponse.getResponse();
+ // return resultsMap;
+ // }
+
+ public static void categoryAuditSuccess(String action, CategoryDefinition categoryDefinition, User user, int status,
+ String resourceType) throws Exception {
+ categoryAuditSuccessInternal(action, categoryDefinition, null, null, user, status, resourceType);
+ }
+
+ public static void categoryAuditFailure(String action, CategoryDefinition categoryDataDefinition, User user,
+ ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
+ categoryAuditFailureInternal(action, categoryDataDefinition, null, null, user, errorMessage, status,
+ resourceType, variables);
+ }
+
+ public static void subCategoryAuditSuccess(String action, CategoryDefinition categoryDefinition,
+ SubCategoryDefinition subCategoryDefinition, User user, int status, String resourceType) throws Exception {
+ categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, null, user, status,
+ resourceType);
+ }
+
+ public static void groupingAuditSuccess(String action, CategoryDefinition categoryDefinition,
+ SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
+ String resourceType) throws Exception {
+ categoryAuditSuccessInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
+ status, resourceType);
+ }
+
+ public static void subCategoryAuditFailure(String action, CategoryDefinition categoryDataDefinition,
+ SubCategoryDefinition subCategoryDefinition, User user, ActionStatus errorMessage, int status,
+ String resourceType, Object... variables) throws Exception {
+ categoryAuditFailureInternal(action, categoryDataDefinition, subCategoryDefinition, null, user, errorMessage,
+ status, resourceType, variables);
+ }
+
+ // NEW Benny
+ public static void groupingAuditFailure(String action, CategoryDefinition categoryDefinition,
+ SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
+ ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
+ groupingAuditFailureInternal(action, categoryDefinition, subCategoryDefinition, groupingDefinition, user,
+ errorMessage, status, resourceType, variables);
+ }
+
+ private static void groupingAuditFailureInternal(String action, CategoryDefinition categoryDataDefinition,
+ SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
+ ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(action);
+ expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
+ String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
+ : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
+ String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
+ expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
+ }
+
+ ///
+ private static void categoryAuditSuccessInternal(String action, CategoryDefinition categoryDefinition,
+ SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user, int status,
+ String resourceType) throws Exception {
+ // resourceType = Service/Resource/Product
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(action);
+ expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDefinition.getName());
+ String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
+ : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
+ String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
+ expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
+ expectedCatrgoryAuditJavaObject.setDesc("OK");
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
+ }
+
+ ///////////////////////////
+ ///// BENNNNNNNNY
+ public enum UserAuditJsonKeysEnum {
+ ACTION("ACTION"), MODIFIER("MODIFIER"), STATUS("STATUS"), DESC("DESCRIPTION"), USER_AFTER(
+ "USER_AFTER"), USER_BEFORE("USER_BEFORE");
+ private String auditJsonKeyName;
+
+ private UserAuditJsonKeysEnum(String auditJsonKeyName) {
+ this.auditJsonKeyName = auditJsonKeyName;
+ }
+
+ public String getAuditJsonKeyName() {
+ return auditJsonKeyName.toLowerCase();
+ }
+ }
+
+ public static void validateAddUserAudit(ExpectedUserCRUDAudit expectedAddUserAuditJavaObject, String action)
+ throws Exception {
+
+ List<Map<String, Object>> actionToList = getAuditListByAction(expectedAddUserAuditJavaObject.getAction(), 1);
+ Map<String, Object> map = actionToList.get(0);
+ validateField(map, UserAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map, UserAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ expectedAddUserAuditJavaObject.getModifier());
+ validateField(map, UserAuditJsonKeysEnum.USER_AFTER.getAuditJsonKeyName(),
+ expectedAddUserAuditJavaObject.getUserAfter());
+ validateField(map, UserAuditJsonKeysEnum.USER_BEFORE.getAuditJsonKeyName(),
+ expectedAddUserAuditJavaObject.getUserBefore());
+ validateField(map, UserAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ expectedAddUserAuditJavaObject.getStatus());
+ validateField(map, UserAuditJsonKeysEnum.DESC.getAuditJsonKeyName(), expectedAddUserAuditJavaObject.getDesc());
+
+ }
+
+ private static void categoryAuditFailureInternal(String action, CategoryDefinition categoryDataDefinition,
+ SubCategoryDefinition subCategoryDefinition, GroupingDefinition groupingDefinition, User user,
+ ActionStatus errorMessage, int status, String resourceType, Object... variables) throws Exception {
+ // validate audit
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorMessage.name());
+ ExpectedCategoryAudit expectedCatrgoryAuditJavaObject = new ExpectedCategoryAudit();
+ expectedCatrgoryAuditJavaObject.setAction(action);
+ expectedCatrgoryAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ expectedCatrgoryAuditJavaObject.setCategoryName(categoryDataDefinition.getName());
+ String subCategoryName = (subCategoryDefinition != null ? subCategoryDefinition.getName()
+ : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setSubCategoryName(subCategoryName);
+ String groupingName = (groupingDefinition != null ? groupingDefinition.getName() : Constants.EMPTY_STRING);
+ expectedCatrgoryAuditJavaObject.setGroupingName(groupingName);
+ expectedCatrgoryAuditJavaObject.setResourceType(resourceType);
+ expectedCatrgoryAuditJavaObject.setStatus(String.valueOf(status));
+ expectedCatrgoryAuditJavaObject.setDesc(errorInfo.getAuditDesc(variables));
+ AuditValidationUtils.validateCategoryAudit(expectedCatrgoryAuditJavaObject, action);
+ }
+
+ public static void validateGetCategoryHirarchy(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action)
+ throws Exception {
+
+ List<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
+ Map<String, Object> map = actionToList.get(0);
+
+ expectedCatrgoryAuditJavaObject.setModifier(getModifierString(expectedCatrgoryAuditJavaObject.getModifierName(),
+ expectedCatrgoryAuditJavaObject.getModifierUid()));
+ validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getModifier());
+ validateField(map, CategoryAuditJsonKeysEnum.DETAILS.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getDetails());
+ validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getStatus());
+ validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getDesc());
+
+ }
+
+ public static void validateCategoryAudit(ExpectedCategoryAudit expectedCatrgoryAuditJavaObject, String action)
+ throws Exception {
+
+ List<Map<String, Object>> actionToList = getAuditListByAction(expectedCatrgoryAuditJavaObject.getAction(), 1);
+ Map<String, Object> map = actionToList.get(0);
+ validateField(map, CategoryAuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map, CategoryAuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getModifier());
+ validateField(map, CategoryAuditJsonKeysEnum.CATEGORY_NAME.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getCategoryName());
+ validateField(map, CategoryAuditJsonKeysEnum.SUB_CATEGORY_NAME.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getSubCategoryName());
+ validateField(map, CategoryAuditJsonKeysEnum.GROUPING_NAME.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getGroupingName());
+ validateField(map, CategoryAuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getResourceType());
+ validateField(map, CategoryAuditJsonKeysEnum.STATUS.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getStatus());
+ validateField(map, CategoryAuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(),
+ expectedCatrgoryAuditJavaObject.getDesc());
+ }
+
+ public static void GetCategoryHierarchyAuditSuccess(String action, String componentType, User user, int status)
+ throws Exception {
+ ExpectedGetUserListAudit expectedGetListOfUsersAuditJavaObject = new ExpectedGetUserListAudit();
+ expectedGetListOfUsersAuditJavaObject.setAction(action);
+ expectedGetListOfUsersAuditJavaObject.setStatus(String.valueOf(status));
+ expectedGetListOfUsersAuditJavaObject.setDesc("OK");
+ expectedGetListOfUsersAuditJavaObject.setModifier(user.getFullName() + "(" + user.getUserId() + ")");
+ expectedGetListOfUsersAuditJavaObject.setDetails(componentType.toLowerCase());
+ validateAuditGetListOfUsersByRoles(expectedGetListOfUsersAuditJavaObject, action);
+ }
+
+ public static String buildArtifactDataAudit(ArtifactDefinition artifactDefinition) {
+ StringBuilder sb = new StringBuilder();
+ if (artifactDefinition.getTimeout() == null) {
+ artifactDefinition.setTimeout(0);
+ }
+ if (artifactDefinition != null) {
+ sb.append(artifactDefinition.getArtifactGroupType() == null ? null
+ : artifactDefinition.getArtifactGroupType().getType()).append(",").append("'")
+ .append(artifactDefinition.getArtifactLabel()).append("'").append(",")
+ .append(artifactDefinition.getArtifactType()).append(",")
+ .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout())
+ .append(",").append(artifactDefinition.getEsId());
+ sb.append(",");
+ if (artifactDefinition.getArtifactVersion() != null) {
+ sb.append(artifactDefinition.getArtifactVersion());
+ } else {
+ sb.append(" ");
+ }
+ sb.append(",");
+ if (artifactDefinition.getArtifactUUID() != null) {
+ sb.append(artifactDefinition.getArtifactUUID());
+ } else {
+ sb.append(" ");
+ }
+ }
+
+ return sb.toString();
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedMissingInformationAuditObject(String Action,
+ String resourceUid, ComponentType resourceType) throws FileNotFoundException {
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceUid);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion("");
+ expectedAudit.setModifierName("");
+ expectedAudit.setModifierUid("");
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState("");
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid("");
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("403");
+ expectedAudit.setDesc(buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.MISSING_INFORMATION.name()),
+ new ArrayList<String>()));
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedComponentNotFoundAuditObject(String Action,
+ String resourceUid, ComponentType resourceType, String artifactUid, User user,
+ ArrayList<String> notFoundComponent) throws FileNotFoundException {
+ String desc = null;
+
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceUid);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion("");
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState("");
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid(artifactUid);
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("404");
+
+ if (resourceType.getValue() == ComponentType.SERVICE.getValue()) {
+ desc = buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.SERVICE_NOT_FOUND.name()),
+ notFoundComponent);
+ } else if (resourceType.getValue() == ComponentType.RESOURCE.getValue())
+ desc = buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESOURCE_NOT_FOUND.name()),
+ notFoundComponent);
+
+ expectedAudit.setDesc(desc);
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action, String resourceUid,
+ ComponentType resourceType, String artifactUid, User user, String currState, String currVersion)
+ throws FileNotFoundException {
+ String desc = null;
+
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceUid);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion(currVersion);
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState(currState);
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid(artifactUid);
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("404");
+
+ desc = buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()),
+ Arrays.asList(""));
+
+ expectedAudit.setDesc(desc);
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedArtifactNotFoundAuditObject(String Action,
+ String resourceName, ComponentType resourceType, String artifactUid, LifecycleStateEnum lifecycle,
+ User user, String currVersion) throws FileNotFoundException {
+ String desc = null;
+
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceName);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion(currVersion);
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState(lifecycle.name());
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid(artifactUid);
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("404");
+
+ desc = buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.ARTIFACT_NOT_FOUND.name()),
+ new ArrayList<String>());
+
+ expectedAudit.setDesc(desc);
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedRestrictedOperationAuditObject(String Action,
+ String resourceNameOrUid, ComponentType resourceType, String artifactUid, User user, String currVersion,
+ String currState) throws FileNotFoundException {
+ String desc = null;
+
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceNameOrUid);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion(currVersion);
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState(currState);
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid(artifactUid);
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("409");
+
+ desc = buildAuditDescription(
+ new ErrorValidationUtils().parseErrorConfigYaml(ActionStatus.RESTRICTED_OPERATION.name()),
+ new ArrayList<String>());
+
+ expectedAudit.setDesc(desc);
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(String Action, String resourceName,
+ ComponentType resourceType, String artifactUid, User user, String currVersion, String currState,
+ ArrayList<String> invalidContentList) throws FileNotFoundException {
+ return expectedInvalidContentAuditObject(ActionStatus.INVALID_CONTENT, Action, resourceName, resourceType,
+ artifactUid, user, currVersion, currState, invalidContentList);
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedInvalidContentAuditObject(ActionStatus actionStatus,
+ String Action, String resourceName, ComponentType resourceType, String artifactUid, User user,
+ String currVersion, String currState, ArrayList<String> invalidContentList) throws FileNotFoundException {
+ String desc = null;
+
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceName);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion(currVersion);
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState(currState);
+ expectedAudit.setPrevArtifactUuid("");
+ expectedAudit.setCurrArtifactUuid(artifactUid);
+ expectedAudit.setArtifactData("");
+ expectedAudit.setStatus("400");
+
+ desc = buildAuditDescription(new ErrorValidationUtils().parseErrorConfigYaml(actionStatus.name()),
+ invalidContentList);
+
+ expectedAudit.setDesc(desc);
+ return expectedAudit;
+ }
+
+ public static ExpectedResourceAuditJavaObject expectedSuccessAuditObject(String Action, String resourceName,
+ ComponentType resourceType, ArtifactReqDetails artifactReq, User user, String currVersion, String currState,
+ String prevArtifactUuid) throws FileNotFoundException {
+ ExpectedResourceAuditJavaObject expectedAudit = new ExpectedResourceAuditJavaObject();
+ expectedAudit.setAction(Action);
+ expectedAudit.setResourceName(resourceName);
+ expectedAudit.setResourceType(resourceType.getValue());
+ expectedAudit.setPrevVersion("");
+ expectedAudit.setCurrVersion(currVersion);
+ expectedAudit.setModifierName(user.getFirstName() + " " + user.getLastName());
+ expectedAudit.setModifierUid(user.getUserId());
+ expectedAudit.setPrevState("");
+ expectedAudit.setCurrState(currState);
+ expectedAudit.setPrevArtifactUuid(prevArtifactUuid);
+ expectedAudit.setCurrArtifactUuid(artifactReq.getUniqueId());
+ expectedAudit
+ .setArtifactData(buildArtifactDataAudit(ArtifactUtils.convertArtifactReqToDefinition(artifactReq)));
+ expectedAudit.setStatus("200");
+ expectedAudit.setDesc("OK");
+ return expectedAudit;
+ }
+
+ public static JSONObject filterAuditByUuid(String action, String uuid) throws Exception {
+ Map<String, String> actionMap = new HashMap<String, String>();
+ actionMap.put("ACTION", action);
+ JSONObject actionJsonObject = new JSONObject(actionMap);
+ Map<String, String> uuidMap = new HashMap<String, String>();
+ uuidMap.put("SERVICE_INSTANCE_ID", uuid);
+ JSONObject uuidJsonObject = new JSONObject(uuidMap);
+
+ List<JSONObject> filters = new ArrayList<JSONObject>(Arrays.asList(actionJsonObject, uuidJsonObject));
+ JSONObject body = buildElasticQueryBody(filters);
+ return body;
+ }
+
+ public static void validateAudit(ExpectedResourceAuditJavaObject resourceAuditJavaObject, String action)
+ throws Exception {
+ List<Map<String, Object>> actionToList = getAuditListByAction(resourceAuditJavaObject.getAction(), 1);
+ Map<String, Object> map2 = actionToList.get(0);
+ validateField(map2, AuditJsonKeysEnum.ACTION.getAuditJsonKeyName(), action);
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_NAME.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceName());
+ validateField(map2, AuditJsonKeysEnum.RESOURCE_TYPE.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getResourceType());
+ validateField(map2, AuditJsonKeysEnum.PREV_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getPrevVersion());
+ validateField(map2, AuditJsonKeysEnum.CURR_VERSION.getAuditJsonKeyName(),
+ resourceAuditJavaObject.getCurrVersion());
+ validateField(map2, AuditJsonKeysEnum.MODIFIER.getAuditJsonKeyName(), resourceAuditJavaObject.getMODIFIER());
+ validateField(map2, AuditJsonKeysEnum.PREV_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getPrevState());
+ validateField(map2, AuditJsonKeysEnum.CURR_STATE.getAuditJsonKeyName(), resourceAuditJavaObject.getCurrState());
+ validateField(map2, AuditJsonKeysEnum.STATUS.getAuditJsonKeyName(), resourceAuditJavaObject.getStatus());
+ validateField(map2, AuditJsonKeysEnum.DESCRIPTION.getAuditJsonKeyName(), resourceAuditJavaObject.getDesc());
+ validateField(map2, AuditJsonKeysEnum.COMMENT.getAuditJsonKeyName(), resourceAuditJavaObject.getComment());
+ }
+
+ ////// service audit validation/////////////////////
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
+ String serviceVersion, User sdncUserDetails) {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+
+ expectedResourceAuditJavaObject.setAction("Create");
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
+ expectedResourceAuditJavaObject.setModifierName(userFirstLastName);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f));
+ expectedResourceAuditJavaObject.setCurrVersion(serviceVersion);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setComment(null);
+
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
+ String serviceVersion, User sdncUserDetails, ActionStatus errorStatus, List<String> variables)
+ throws FileNotFoundException {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = constructFieldsForAuditValidation(
+ serviceReqDetails, serviceVersion, sdncUserDetails);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorStatus.name());
+
+ expectedResourceAuditJavaObject.setStatus(errorInfo.getCode().toString());
+ String auditDesc = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ expectedResourceAuditJavaObject.setDesc(auditDesc);
+
+ return expectedResourceAuditJavaObject;
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
new file mode 100644
index 0000000000..eb3ee331ed
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/BaseValidationUtils.java
@@ -0,0 +1,116 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.FileNotFoundException;
+import java.util.Arrays;
+
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.exception.ResponseFormat;
+import org.testng.Assert;
+
+public class BaseValidationUtils {
+
+ public static final int STATUS_CODE_SUCCESS = 200;
+ public static final int STATUS_CODE_CREATED = 201;
+ public static final int STATUS_CODE_DELETE = 204;
+ public static final int STATUS_CODE_NOT_FOUND = 404;
+ public static final int STATUS_CODE_SUCCESS_NO_CONTENT = 204;
+ public static final int STATUS_CODE_SUCCESS_DELETE = 204;
+ public static final int STATUS_CODE_INVALID_CONTENT = 400;
+ public static final int STATUS_CODE_MISSING_DATA = 400;
+ public static final int STATUS_CODE_MISSING_INFORMATION = 403;
+ public static final int STATUS_CODE_RESTRICTED_ACCESS = 403;
+ public static final int STATUS_CODE_RESTRICTED_OPERATION = 409;
+ public static final int STATUS_CODE_ALREADY_EXISTS = 409;
+
+ // ------
+ protected static Boolean checkErrorCode(RestResponse deleteResponse) {
+ if (deleteResponse.getErrorCode() == STATUS_CODE_SUCCESS
+ || deleteResponse.getErrorCode() == STATUS_CODE_DELETE) {
+ return true;
+ }
+ return false;
+ }
+
+ // *** STATUS CODE VALIDATION UTIITIES ****
+ public static void checkStatusCode(RestResponse response, String assertMessage, boolean AND, int... statuses) {
+ int statusCode = response.getErrorCode();
+ for (int status : statuses) {
+ if (AND && statusCode != status) {
+ Assert.fail(assertMessage + " status: " + statusCode);
+ } else if (statusCode == status) {
+ return;
+ }
+ }
+ if (!AND) {
+ Assert.fail(assertMessage + " status: " + statusCode);
+ }
+ }
+
+ public static void checkDeleteResponse(RestResponse response) {
+ checkStatusCode(response, "delete request failed", false, STATUS_CODE_DELETE, STATUS_CODE_NOT_FOUND,
+ STATUS_CODE_SUCCESS); // STATUS_CODE_SUCCESS for deActivate user
+ }
+
+ public static void checkCreateResponse(RestResponse response) {
+ checkStatusCode(response, "create request failed", false, STATUS_CODE_CREATED);
+ }
+
+ public static void checkSuccess(RestResponse response) {
+ checkStatusCode(response, "request failed", false, STATUS_CODE_SUCCESS);
+ }
+
+ public static void checkErrorResponse(RestResponse errorResponse, ActionStatus actionStatus,
+ String... expectedVariables) throws FileNotFoundException {
+ // Expected error
+ ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ String expectedMessage = expectedError.getMessage();
+
+ // Actual error
+ ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(),
+ ResponseFormat.class);
+ String actualMessage = responseFormat.getText();
+ String[] actualVariables = responseFormat.getVariables();
+
+ assertEquals("Unexpected error message", expectedMessage, actualMessage);
+ assertEquals("Unexpected error variables", Arrays.asList(expectedVariables), Arrays.asList(actualVariables));
+ }
+
+ public static void checkErrorMessageResponse(RestResponse errorResponse, ActionStatus actionStatus)
+ throws FileNotFoundException {
+ // Expected error
+ ErrorInfo expectedError = ErrorValidationUtils.parseErrorConfigYaml(actionStatus.name());
+ String expectedMessage = expectedError.getMessage();
+
+ // Actual error
+ ResponseFormat responseFormat = ResponseParser.parseToObjectUsingMapper(errorResponse.getResponse(),
+ ResponseFormat.class);
+ String actualMessage = responseFormat.getText();
+
+ assertEquals("Unexpected error message", expectedMessage, actualMessage);
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
new file mode 100644
index 0000000000..cd2297fd19
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CategoryValidationUtils.java
@@ -0,0 +1,126 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+import static org.testng.AssertJUnit.assertTrue;
+
+import org.json.JSONObject;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
+
+public class CategoryValidationUtils {
+
+ public static void verifyCategoryExistInGetResponse(RestResponse getAllCategoryRest,
+ CategoryDefinition categoryDefinition) {
+
+ int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition);
+ assertEquals("category " + categoryDefinition.getName() + " not found during get or found more than once", 1,
+ categoriesNum);
+ }
+
+ public static void verifyCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest,
+ CategoryDefinition categoryDefinition) {
+
+ int categoriesNum = CategoryRestUtils.getMatchingCategoriesNum(getAllCategoryRest, categoryDefinition);
+ assertEquals("category " + categoryDefinition.getName() + " should't be found during get", 0, categoriesNum);
+ }
+
+ public static void verifySubCategoryExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
+ SubCategoryDefinition expectedSubCategoryDefinition) {
+
+ int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId,
+ expectedSubCategoryDefinition);
+ assertEquals(
+ "sub-category " + expectedSubCategoryDefinition.getName()
+ + " not found during get or found more than once for parentId " + parentCategoryId,
+ 1, subCategoriesNum);
+ }
+
+ public static void verifyGroupingExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
+ String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
+
+ int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId,
+ expectedGroupingDefinition);
+ assertEquals(
+ "sub-category " + expectedGroupingDefinition.getName()
+ + " not found during get or found more than once for parentId " + parentCategoryId,
+ 1, groupingNum);
+ }
+
+ public static void verifyGroupingNotExistInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
+ String subCategoryId, GroupingDefinition expectedGroupingDefinition) {
+
+ int groupingNum = CategoryRestUtils.getMatchingGroupingNum(getAllCategoryRest, parentCategoryId, subCategoryId,
+ expectedGroupingDefinition);
+ assertEquals(
+ "sub-category " + expectedGroupingDefinition.getName()
+ + " not found during get or found more than once for parentId " + parentCategoryId,
+ 0, groupingNum);
+ }
+
+ public static void verifySubCategoryNotExistsInGetResponse(RestResponse getAllCategoryRest, String parentCategoryId,
+ SubCategoryDefinition expectedSubCategoryDefinition) {
+
+ int subCategoriesNum = CategoryRestUtils.getMatchingSubCategoriesNum(getAllCategoryRest, parentCategoryId,
+ expectedSubCategoryDefinition);
+ assertEquals("sub-category " + expectedSubCategoryDefinition.getName()
+ + " should't be found during get for parentId " + parentCategoryId, 0, subCategoriesNum);
+ }
+
+ /// NEE Benny
+ public static void validateCreateGroupResponse(RestResponse createSubCategoryRest,
+ GroupingDefinition expectedGroupDefinition) throws Exception {
+
+ String response = createSubCategoryRest.getResponse();
+ JSONObject jobject = new JSONObject(response);
+ assertTrue(jobject.get("name").equals(expectedGroupDefinition.getName()));
+ assertTrue(jobject.get("normalizedName").equals(expectedGroupDefinition.getNormalizedName()));
+ // assertNotNull(jobject.get("normalizedName"));
+ assertNotNull(jobject.get("uniqueId"));
+ expectedGroupDefinition.setUniqueId(jobject.get("uniqueId").toString());
+
+ }
+
+ public static void validateCreateSubCategoryResponse(RestResponse createSubCategoryRest,
+ SubCategoryDefinition expectedSubCategoryDefinition) throws Exception {
+
+ String response = createSubCategoryRest.getResponse();
+ JSONObject jobject = new JSONObject(response);
+ assertTrue(jobject.get("name").equals(expectedSubCategoryDefinition.getName()));
+ assertNotNull(jobject.get("normalizedName"));
+ assertNotNull(jobject.get("uniqueId"));
+ }
+
+ public static void validateCreateCategoryResponse(RestResponse createCategoryRest,
+ CategoryDefinition expectedCategoryDefinition) throws Exception {
+ String response = createCategoryRest.getResponse();
+ JSONObject jobject = new JSONObject(response);
+ assertTrue(jobject.get("name").equals(expectedCategoryDefinition.getName()));
+ assertTrue(jobject.get("normalizedName").equals(expectedCategoryDefinition.getNormalizedName()));
+ assertNotNull(jobject.get("uniqueId"));
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
new file mode 100644
index 0000000000..29f9e84dd8
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/CsarValidationUtils.java
@@ -0,0 +1,274 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.parser.JSONParser;
+import org.openecomp.sdc.be.model.GroupDefinition;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.ci.tests.datatypes.GroupHeatMetaDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.PropertyHeatMetaDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.TypeHeatMetaDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition;
+import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaRequirementsNodeTemplatesDefinition;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils;
+import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
+import org.openecomp.sdc.common.util.ZipUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CsarValidationUtils {
+ private static Logger log = LoggerFactory.getLogger(CsarValidationUtils.class.getName());
+
+ public static String getCsarPayload(String csarName, String fileLocation) throws Exception {
+
+ RestResponseAsByteArray csar = ImportRestUtils.getCsar(csarName, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ assertTrue("Return response code different from 200", csar.getHttpStatusCode() == BaseRestUtils.STATUS_CODE_SUCCESS);
+ Map<String, byte[]> readZip = null;
+ byte[] data = csar.getResponse();
+ if (data != null && data.length > 0) {
+ readZip = ZipUtil.readZip(data);
+
+ }
+
+ byte[] artifactsBs = readZip.get(fileLocation);
+ String str = new String(artifactsBs, StandardCharsets.UTF_8);
+
+ return str;
+
+ }
+
+ public static List<TypeHeatMetaDefinition> getListTypeHeatMetaDefinition(String csarUUID) throws Exception {
+
+ String artifactHeatMetaLocation = "Artifacts/HEAT.meta";
+ JSONParser parser = new JSONParser();
+ String csarPayload = getCsarPayload(csarUUID, artifactHeatMetaLocation);
+ if (csarPayload != null) {
+ Object parse = parser.parse(csarPayload);
+ JSONObject jsonObject = (JSONObject) parse;
+ JSONObject jsonObjectImportStructure = (JSONObject) jsonObject.get("importStructure");
+ List<TypeHeatMetaDefinition> listHeatMetaDefenition = new ArrayList<TypeHeatMetaDefinition>();
+ listHeatMetaDefenition = getArtifactsByGroup(jsonObjectImportStructure, listHeatMetaDefenition);
+ return listHeatMetaDefenition;
+ }
+ return null;
+
+ }
+
+ protected static List<TypeHeatMetaDefinition> getArtifactsByGroup(JSONObject jsonObjectImportStructure, List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
+
+ @SuppressWarnings("unchecked")
+ Set<Object> typeSet = jsonObjectImportStructure.keySet();
+ for (Object type : typeSet) {
+ TypeHeatMetaDefinition heatMetaDefenition = new TypeHeatMetaDefinition();
+ log.debug(type.toString());
+ log.debug("{}", jsonObjectImportStructure.get(type));
+ JSONArray array = (JSONArray) jsonObjectImportStructure.get(type);
+ heatMetaDefenition.setTypeName((String) type);
+ List<GroupHeatMetaDefinition> groupHeatMetaDefinitions = new ArrayList<GroupHeatMetaDefinition>();
+ heatMetaDefenition.setGroupHeatMetaDefinition(fetchArtifactByGroup(array, groupHeatMetaDefinitions, true));
+ listHeatMetaDefenition.add(heatMetaDefenition);
+ }
+ return listHeatMetaDefenition;
+ }
+
+ protected static List<GroupHeatMetaDefinition> fetchArtifactByGroup(JSONArray array, List<GroupHeatMetaDefinition> listGroupHeatMetaDefinition, Boolean openNewGroup) {
+
+ GroupHeatMetaDefinition groupHeatMetaDefinition;
+
+ if (array != null) {
+ for (int i = 0; i < array.size(); i++) {
+ if (openNewGroup) {
+ groupHeatMetaDefinition = new GroupHeatMetaDefinition();
+ int groupNumber = listGroupHeatMetaDefinition.size() + 1;
+ log.debug("groupName={}", groupNumber);
+ groupHeatMetaDefinition.setGroup(groupNumber);
+ listGroupHeatMetaDefinition.add(groupHeatMetaDefinition);
+ PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition();
+ propertyHeatMetaDefinition.setName("isBase");
+ propertyHeatMetaDefinition.setValue(false);
+ groupHeatMetaDefinition.setPropertyHeatMetaDefinition(propertyHeatMetaDefinition);
+ }
+ groupHeatMetaDefinition = listGroupHeatMetaDefinition.get(listGroupHeatMetaDefinition.size() - 1);
+ JSONObject jsonObject = (JSONObject) array.get(i);
+ @SuppressWarnings("unchecked")
+ Set<Object> groupsKey = jsonObject.keySet();
+ for (Object groupKey : groupsKey) {
+ String groupKeyStr = (String) groupKey;
+ if (groupKeyStr.equals("isBase")) {
+ PropertyHeatMetaDefinition propertyHeatMetaDefinition = new PropertyHeatMetaDefinition();
+ propertyHeatMetaDefinition.setName(groupKeyStr);
+ propertyHeatMetaDefinition.setValue((boolean) jsonObject.get(groupKeyStr));
+ if (!groupHeatMetaDefinition.getPropertyHeatMetaDefinition().equals(propertyHeatMetaDefinition)) {
+ groupHeatMetaDefinition.getPropertyHeatMetaDefinition().setValue((boolean) jsonObject.get(groupKeyStr));
+ }
+ }
+ if (groupKeyStr.equals("fileName") || groupKeyStr.equals("env")) {
+ String artifactName = (String) jsonObject.get(groupKeyStr);
+ List<String> listArtifactNames = groupHeatMetaDefinition.getArtifactList();
+ listArtifactNames.add(artifactName);
+ groupHeatMetaDefinition.setArtifactList(listArtifactNames);
+ } else {
+ if (!groupKeyStr.equals("isBase")) {
+ fetchArtifactByGroup((JSONArray) jsonObject.get(groupKeyStr), listGroupHeatMetaDefinition, false);
+ }
+ }
+ }
+ }
+ }
+ return listGroupHeatMetaDefinition;
+ }
+
+ private static Integer getArtifactCount(List<TypeHeatMetaDefinition> listHeatMetaDefenition, Boolean isEnvIncluded) {
+ int count = 0;
+ List<String> uniqeArtifactList = new ArrayList<>();
+
+ for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) {
+ for (GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()) {
+ if (isEnvIncluded) {
+ count = count + groupHeatMetaDefinition.getArtifactList().size();
+ } else {
+ for (String fileName : groupHeatMetaDefinition.getArtifactList()) {
+ if (!fileName.contains(".env") && !uniqeArtifactList.contains(fileName)) {
+ uniqeArtifactList.add(fileName);
+ count = count + 1;
+ }
+ }
+ }
+ }
+ }
+ return count;
+ }
+
+ private static Integer getGroupCount(List<TypeHeatMetaDefinition> listHeatMetaDefenition) {
+ int count = 0;
+ for (TypeHeatMetaDefinition typeHeatMetaDefinition : listHeatMetaDefenition) {
+ count = count + typeHeatMetaDefinition.getGroupHeatMetaDefinition().size();
+ }
+ return count;
+ }
+
+ private static String groupNameBuilder(Resource resource) {
+ String separator = "::";
+ String module = "module-";
+ String groupName = resource.getSystemName() + separator + module;
+ return groupName;
+ }
+
+ public static void validateCsarVfArtifact(String csarUUID, Resource resource) throws Exception {
+
+ List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = getListTypeHeatMetaDefinition(csarUUID);
+ assertTrue("check group count, expected: " + getGroupCount(listTypeHeatMetaDefinition) + ", actual: " + resource.getGroups().size(), getGroupCount(listTypeHeatMetaDefinition) == resource.getGroups().size());
+ assertTrue("check artifact count, expected: " + getArtifactCount(listTypeHeatMetaDefinition, false) + ", actual: " + resource.getDeploymentArtifacts().size(),
+ getArtifactCount(listTypeHeatMetaDefinition, false) == resource.getDeploymentArtifacts().size());
+
+ }
+
+ public static void validateToscaDefinitonObjectVsResource(ToscaDefinition toscaDefinition, Resource resource) throws Exception {
+
+ assertTrue("check resource instance count, expected: " + getResourceInstanceCount(toscaDefinition) + ", actual: " + resource.getComponentInstances().size(),
+ getResourceInstanceCount(toscaDefinition) == resource.getComponentInstances().size());
+ assertTrue("check resource instance relation count, expected: " + getResourceInstanceRelationCount(toscaDefinition) + ", actual: " + resource.getComponentInstancesRelations().size(),
+ getResourceInstanceRelationCount(toscaDefinition) == resource.getComponentInstancesRelations().size());
+
+ }
+
+ public static Integer getResourceInstanceCount(ToscaDefinition toscaDefinition) {
+
+ return toscaDefinition.getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition().size();
+ }
+
+ public static Integer getResourceInstanceRelationCount(ToscaDefinition toscaDefinition) {
+ int count = 0;
+ List<ToscaNodeTemplatesTopologyTemplateDefinition> toscaNodeTemplatesTopologyTemplateDefinition = toscaDefinition.getToscaTopologyTemplate().getToscaNodeTemplatesTopologyTemplateDefinition();
+ for (int i = 0; i < toscaNodeTemplatesTopologyTemplateDefinition.size(); i++) {
+ List<ToscaRequirementsNodeTemplatesDefinition> requirements = toscaNodeTemplatesTopologyTemplateDefinition.get(i).getRequirements();
+ if (requirements != null) {
+ for (ToscaRequirementsNodeTemplatesDefinition requirement : requirements) {
+ if (requirement.getNode() != null) {
+ count = count + 1;
+ }
+ }
+ }
+ }
+ return count;
+ }
+
+ // not finished yet
+ private static void validateCsarVfgroup(String csarUUID, Resource resource) {
+
+ List<GroupDefinition> groups = resource.getGroups();
+ for (GroupDefinition groupDefinition : groups) {
+ List<String> artifacts = groupDefinition.getArtifacts();
+ assertTrue("group description is null", groupDefinition.getDescription() != null);
+ assertTrue("InvariantUUID is null", groupDefinition.getInvariantUUID() != null);
+ // groupDefinition.getMembers();
+ assertTrue("name format mismatch, expected: " + groupNameBuilder(resource) + "[0-9], actual: " + groupDefinition.getName(), groupDefinition.getName().contains(groupNameBuilder(resource)));
+ // groupDefinition.getProperties();
+ // groupDefinition.getPropertyValueCounter();
+ assertTrue(groupDefinition.getType().equals(getGroupType()));
+ }
+
+ String expectedCsarUUID = csarUUID;
+ // String expectedToscaResourceName = "org.openecomp.resource.vf." +
+ // WordUtils.capitalize(resourceDetails.getName().toLowerCase());
+ //
+ // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID,
+ // resource.getCsarUUID()),
+ // expectedCsarUUID.equals(resource.getCsarUUID()));
+ // assertTrue("toscaResourceName : " +
+ // buildAssertMessage(expectedToscaResourceName,
+ // resource.getToscaResourceName()),
+ // expectedToscaResourceName.equals(resource.getToscaResourceName()));
+ //
+ // RestResponse getResourceResponse =
+ // ResourceRestUtils.getResource(resource.getUniqueId());
+ // Resource getResource =
+ // ResponseParser.parseToObjectUsingMapper(getResourceResponse.getResponse(),
+ // Resource.class);
+ // assertTrue("csarUUID : " + buildAssertMessage(expectedCsarUUID,
+ // getResource.getCsarUUID()),
+ // expectedCsarUUID.equals(getResource.getCsarUUID()));
+ // assertTrue("toscaResourceName : " +
+ // buildAssertMessage(expectedToscaResourceName,
+ // getResource.getToscaResourceName()),
+ // expectedToscaResourceName.equals(getResource.getToscaResourceName()));
+
+ }
+
+ private static String getGroupType() {
+ return "org.openecomp.groups.VfModule";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
new file mode 100644
index 0000000000..ac5a05d7ca
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ErrorValidationUtils.java
@@ -0,0 +1,112 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+import org.openecomp.sdc.ci.tests.config.Config;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ExceptionEnumType;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.yaml.snakeyaml.Yaml;
+
+public class ErrorValidationUtils {
+
+ static Logger logger = LoggerFactory.getLogger(Utils.class.getName());
+
+ public static void checkBodyResponseOnError(String errorType, List<String> variables, String actualResponse)
+ throws FileNotFoundException, JSONException {
+
+ ErrorInfo errorInfo = parseErrorConfigYaml(errorType);
+ JSONObject expectedResponseBody = null;
+ if (errorInfo.getMessageId() != null) {
+ if (errorInfo.getMessageId().contains("SVC")) {
+ expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(),
+ variables, ExceptionEnumType.SERVICE_EXCEPTION.getValue());
+ } else {
+ expectedResponseBody = restExceptionFormatBuilder(errorInfo.getMessageId(), errorInfo.getMessage(),
+ variables, ExceptionEnumType.POLICY_EXCPTION.getValue());
+ }
+ }
+ actualResponse = actualResponse.replaceAll("\\n", "");
+ logger.debug("actualResponse - {}", actualResponse);
+ logger.debug("expectedResponseBody - {}", expectedResponseBody);
+ assertEquals(expectedResponseBody, new JSONObject(actualResponse));
+ }
+
+ public static JSONObject restExceptionFormatBuilder(String messageId, String text, List<String> variables,
+ String type) {
+
+ JSONObject simpleElements = new JSONObject();
+ JSONObject exceptionType = new JSONObject();
+ JSONObject requestError = new JSONObject();
+
+ try {
+ simpleElements.put("messageId", messageId);
+ simpleElements.put("text", text);
+ simpleElements.put("variables", variables);
+ exceptionType.put(type, simpleElements);
+ requestError.put("requestError", exceptionType);
+
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+
+ return requestError;
+
+ }
+
+ public static ErrorInfo parseErrorConfigYaml(String error) throws FileNotFoundException {
+ Yaml yaml = new Yaml();
+ ErrorInfo errInfo = null;
+ Config config = Utils.getConfig();
+ String errorConfigurationFile = config.getErrorConfigurationFile();
+ File file = new File(errorConfigurationFile);
+ // File file = new
+ // File("../catalog-be/src/main/resources/config/error-configuration.yaml");
+ InputStream inputStream = new FileInputStream(file);
+ Map<?, ?> map = (Map<?, ?>) yaml.load(inputStream);
+ // System.out.println(map.get("errors"));
+ @SuppressWarnings("unchecked")
+ Map<String, ErrorInfo> errorMap = (Map<String, ErrorInfo>) map.get("errors");
+ @SuppressWarnings("unchecked")
+ Map<String, Object> errorInfo = (Map<String, Object>) errorMap.get(error);
+
+ String message = (String) errorInfo.get("message");
+ String messageId = (String) errorInfo.get("messageId");
+ int code = (Integer) errorInfo.get("code");
+ errInfo = new ErrorInfo(code, message, messageId);
+
+ return errInfo;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
new file mode 100644
index 0000000000..ba5114c1bc
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ProductValidationUtils.java
@@ -0,0 +1,239 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.log4j.Logger;
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+import org.openecomp.sdc.be.model.Product;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.be.model.category.GroupingDefinition;
+import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest.ComponentOperationEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+
+public class ProductValidationUtils {
+
+ static Logger logger = Logger.getLogger(ProductValidationUtils.class.getName());
+
+ public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct) {
+ compareExpectedAndActualProducts(expectedProduct, actualProduct, null);
+ }
+
+ public static void compareExpectedAndActualProducts(Product expectedProduct, Product actualProduct,
+ ComponentOperationEnum operation) {
+
+ assertEquals(expectedProduct.getName(), actualProduct.getName());
+ assertEquals(expectedProduct.getFullName(), actualProduct.getFullName());
+ assertEquals(expectedProduct.getDescription(), actualProduct.getDescription());
+
+ List<String> expectedContacts = expectedProduct.getContacts();
+ List<String> actualContacts = actualProduct.getContacts();
+ assertTrue(
+ "Expected contacts:" + Arrays.toString(expectedContacts.toArray()) + ", actual contacts:"
+ + Arrays.toString(actualContacts.toArray()),
+ expectedContacts.size() == actualContacts.size() && expectedContacts.containsAll(actualContacts)
+ && actualContacts.containsAll(expectedContacts));
+
+ List<String> expectedTags = expectedProduct.getTags();
+ List<String> actualTags = actualProduct.getTags();
+ assertTrue(
+ "Expected tags:" + Arrays.toString(expectedTags.toArray()) + ", actual tags:"
+ + Arrays.toString(actualTags.toArray()),
+ expectedTags.size() == actualTags.size() && expectedTags.containsAll(actualTags)
+ && actualTags.containsAll(expectedTags));
+
+ assertEquals(expectedProduct.getLifecycleState(), actualProduct.getLifecycleState());
+ assertEquals(expectedProduct.getVersion(), actualProduct.getVersion());
+ assertEquals(expectedProduct.isHighestVersion(), actualProduct.isHighestVersion());
+ assertEquals(expectedProduct.getNormalizedName(), actualProduct.getNormalizedName());
+
+ compareCategories(expectedProduct, actualProduct);
+ assertEquals(expectedProduct.getLastUpdaterUserId(), actualProduct.getLastUpdaterUserId());
+ if (operation != null) {
+ assertEquals(expectedProduct.getCreatorUserId(), actualProduct.getCreatorUserId());
+ }
+
+ Long lastUpdateDate = actualProduct.getLastUpdateDate();
+ Long creationDate = actualProduct.getCreationDate();
+ Map<String, String> allVersions = actualProduct.getAllVersions();
+
+ if (operation != null) {
+ if (operation == ComponentOperationEnum.UPDATE_COMPONENT
+ || operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT
+ || operation == ComponentOperationEnum.CHANGE_STATE_CHECKIN
+ || operation == ComponentOperationEnum.CHANGE_STATE_UNDO_CHECKOUT) {
+ assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate,
+ lastUpdateDate > 0 && creationDate > 0 && lastUpdateDate > creationDate);
+ } else {
+ assertTrue("Last update date:" + lastUpdateDate + ", creation date: " + creationDate,
+ lastUpdateDate > 0 && lastUpdateDate.equals(creationDate));
+ }
+ }
+
+ // Check UUIDs
+ // If just created, no way to test the UUIDs themselves
+ // If updated, we expect the UUIDs of actual to match the expected
+ String uniqueId = actualProduct.getUniqueId();
+ if (operation == ComponentOperationEnum.CREATE_COMPONENT) {
+ UUID.fromString(uniqueId);
+ UUID.fromString(actualProduct.getUUID());
+ UUID.fromString(actualProduct.getInvariantUUID());
+ assertTrue(allVersions.size() == 1);
+ assertTrue(allVersions.get("0.1").equals(uniqueId));
+ } else {
+ if (operation == ComponentOperationEnum.CHANGE_STATE_CHECKOUT) {
+ assertFalse(expectedProduct.getUniqueId().equals(uniqueId));
+ // Assigning the updated uniqueId to expected so that it can be
+ // passed to further logic
+ expectedProduct.setUniqueId(uniqueId);
+ } else if (operation != null) {
+ assertTrue(expectedProduct.getUniqueId().equals(uniqueId));
+ }
+ assertEquals(expectedProduct.getUUID(), actualProduct.getUUID());
+ assertEquals(expectedProduct.getInvariantUUID(), actualProduct.getInvariantUUID());
+ }
+ }
+
+ private static void compareCategories(Product expectedProduct, Product actualProduct) {
+ List<CategoryDefinition> expectedCategories = expectedProduct.getCategories();
+ List<CategoryDefinition> actualCategories = actualProduct.getCategories();
+ if (expectedCategories != null && actualCategories != null) {
+ int expSize = expectedCategories.size();
+ int actSize = actualCategories.size();
+
+ assertTrue("Expected size:" + expSize + ", actual size:" + actSize, expSize == actSize);
+
+ for (CategoryDefinition actualDefinition : actualCategories) {
+ int lastIndexOfCat = expectedCategories.lastIndexOf(actualDefinition);
+ assertTrue("Actual category " + actualDefinition + " not found in expected.", lastIndexOfCat != -1);
+ CategoryDefinition expectedDefinition = expectedCategories.get(lastIndexOfCat);
+ List<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
+ List<SubCategoryDefinition> expectedSubcategories = expectedDefinition.getSubcategories();
+ for (SubCategoryDefinition actualSub : actualSubcategories) {
+ lastIndexOfCat = expectedSubcategories.lastIndexOf(actualSub);
+ assertTrue("Actual subcategory " + actualSub + " not found in expected.", lastIndexOfCat != -1);
+ SubCategoryDefinition expectedSub = expectedSubcategories.get(lastIndexOfCat);
+ List<GroupingDefinition> actualGroupings = actualSub.getGroupings();
+ List<GroupingDefinition> expectedGroupings = expectedSub.getGroupings();
+ for (GroupingDefinition actualGrouping : actualGroupings) {
+ lastIndexOfCat = expectedGroupings.lastIndexOf(actualGrouping);
+ assertTrue("Actual grouping " + actualSub + " not found in expected.", lastIndexOfCat != -1);
+ }
+ }
+ }
+
+ for (CategoryDefinition expectedDefinition : expectedCategories) {
+ int lastIndexOfCat = actualCategories.lastIndexOf(expectedDefinition);
+ assertTrue("Expected category " + expectedDefinition + " not found in actual.", lastIndexOfCat != -1);
+ CategoryDefinition actualDefinition = actualCategories.get(lastIndexOfCat);
+ List<SubCategoryDefinition> actualSubcategories = actualDefinition.getSubcategories();
+ List<SubCategoryDefinition> expectedSubcategories = expectedDefinition.getSubcategories();
+ for (SubCategoryDefinition expectedSub : expectedSubcategories) {
+ lastIndexOfCat = actualSubcategories.lastIndexOf(expectedSub);
+ assertTrue("Expected subcategory " + expectedSub + " not found in actual.", lastIndexOfCat != -1);
+ SubCategoryDefinition actualSub = actualSubcategories.get(lastIndexOfCat);
+ List<GroupingDefinition> actualGroupings = actualSub.getGroupings();
+ List<GroupingDefinition> expectedGroupings = expectedSub.getGroupings();
+ for (GroupingDefinition expectedGrouping : expectedGroupings) {
+ lastIndexOfCat = actualGroupings.lastIndexOf(expectedGrouping);
+ assertTrue("Expected grouping " + expectedGrouping + " not found in actual.",
+ lastIndexOfCat != -1);
+ }
+ }
+ }
+ }
+ }
+
+ public static void verifyProductsNotExistInUserFollowedPage(User user, Product... nonExpectedProducts)
+ throws Exception {
+ String component = "products";
+ Boolean isExist;
+ Product nonExpectedProduct;
+ RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId());
+ JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component);
+ if (followedProductes != null) { // if any product exist in followed
+ // page
+ for (int i = 0; i < nonExpectedProducts.length; i++) {
+ nonExpectedProduct = nonExpectedProducts[i];
+ isExist = false;
+ for (int k = 0; k < followedProductes.size(); k++) {
+ JSONObject jobject = (JSONObject) followedProductes.get(k);
+ if (jobject.get("uuid").toString().equals(nonExpectedProduct.getUUID())) {
+ isExist = true;
+ k = followedProductes.size();
+ }
+ }
+ assertFalse(isExist);
+ }
+ }
+
+ }
+
+ public static void checkUserFollowedPage(User user, Product... expectedProducts) throws Exception {
+ String component = "products";
+ Boolean isExist;
+ Product expectedProduct;
+ RestResponse getFollowedPage = ProductRestUtils.getFollowed(user.getUserId());
+ JSONArray followedProductes = getListArrayFromRestResponse(getFollowedPage, component);
+ assertTrue("check if any followedProductes received ", followedProductes != null);
+ assertTrue("check if any expectedProducts and followedProductes are the same size",
+ expectedProducts.length == followedProductes.size());
+ for (int i = 0; i < expectedProducts.length; i++) {
+ expectedProduct = expectedProducts[i];
+ isExist = false;
+ for (int k = 0; k < followedProductes.size(); k++) {
+ JSONObject jobject = (JSONObject) followedProductes.get(k);
+ // if(jobject.get("uuid").toString().equals(expectedProduct.getUUID()))
+ if (jobject.get("uniqueId").toString().equals(expectedProduct.getUniqueId())) {
+
+ String productString = jobject.toJSONString();
+ Product actualProduct = ResponseParser.parseToObjectUsingMapper(productString, Product.class);
+ ProductValidationUtils.compareExpectedAndActualProducts(expectedProduct, actualProduct, null);
+ isExist = true;
+ k = followedProductes.size();
+ }
+ }
+ assertTrue(isExist);
+ }
+ }
+
+ private static JSONArray getListArrayFromRestResponse(RestResponse restResponse, String lst) {
+ String json = restResponse.getResponse();
+ JSONObject jsonResp = (JSONObject) JSONValue.parse(json);
+ JSONArray resources = (JSONArray) jsonResp.get(lst);
+ return resources;
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
new file mode 100644
index 0000000000..a3440df8ad
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ResourceValidationUtils.java
@@ -0,0 +1,354 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.openecomp.sdc.be.model.ArtifactDefinition;
+import org.openecomp.sdc.be.model.InterfaceDefinition;
+import org.openecomp.sdc.be.model.Operation;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.category.CategoryDefinition;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceRespJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.enums.RespJsonKeysEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+
+import com.google.gson.Gson;
+
+public class ResourceValidationUtils {
+
+ public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails,
+ ResourceRespJavaObject resourceRespJavaObject) {
+
+ String expected;
+
+ expected = resourceDetails.getDescription();
+ assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription());
+
+ expected = resourceDetails.getVendorName();
+ assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName());
+
+ expected = resourceDetails.getVendorRelease();
+ assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease());
+
+ expected = resourceDetails.getContactId();
+ assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId());
+
+ }
+
+ public static void validateResourceReqVsResp(ResourceReqDetails resourceDetails, Resource resourceRespJavaObject) {
+
+ String expected;
+
+ expected = resourceDetails.getDescription();
+ assertEquals("resource description - ", expected, resourceRespJavaObject.getDescription());
+
+ expected = resourceDetails.getVendorName();
+ assertEquals("resource vendorName - ", expected, resourceRespJavaObject.getVendorName());
+
+ expected = resourceDetails.getVendorRelease();
+ assertEquals("resource vendorReleaseName - ", expected, resourceRespJavaObject.getVendorRelease());
+
+ expected = resourceDetails.getContactId();
+ assertEquals("resource contactId - ", expected, resourceRespJavaObject.getContactId());
+
+ // Validating deduplication of tags
+ List<String> expectedTags = resourceDetails.getTags();
+ if (expectedTags != null) {
+ Set<String> hs = new LinkedHashSet<>(expectedTags);
+ expectedTags.clear();
+ expectedTags.addAll(hs);
+ List<String> receivedTags = resourceRespJavaObject.getTags();
+ assertEquals("resource tags - ", expectedTags, receivedTags);
+ }
+
+ }
+
+ public static void validateModelObjects(Resource expected, Resource actual) throws Exception {
+
+ compareElements(expected.getUniqueId(), actual.getUniqueId());
+ compareElements(expected.getName(), actual.getName());
+ compareElements(expected.getVersion(), actual.getVersion());
+ compareElements(expected.getCreatorUserId(), actual.getCreatorUserId());
+ compareElements(expected.getCreatorFullName(), actual.getCreatorFullName());
+ compareElements(expected.getLastUpdaterUserId(), actual.getLastUpdaterUserId());
+ compareElements(expected.getLastUpdaterFullName(), actual.getLastUpdaterFullName());
+ compareElements(expected.getCreatorFullName(), actual.getCreatorFullName());
+ compareElements(expected.getCreationDate(), actual.getCreationDate());
+ compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate());
+ compareElements(expected.getDescription(), actual.getDescription());
+ compareElements(expected.getIcon(), actual.getIcon());
+ compareElements(expected.getLastUpdateDate(), actual.getLastUpdateDate());
+ // TODO compare tags
+ compareElements(expected.getCategories(), actual.getCategories());
+ compareElements(expected.getLifecycleState(), actual.getLifecycleState());
+ compareElements(expected.getVendorName(), actual.getVendorName());
+ compareElements(expected.getVendorRelease(), actual.getVendorRelease());
+ compareElements(expected.getContactId(), actual.getContactId());
+ compareElements(expected.getUUID(), actual.getUUID());
+ compareElements(expected.getVersion(), actual.getVersion());
+
+ }
+
+ public static void validateResp(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject)
+ throws Exception {
+
+ Gson gson = new Gson();
+ String response = restResponse.getResponse();
+
+ validateResp(response, resourceRespJavaObject, gson);
+
+ }
+
+ public static void validateResp(String response, ResourceRespJavaObject resourceRespJavaObject, Gson gson) {
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map = (Map<String, Object>) gson.fromJson(response, map.getClass());
+
+ // De-duplicating the tags list for comparison
+ List<String> tags = resourceRespJavaObject.getTags();
+ if (tags != null) {
+ Set<String> hs = new LinkedHashSet<>(tags);
+ tags = new ArrayList<String>(hs);
+ resourceRespJavaObject.setTags(tags);
+ tags = new ArrayList<String>(hs);
+ resourceRespJavaObject.setTags(tags);
+ }
+
+ validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName());
+ validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(),
+ resourceRespJavaObject.getDescription());
+ // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(),
+ // resourceRespJavaObject.getCategories());
+ validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName());
+ validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(),
+ resourceRespJavaObject.getVendorRelease());
+ validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId());
+ validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon());
+ validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(),
+ Boolean.valueOf(resourceRespJavaObject.getAbstractt()));
+ validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(),
+ Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion()));
+ validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId());
+ validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion());
+ validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(),
+ resourceRespJavaObject.getLifecycleState());
+ validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), tags);
+ validateField(map, RespJsonKeysEnum.CREATOR_USER_ID.getRespJsonKeyName(),
+ resourceRespJavaObject.getCreatorUserId());
+ validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
+ resourceRespJavaObject.getCreatorFullName());
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(),
+ resourceRespJavaObject.getLastUpdaterUserId());
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
+ resourceRespJavaObject.getLastUpdaterFullName());
+ validateField(map, RespJsonKeysEnum.COST.getRespJsonKeyName(), resourceRespJavaObject.getCost());
+ validateField(map, RespJsonKeysEnum.LICENSE_TYPE.getRespJsonKeyName(), resourceRespJavaObject.getLicenseType());
+ validateField(map, RespJsonKeysEnum.RESOURCE_TYPE.getRespJsonKeyName(),
+ resourceRespJavaObject.getResourceType().toString());
+ if (resourceRespJavaObject.getResourceType().equals("VF")) {
+ validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), null);
+ } else {
+ validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(),
+ resourceRespJavaObject.getDerivedFrom());
+ }
+
+ validateCategories(resourceRespJavaObject, map);
+
+ String uuid = ResponseParser.getValueFromJsonResponse(response, RespJsonKeysEnum.UUID.getRespJsonKeyName());
+ assertTrue("UUID is empty", uuid != null && !uuid.isEmpty());
+ }
+
+ private static void validateCategories(ResourceRespJavaObject resourceRespJavaObject, Map<String, Object> map) {
+ assertTrue(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName() + " is missing",
+ map.containsKey(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName()));
+ Object foundValue = map.get(RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName());
+ List<Map<String, Object>> foundList = (List<Map<String, Object>>) foundValue;
+ List<CategoryDefinition> excpectedList = resourceRespJavaObject.getCategories();
+
+ assertTrue(foundList.size() == excpectedList.size());
+ for (int i = 0; i < foundList.size(); i++) {
+ CategoryDefinition expCat = excpectedList.get(i);
+ Map<String, Object> foun = foundList.get(i);
+ assertTrue("expected " + expCat.getName() + " not equal to actual " + foundValue,
+ foun.get("name").equals(expCat.getName()));
+ }
+ }
+
+ public static void validateField(Map<String, Object> map, String jsonField, Object expectedValue) {
+ if (expectedValue == null) {
+ assertTrue(jsonField + " is expected to be null", !map.containsKey(jsonField));
+ } else {
+ assertTrue(jsonField + " is missing", map.containsKey(jsonField));
+ Object foundValue = map.get(jsonField);
+ compareElements(expectedValue, foundValue);
+ }
+ }
+
+ public static void compareElements(Object expectedValue, Object foundValue) {
+ if (expectedValue instanceof String) {
+ assertTrue(foundValue instanceof String);
+ assertTrue("expected " + expectedValue + " not equal to actual " + foundValue,
+ foundValue.equals(expectedValue));
+ }
+ else if (expectedValue instanceof Boolean) {
+ assertTrue(foundValue instanceof Boolean);
+ assertTrue(foundValue == expectedValue);
+ } else if (expectedValue instanceof Map) {
+ assertTrue(foundValue instanceof Map);
+ Map<String, Object> foundMap = (Map<String, Object>) foundValue;
+ Map<String, Object> excpectedMap = (Map<String, Object>) expectedValue;
+ assertTrue(foundMap.size() == excpectedMap.size());
+ Iterator<String> foundkeyItr = foundMap.keySet().iterator();
+ while (foundkeyItr.hasNext()) {
+ String foundKey = foundkeyItr.next();
+ assertTrue(excpectedMap.containsKey(foundKey));
+ compareElements(excpectedMap.get(foundKey), foundMap.get(foundKey));
+ }
+
+ } else if (expectedValue instanceof List) {
+ assertTrue(foundValue instanceof List);
+ List<Object> foundList = (List<Object>) foundValue;
+ List<Object> excpectedList = (List<Object>) expectedValue;
+ assertTrue(foundList.size() == excpectedList.size());
+ for (int i = 0; i < foundList.size(); i++) {
+ compareElements(excpectedList.get(i), foundList.get(i));
+ }
+
+ } else {
+ assertTrue(foundValue.equals(expectedValue));
+ }
+ }
+
+ public static boolean validateUuidAfterChangingStatus(String oldUuid, String newUuid) {
+ return oldUuid.equals(newUuid);
+
+ }
+
+ public static void validateRespArt(RestResponse restResponse, ResourceRespJavaObject resourceRespJavaObject,
+ String interfaze) throws Exception {
+
+ Gson gson = new Gson();
+ String response = restResponse.getResponse();
+
+ Map<String, Object> map = new HashMap<String, Object>();
+ map = (Map<String, Object>) gson.fromJson(response, map.getClass());
+
+ Resource resource = gson.fromJson(response, Resource.class);
+
+ Map<String, ArtifactDefinition> artifacts = resource.getArtifacts();
+ Map<String, InterfaceDefinition> interfaces = null;
+
+ if (interfaze != null) {
+ interfaces = resource.getInterfaces();
+ Map<String, Operation> operation = interfaces.get(interfaze).getOperations();
+ // operation.get("configure").getUniqueId();
+ }
+
+ validateField(map, RespJsonKeysEnum.RESOURCE_NAME.getRespJsonKeyName(), resourceRespJavaObject.getName());
+ validateField(map, RespJsonKeysEnum.RESOURCE_DESC.getRespJsonKeyName(),
+ resourceRespJavaObject.getDescription());
+ // validateField(map, RespJsonKeysEnum.CATEGORIES.getRespJsonKeyName(),
+ // resourceRespJavaObject.getCategories());
+ validateField(map, RespJsonKeysEnum.DERIVED_FROM.getRespJsonKeyName(), resourceRespJavaObject.getDerivedFrom());
+ validateField(map, RespJsonKeysEnum.VENDOR_NAME.getRespJsonKeyName(), resourceRespJavaObject.getVendorName());
+ validateField(map, RespJsonKeysEnum.VENDOR_RELEASE.getRespJsonKeyName(),
+ resourceRespJavaObject.getVendorRelease());
+ validateField(map, RespJsonKeysEnum.CONTACT_ID.getRespJsonKeyName(), resourceRespJavaObject.getContactId());
+ validateField(map, RespJsonKeysEnum.ICON.getRespJsonKeyName(), resourceRespJavaObject.getIcon());
+ validateField(map, RespJsonKeysEnum.IS_ABSTRACT.getRespJsonKeyName(),
+ Boolean.valueOf(resourceRespJavaObject.getAbstractt()));
+ validateField(map, RespJsonKeysEnum.HIGHEST_VERSION.getRespJsonKeyName(),
+ Boolean.valueOf(resourceRespJavaObject.getIsHighestVersion()));
+ validateField(map, RespJsonKeysEnum.UNIQUE_ID.getRespJsonKeyName(), resourceRespJavaObject.getUniqueId());
+ validateField(map, RespJsonKeysEnum.RESOURCE_VERSION.getRespJsonKeyName(), resourceRespJavaObject.getVersion());
+ validateField(map, RespJsonKeysEnum.LIFE_CYCLE_STATE.getRespJsonKeyName(),
+ resourceRespJavaObject.getLifecycleState());
+ validateField(map, RespJsonKeysEnum.TAGS.getRespJsonKeyName(), resourceRespJavaObject.getTags());
+ validateField(map, RespJsonKeysEnum.CREATOR_USER_ID.getRespJsonKeyName(),
+ resourceRespJavaObject.getCreatorUserId());
+ validateField(map, RespJsonKeysEnum.CREATOR_FULL_NAME.getRespJsonKeyName(),
+ resourceRespJavaObject.getCreatorFullName());
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_ATT_UID.getRespJsonKeyName(),
+ resourceRespJavaObject.getLastUpdaterUserId());
+ validateField(map, RespJsonKeysEnum.LAST_UPDATER_FULL_NAME.getRespJsonKeyName(),
+ resourceRespJavaObject.getLastUpdaterFullName());
+
+ // validate number of artifacts
+ if (resourceRespJavaObject.getArtifacts() != null) {
+
+ // assertEquals("check number of artifacts",
+ // resourceRespJavaObject.getArtifacts().size(), artifacts.size());
+ int iterNum = -1;
+ ArrayList<String> myArtifacats = new ArrayList<String>();
+ Iterator it = artifacts.entrySet().iterator();
+ while (it.hasNext()) {
+ iterNum++;
+ Map.Entry pair = (Map.Entry) it.next();
+ // System.out.println(pair.getKey() + " = " + pair.getValue());
+ ArtifactDefinition myArtifact = artifacts.get(pair.getKey());
+ myArtifacats.add(myArtifact.getEsId());
+ it.remove(); // avoids a ConcurrentModificationException
+ }
+ // assertTrue("check service contains
+ // artifacts",myArtifacats.containsAll(resourceRespJavaObject.getArtifacts()));
+ }
+
+ // validate number of interfaces:
+
+ if (interfaze != null) {
+ assertEquals("check number of interfaces", resourceRespJavaObject.getInterfaces().size(),
+ interfaces.size());
+ }
+
+ }
+
+ public static boolean validateResourceIsAbstartct(List<Resource> resourceList, Boolean bool) {
+ if (resourceList != null && resourceList.size() > 0) {
+ for (Resource resource : resourceList) {
+ if (resource.isAbstract().equals(bool))
+ continue;
+ else
+ return false;
+ }
+ } else
+ return false;
+ return true;
+ }
+
+ public static void validateResourceVersion(Resource resource, String expectedVersion) {
+ if (resource != null && !resource.equals("")) {
+ assertTrue("expected resource version is: " + expectedVersion + ", but actual is: " + resource.getVersion(),
+ resource.getVersion().equals(expectedVersion));
+ }
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
new file mode 100644
index 0000000000..19bd7b9488
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/ServiceValidationUtils.java
@@ -0,0 +1,130 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.LifecycleStateEnum;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedResourceAuditJavaObject;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+
+public class ServiceValidationUtils {
+
+ public static void validateServiceResponseMetaData(ServiceReqDetails serviceDetails, Service service, User user,
+ LifecycleStateEnum lifecycleState) {
+ validateServiceResponseMetaData(serviceDetails, service, user, user, lifecycleState);
+ }
+
+ public static void validateServiceResponseMetaData(ServiceReqDetails expectedService, Service service,
+ User creatorUser, User updaterUser, LifecycleStateEnum lifeCycleState) {
+ List<String> expectedTags = expectedService.getTags();
+ expectedTags.add(expectedService.getName());
+ List<String> receivedTags = service.getTags();
+ if (expectedTags != null) {
+ Set<String> hs = new LinkedHashSet<>(expectedTags);
+ expectedTags.clear();
+ expectedTags.addAll(hs);
+ }
+
+ assertEquals("Check service name on response after create service", expectedService.getName(),
+ service.getName());
+ // check size of list
+ assertEquals("Check only 1 category returned on response after create service", 1,
+ expectedService.getCategories().size());
+ assertEquals("Check service name on response after create service", expectedService.getName(),
+ service.getName());
+ assertEquals("Check categories on response after create service",
+ expectedService.getCategories().get(0).getName(), service.getCategories().get(0).getName());
+ assertEquals("Check tag list on response after create service", expectedTags, receivedTags);
+ assertEquals("Check description on response after create service", expectedService.getDescription(),
+ service.getDescription());
+ // assertEquals("Check vendor name on response after create service",
+ // expectedService.getVendorName(), service.getVendorName());
+ // assertEquals("Check vendor release on response after create service",
+ // expectedService.getVendorRelease(), service.getVendorRelease());
+ assertEquals("Check attContant name on response after create service",
+ expectedService.getContactId().toLowerCase(), service.getContactId());
+ assertEquals("Check icon name on response after create service", expectedService.getIcon(), service.getIcon());
+ assertEquals("Check LastUpdaterUserId after create service", updaterUser.getUserId(), service.getLastUpdaterUserId());
+ assertEquals("Check LastUpdaterName after create service",
+ updaterUser.getFirstName() + " " + updaterUser.getLastName(), service.getLastUpdaterFullName());
+ assertEquals("Check CreatorUserId after create service", creatorUser.getUserId(), service.getCreatorUserId());
+ assertEquals("Check CreatorName after create service",
+ creatorUser.getFirstName() + " " + creatorUser.getLastName(), service.getCreatorFullName());
+ assertEquals("Check version after create service", expectedService.getVersion(), service.getVersion());
+ // assertEquals("Check UniqueId after create service", SERVICE_PREFIX +
+ // serviceDetails.getServiceName().toLowerCase()+"." +
+ // serviceBaseVersion, service.getUniqueId());
+ assertFalse("Check uuid after create service", service.getUUID().isEmpty());
+
+ // assertTrue("check creation date after create service",
+ // service.getCreationDate() != null);
+ // assertTrue("check update date after create service",
+ // service.getLastUpdateDate() != null);
+
+ if (lifeCycleState != null)
+ assertEquals("Check LifecycleState after create service", lifeCycleState, service.getLifecycleState());
+ else
+ assertEquals("Check LifecycleState after create service", LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT,
+ service.getLifecycleState());
+ }
+
+ public static ExpectedResourceAuditJavaObject constructFieldsForAuditValidation(ServiceReqDetails serviceReqDetails,
+ String serviceVersion, User sdncUserDetails) {
+
+ ExpectedResourceAuditJavaObject expectedResourceAuditJavaObject = new ExpectedResourceAuditJavaObject();
+
+ expectedResourceAuditJavaObject.setAction("Create");
+ expectedResourceAuditJavaObject.setModifierUid(sdncUserDetails.getUserId());
+ String userFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
+ expectedResourceAuditJavaObject.setModifierName(userFirstLastName);
+ expectedResourceAuditJavaObject.setStatus("200");
+ expectedResourceAuditJavaObject.setDesc("OK");
+ expectedResourceAuditJavaObject.setResourceName(serviceReqDetails.getName());
+ expectedResourceAuditJavaObject.setResourceType("Service");
+ expectedResourceAuditJavaObject.setPrevVersion(String.valueOf(Float.parseFloat(serviceVersion) - 0.1f));
+ expectedResourceAuditJavaObject.setCurrVersion(serviceVersion);
+ expectedResourceAuditJavaObject.setPrevState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setCurrState((LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT).toString());
+ expectedResourceAuditJavaObject.setComment(null);
+
+ return expectedResourceAuditJavaObject;
+
+ }
+
+ public static void validateDistrubtionStatusValue(RestResponse response,
+ DistributionStatusEnum expectedDistributionValue) throws Exception {
+ String actualDistributionValue = ResponseParser.getValueFromJsonResponse(response.getResponse(),
+ "distributionStatus");
+ assertEquals(expectedDistributionValue.name(), actualDistributionValue);
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
new file mode 100644
index 0000000000..a75434edcf
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/utils/validation/UserValidationUtils.java
@@ -0,0 +1,279 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.utils.validation;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertTrue;
+
+import java.util.List;
+
+import org.apache.commons.lang.StringUtils;
+import org.openecomp.sdc.be.dao.utils.UserStatusEnum;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.users.AddUserAuditMessageInfo;
+import org.openecomp.sdc.ci.tests.users.UserAuditJavaObject;
+import org.openecomp.sdc.ci.tests.utils.DbUtils;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+
+public class UserValidationUtils {
+ public static void compareExpectedAndActualUsers(User expected, User actual) {
+
+ String actualFirstName = actual.getFirstName();
+ String expectedFirstName = expected.getFirstName();
+ assertEquals("check user first name - ", expectedFirstName, actualFirstName);
+
+ String actualLastName = actual.getLastName();
+ String expectedLastName = expected.getLastName();
+ assertEquals("check user last name - ", expectedLastName, actualLastName);
+
+ String actualUserId = actual.getUserId();
+ String expectedUserId = expected.getUserId();
+ assertEquals("check user userId - ", expectedUserId, actualUserId);
+
+ String actualEmail = actual.getEmail();
+ String expectedEmail = expected.getEmail();
+ assertEquals("check user email - ", expectedEmail, actualEmail);
+
+ Long actualLastLoginTime = actual.getLastLoginTime();
+ Long expectedLastLoginTime = expected.getLastLoginTime();
+ assertEquals("check user last login time - ", expectedLastLoginTime, actualLastLoginTime);
+
+ String actualRole = actual.getRole();
+ if (expected.getRole() == null) {
+ String expectedRole = UserRoleEnum.DESIGNER.name();
+ assertEquals("check user role - ", expectedRole, actualRole);
+ } else {
+ String expectedRole = expected.getRole();
+ assertEquals("check user role - ", expectedRole, actualRole);
+ }
+
+ UserStatusEnum actualStatus = expected.getStatus();
+ UserStatusEnum expectedStatus = expected.getStatus();
+ assertEquals("check user status - ", expectedStatus, actualStatus);
+ }
+
+ public static void validateDeleteUserAuditMessage(User sdncUserDetails, User sdncModifierDetails,
+ String responseCode, String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) {
+ String action = "DeleteUser";
+ validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage,
+ addUserAuditMessageInfo, action);
+
+ }
+
+ private static void validateUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode,
+ String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo, String expectedAction) {
+
+ assertEquals("check audit action - ", expectedAction, addUserAuditMessageInfo.getACTION());
+
+ // String expectedModifierFirstLastName =
+ // sdncModifierDetails.getFirstName() + " " +
+ // sdncModifierDetails.getLastName();
+ // assertEquals("check audit modifier name - ",
+ // expectedModifierFirstLastName,
+ // addUserAuditMessageInfo.getMODIFIER_NAME());
+ String fullName = sdncModifierDetails.getFullName();
+ if (sdncModifierDetails.getFullName().equals(" ")) {
+ fullName = "";
+ }
+ String expectedModifierId = fullName + "(" + sdncModifierDetails.getUserId() + ")";
+ assertEquals("check audit modifier uid - ", expectedModifierId, addUserAuditMessageInfo.getMODIFIER());
+
+ String expectedUserFirstLastName = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
+ if (expectedUserFirstLastName.equals("null null")) {
+ expectedUserFirstLastName = "";
+ }
+
+ String email = (sdncUserDetails.getEmail() == null) ? "" : sdncUserDetails.getEmail();
+ String role = (sdncUserDetails.getRole() == null) ? "DESIGNER" : sdncUserDetails.getRole();
+
+ String formatedUser = String.format("%s,%s,%s,%s", sdncUserDetails.getUserId(), expectedUserFirstLastName,
+ email, role);
+
+ //
+ // String expectedUserFirstLastName = sdncUserDetails.getFirstName() + "
+ // " + sdncUserDetails.getLastName();
+ // if (expectedUserFirstLastName.equals("null null")) {
+ // expectedUserFirstLastName = "";
+ // }
+ //
+ // String expectedUserFirstLastName = "";
+ // expectedUserFirstLastName += sdncUserDetails.getFirstName() == null ?
+ // "" : sdncUserDetails.getFirstName();
+ // String lastName = sdncUserDetails.getLastName() == null ? "" :
+ // sdncUserDetails.getLastName();
+ // if (expectedUserFirstLastName.isEmpty()) {
+ // expectedUserFirstLastName = lastName;
+ // } else {
+ // expectedUserFirstLastName += " " + lastName;
+ // }
+
+ assertEquals("check audit user name - ", formatedUser, addUserAuditMessageInfo.getUSER());
+
+ // String expectedUserUid = sdncUserDetails.getUserId();
+ // assertEquals("check audit user uid - ", expectedUserUid,
+ // addUserAuditMessageInfo.getUSER_UID());
+ //
+ // String expectedUserEmail = sdncUserDetails.getEmail() == null ? "" :
+ // sdncUserDetails.getEmail();
+ // //TODO: esofer check with Andrey. Audit return "" but in user we have
+ // null
+ // assertEquals("check audit user email - ", expectedUserEmail,
+ // addUserAuditMessageInfo.getUSER_EMAIL());
+ //
+ // String expectedUserRole = sdncUserDetails.getRole();
+ // if (expectedUserRole ==null){
+ // expectedUserRole = "DESIGNER";
+ // assertEquals("check audit user role - ", expectedUserRole,
+ // addUserAuditMessageInfo.getUSER_ROLE());
+ // }else{
+ // assertEquals("check audit user role - ", expectedUserRole,
+ // addUserAuditMessageInfo.getUSER_ROLE());
+ // }
+
+ String expectedUserResponseCode = responseCode;
+ assertEquals("check audit user response code - ", expectedUserResponseCode,
+ addUserAuditMessageInfo.getSTATUS());
+
+ String expectedUserResponseMessage = responseMessage;
+ assertEquals("check audit user response message - ", expectedUserResponseMessage,
+ addUserAuditMessageInfo.getDESC());
+
+ }
+
+ public static void validateDataAgainstAuditDB_access(User sdncUserDetails, UserAuditJavaObject auditJavaObject,
+ RestResponse restResponse, ErrorInfo errorInfo, List<String> variables) {
+
+ validateAuditDataAgainstAuditDbInAccess(sdncUserDetails, auditJavaObject, restResponse, errorInfo, variables);
+
+ }
+
+ public static void validateAuditDataAgainstAuditDbInAccess(User sdncUserDetails,
+ UserAuditJavaObject auditJavaObject, RestResponse restResponse, ErrorInfo errorInfo,
+ List<String> variables) {
+
+ String expected;
+
+ expected = "Access";
+ assertEquals("ACTION- ", expected, auditJavaObject.getACTION());
+
+ if (sdncUserDetails.getFirstName() != StringUtils.EMPTY && sdncUserDetails.getLastName() != StringUtils.EMPTY) {
+ expected = sdncUserDetails.getFirstName() + " " + sdncUserDetails.getLastName();
+ } else {
+ expected = StringUtils.EMPTY;
+ }
+ String formatedUser = String.format("%s(%s)", expected, sdncUserDetails.getUserId());
+ assertTrue(
+ "check audit user: expected start with - " + formatedUser + " ,actual - " + auditJavaObject.getUSER(),
+ auditJavaObject.getUSER().startsWith(formatedUser));
+
+ expected = restResponse.getErrorCode().toString();
+ assertEquals("check audit user status code - ", expected, auditJavaObject.getSTATUS());
+
+ if (restResponse.getErrorCode() == 200 || restResponse.getErrorCode() == 201) {
+ expected = errorInfo.getMessage();
+ } else {
+ expected = AuditValidationUtils.buildAuditDescription(errorInfo, variables);
+ }
+
+ assertEquals("check audit user desc - ", expected, auditJavaObject.getDESC());
+
+ // expected = sdncUserDetails.getUserId();
+ // assertEquals(expected, auditJavaObject.getUSER());
+
+ }
+
+ public static void validateUserDetailsOnResponse(User sdncUserDetails, String userDetailsOnResponse) {
+
+ String actualFirstName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "firstName");
+ String expectedFirstName = sdncUserDetails.getFirstName();
+ assertEquals("check user first name - ", expectedFirstName, actualFirstName);
+
+ String actualLastName = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "lastName");
+ String expectedLastName = sdncUserDetails.getLastName();
+ assertEquals("check user last name - ", expectedLastName, actualLastName);
+
+ String actualUserId = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "userId");
+ String expectedUserId = sdncUserDetails.getUserId();
+ assertEquals("check user userId - ", expectedUserId, actualUserId);
+
+ String actualEmail = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "email");
+ String expectedEmail = sdncUserDetails.getEmail();
+ assertEquals("check user email - ", expectedEmail, actualEmail);
+
+ String actualRole = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "role");
+ if (sdncUserDetails.getRole() == null) {
+ String expectedRole = UserRoleEnum.DESIGNER.name();
+ assertEquals("check user role - ", expectedRole, actualRole);
+ } else {
+ String expectedRole = sdncUserDetails.getRole();
+ assertEquals("check user role - ", expectedRole, actualRole);
+ }
+
+ String actualStatus = Utils.getJsonObjectValueByKey(userDetailsOnResponse, "status");
+ String expectedStatus = sdncUserDetails.getStatus().name();
+ assertEquals("check user status - ", expectedStatus, actualStatus);
+
+ }
+
+ public static AddUserAuditMessageInfo getAddUserAuditMessage(String action) throws Exception {
+
+ Gson gson = new Gson();
+ String index = "auditingevents*";
+ String type = "useradminevent";
+ String pattern = "/_search?q=ACTION:\"" + action + "\"";
+ String auditingMessage = DbUtils.retrieveAuditMessagesByPattern(pattern);
+ // String auditingMessage = retrieveAuditMessageByIndexType(index, type,
+ // pattern);
+ JsonElement jElement = new JsonParser().parse(auditingMessage);
+ JsonObject jObject = jElement.getAsJsonObject();
+ JsonObject hitsObject = (JsonObject) jObject.get("hits");
+ JsonArray hitsArray = (JsonArray) hitsObject.get("hits");
+ // for (int i = 0; i < hitsArray.size();){
+ if (hitsArray != null) {
+ JsonObject jHitObject = (JsonObject) hitsArray.get(0);
+ JsonObject jSourceObject = (JsonObject) jHitObject.get("_source");
+ AddUserAuditMessageInfo addUserAuditMessageInfo = new AddUserAuditMessageInfo();
+ addUserAuditMessageInfo = gson.fromJson(jSourceObject, AddUserAuditMessageInfo.class);
+ return addUserAuditMessageInfo;
+ }
+ return null;
+
+ }
+
+ public static void validateAddUserAuditMessage(User sdncUserDetails, User sdncModifierDetails, String responseCode,
+ String responseMessage, AddUserAuditMessageInfo addUserAuditMessageInfo) {
+
+ String action = "AddUser";
+ validateUserAuditMessage(sdncUserDetails, sdncModifierDetails, responseCode, responseMessage,
+ addUserAuditMessageInfo, action);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java
new file mode 100644
index 0000000000..0c19627bda
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/ci/tests/webSealAccess/NeoJavaObject.java
@@ -0,0 +1,111 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.ci.tests.webSealAccess;
+
+public class NeoJavaObject {
+
+ String userId;
+ String firstName;
+ String lastName;
+ String email;
+ String role;
+ String label;
+ String elementType;
+
+ public NeoJavaObject(String userId, String firstName, String lastName, String email, String role, String label,
+ String elementType) {
+ super();
+ this.userId = userId;
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.email = email;
+ this.role = role;
+ this.label = label;
+ this.elementType = elementType;
+ }
+
+ public NeoJavaObject() {
+ super();
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getElementType() {
+ return elementType;
+ }
+
+ public void setElementType(String elementType) {
+ this.elementType = elementType;
+ }
+
+ @Override
+ public String toString() {
+ return "QueryUserNeo4jInfo [userId=" + userId + ", firstName=" + firstName + ", lastName=" + lastName
+ + ", email=" + email + ", role=" + role + ", label=" + label + ", elementType=" + elementType + "]";
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
new file mode 100644
index 0000000000..8ea8524489
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetAssetServlet.java
@@ -0,0 +1,351 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.externalApis;
+
+import static org.testng.AssertJUnit.assertEquals;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.ArtifactUiDownloadData;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.model.User;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.api.Urls;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.common.api.Constants;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import com.google.gson.Gson;
+
+public class GetAssetServlet extends ComponentBaseTest {
+
+ protected User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER);
+ protected User sdncAdminUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN);
+ protected ConsumerDataDefinition consumerDataDefinition;
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetAssetServlet() {
+ super(name, GetAssetServlet.class.getName());
+ }
+
+ Gson gson = new Gson();
+
+ @BeforeMethod
+ public void setup() throws Exception {
+
+ AtomicOperationUtils.createDefaultConsumer(true);
+ // consumerDataDefinition =
+ // ConsumerRestUtils.getDefaultConsumerDetails();
+ // RestResponse deleteResponse =
+ // ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ // sdncAdminUserDetails);
+ // BaseRestUtils.checkStatusCode(deleteResponse, "delete operation
+ // filed", false, 404,200);;
+ //
+ // RestResponse createResponse =
+ // ConsumerRestUtils.createConsumer(consumerDataDefinition,
+ // sdncAdminUserDetails);
+ // BaseRestUtils.checkCreateResponse(createResponse);
+
+ }
+
+ // @AfterMethod
+ // public void tearDown() throws Exception{
+ // RestResponse deleteResponse =
+ // ConsumerRestUtils.deleteConsumer(consumerDataDefinition,
+ // sdncAdminUserDetails);
+ // BaseRestUtils.checkStatusCode(deleteResponse, "delete operation filed",
+ // false, 404,200);
+ //
+ // }
+
+ @Test // (enabled = false)
+ public void getResourceAssetSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("Resource1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource2");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource3");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource4");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource5");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource6");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails.setName("Resource7");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+ expectedAssetNamesList.add(resource.getName());
+
+ System.out.println("7 VF resources were created");
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ AssetRestUtils.checkResourceTypeInObjectList(resourceAssetList, ResourceTypeEnum.VF);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_ASSET_LIST);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), null);
+
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setName("Service1");
+ RestResponse createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ Service service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service2");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service3");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service4");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service5");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service6");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service7");
+ createService = ServiceRestUtils.createService(serviceDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft();
+ expectedAssetNamesList.add(service.getName());
+ expectedAssetNamesList.add(service.getName());
+
+ System.out.println("7 Services were created");
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_ASSET_LIST);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_ASSET_LIST.getName(), null);
+
+ }
+
+ @Test
+ public void getToscaModelSuccess() throws Exception {
+
+ CloseableHttpClient httpclient = HttpClients.createDefault();
+ ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
+ resourceDetails.setName("Resource1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncUserDetails);
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ HttpResponse assetResponse = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
+ resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ String artId = resource.getToscaArtifacts().get("assettoscacsar").getEsId();
+ String url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), resource.getUniqueId(), artId);
+ HttpGet httpGet = createGetRequest(url);
+ HttpResponse response = httpclient.execute(httpGet);
+ InputStream inputStream = response.getEntity().getContent();
+ ArtifactUiDownloadData artifactUiDownloadData = getArtifactUiDownloadData(IOUtils.toString(inputStream));
+ assetResponse = AssetRestUtils.getComponentToscaModel(AssetTypeEnum.RESOURCES, resource.getUUID());
+ inputStream = assetResponse.getEntity().getContent();
+ int len = (int) assetResponse.getEntity().getContentLength();
+ byte[] res = new byte[len];
+ inputStream.read(res, 0, len);
+ byte[] fromUiDownload = artifactUiDownloadData.getBase64Contents().getBytes();
+ assertEquals(Base64.encodeBase64(res), fromUiDownload);
+ String fileName = assetResponse.getFirstHeader(Constants.CONTENT_DISPOSITION_HEADER).getValue();
+ assertEquals(fileName, new StringBuilder().append("attachment; filename=\"").append(artifactUiDownloadData.getArtifactName()).append("\"").toString());
+ }
+
+ private HttpGet createGetRequest(String url) {
+ HttpGet httpGet = new HttpGet(url);
+ httpGet.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId());
+ return httpGet;
+ }
+
+ private ArtifactUiDownloadData getArtifactUiDownloadData(String artifactUiDownloadDataStr) throws Exception {
+
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ ArtifactUiDownloadData artifactUiDownloadData = mapper.readValue(artifactUiDownloadDataStr, ArtifactUiDownloadData.class);
+ return artifactUiDownloadData;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java
new file mode 100644
index 0000000000..3886c5aa3e
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetFilteredAssetServlet.java
@@ -0,0 +1,438 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.externalApis;
+
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ErrorInfo;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.NormativeTypesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ServiceCategoriesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GetFilteredAssetServlet extends ComponentBaseTest {
+
+ protected final static String categoryFilterKey = "category";
+ protected final static String subCategoryFilterKey = "subCategory";
+ protected final static String distributionStatusFilterKey = "distributionStatus";
+ protected final static String serviceKey = "service";
+ protected final static String resourceKey = "resource";
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetFilteredAssetServlet() {
+ super(name, GetFilteredAssetServlet.class.getName());
+ }
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ AtomicOperationUtils.createDefaultConsumer(true);
+ }
+
+ // RESOURCE
+ // Success
+
+ @Test // (enabled = false)
+ public void getResourceAssetBySpecifiedCategory() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory() };
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resource1.getName());
+ Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resource2.getName());
+ Resource resource3 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.NETWORK_CONNECTIVITY_CON_POINT, UserRoleEnum.DESIGNER, true).left().value();
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ // 2 resources has the same category and different subcategory
+ @Test // (enabled = false)
+ public void getResourceAssetBySpecifiedCategoryAndSubCategory() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory(), subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getSubCategory() };
+ // String[] filter2 = {categoryFilterKey + "=" +
+ // ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getCategory(),
+ // subCategoryFilterKey + "=" +
+ // ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS.getSubCategory()};
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resource1.getName());
+ Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_NETWORK_ELEMENTS, UserRoleEnum.DESIGNER, true).left().value();
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetBySpecifiedSubCategoryAndCategory() throws Exception {
+ String[] filter = { subCategoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory(), categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), };
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ Resource resource1 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.COMPUTE, ResourceCategoryEnum.GENERIC_ABSTRACT, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils.createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.DATABASE, ResourceCategoryEnum.GENERIC_DATABASE, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(resource2.getName());
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ // Failure
+ @Test // (enabled = false)
+ public void getResourceAssetCategoryNotExists() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + "NotExistingCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(resourceKey, categoryFilterKey, "NotExistingCategory");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetSubCategoryNotExists() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory(), subCategoryFilterKey + "=" + "NotExistingSubCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList("Resource", "NotExistingSubCategory", ResourceCategoryEnum.GENERIC_ABSTRACT.getCategory());
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_SUB_CATEGORY_NOT_FOUND_FOR_CATEGORY.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetCategoryNotExistsSubCategoryExists() throws Exception {
+ String[] filter = { subCategoryFilterKey + "=" + ResourceCategoryEnum.NETWORK_L2_3_GETEWAY.getSubCategory(), categoryFilterKey + "=" + "NotExistingCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(resourceKey, categoryFilterKey, "NotExistingCategory");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetInvalidFilterKey() throws Exception {
+ String[] filter = { subCategoryFilterKey + "1=" + ResourceCategoryEnum.NETWORK_L2_3_GETEWAY.getSubCategory(), categoryFilterKey + "=" + "NotExistingCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.RESOURCES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(subCategoryFilterKey + "1", "[" + subCategoryFilterKey + ", " + categoryFilterKey + "]");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.RESOURCES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ // ---------------------------------------------------------------------------------------------------------
+ // SERVICE
+ // Success
+ @Test // (enabled = false)
+ public void getServiceAssetBySpecifiedCategory() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue() };
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(service1.getName());
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetBySpecifiedCategoryAndDistributionStatus() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue(), distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED };
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
+
+ Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(service1.getName());
+ Service service2 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service2.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service2 = (Service) AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ expectedAssetNamesList.add(service2.getName());
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetByDistributionStatus() throws Exception {
+ String[] filter = { distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED };
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER, ArtifactTypeEnum.OTHER, true);
+
+ Service service1 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ expectedAssetNamesList.add(service1.getName());
+ Service service2 = AtomicOperationUtils.createServiceByCategory(ServiceCategoriesEnum.MOBILITY, UserRoleEnum.DESIGNER, true).left().value();
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service2.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service2 = (Service) AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ ServiceRestUtils.approveServiceDistribution(service2.getUniqueId(), UserRoleEnum.GOVERNOR.getUserId());
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> serviceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(serviceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ // Failure
+ @Test // (enabled = false)
+ public void getServiceAssetCategoryNotExists() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + "NotExistingCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(serviceKey, categoryFilterKey, "NotExistingCategory");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetInvalidDistributionStatus() throws Exception {
+ String[] filter = { distributionStatusFilterKey + "=" + "NotExistingDistributionStatus" };
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(serviceKey, distributionStatusFilterKey, "NotExistingDistributionStatus");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetCategoryExitsDistributionStatusInvalid() throws Exception {
+ String[] filter = { categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue(), distributionStatusFilterKey + "=" + "NotExistingDistributionStatus" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(serviceKey, distributionStatusFilterKey, "NotExistingDistributionStatus");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetCategoryNotExistsDistributionStatus() throws Exception {
+ String[] filter = { distributionStatusFilterKey + "=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, categoryFilterKey + "=" + "NotExistingCategory" };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(serviceKey, categoryFilterKey, "NotExistingCategory");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.COMPONENT_CATEGORY_NOT_FOUND.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetInvalidFilterKey() throws Exception {
+ String[] filter = { distributionStatusFilterKey + "1=" + DistributionStatusEnum.DISTRIBUTION_NOT_APPROVED, categoryFilterKey + "=" + ServiceCategoriesEnum.MOBILITY.getValue() };
+
+ RestResponse assetResponse = AssetRestUtils.getComponentListByAssetType(true, AssetTypeEnum.SERVICES, filter);
+ ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(ActionStatus.INVALID_FILTER_KEY.name());
+
+ assertNotNull("check response object is not null after create resouce", assetResponse);
+ assertNotNull("check error code exists in response after create resource", assetResponse.getErrorCode());
+ assertEquals("Check response code after create resource", errorInfo.getCode(), assetResponse.getErrorCode());
+
+ List<String> variables = Arrays.asList(distributionStatusFilterKey + "1", "[" + categoryFilterKey + ", " + distributionStatusFilterKey + "]");
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.INVALID_FILTER_KEY.name(), variables, assetResponse.getResponse());
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory.getDefaultAssetListAudit(AssetTypeEnum.SERVICES, AuditingActionEnum.GET_FILTERED_ASSET_LIST);
+ expectedAssetListAudit.setRESOURCE_URL(AssetRestUtils.buildUrlWithFilter(expectedAssetListAudit.getRESOURCE_URL(), filter));
+ expectedAssetListAudit.setSTATUS(errorInfo.getCode().toString());
+ expectedAssetListAudit.setDESC(AuditValidationUtils.buildAuditDescription(errorInfo, variables));
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit, AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+
+ }
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
new file mode 100644
index 0000000000..05d305ad9a
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/externalApis/GetSpecificAssetMetadataServlet.java
@@ -0,0 +1,773 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.externalApis;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Rule;
+import org.junit.rules.TestName;
+import org.openecomp.sdc.be.dao.api.ActionStatus;
+import org.openecomp.sdc.be.datatypes.enums.AssetTypeEnum;
+import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
+import org.openecomp.sdc.be.model.DistributionStatusEnum;
+import org.openecomp.sdc.be.model.Resource;
+import org.openecomp.sdc.be.model.Service;
+import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
+import org.openecomp.sdc.ci.tests.api.ComponentBaseTest;
+import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceDetailedAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceDetailedAssetStructure;
+import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.ResourceCategoryEnum;
+import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
+import org.openecomp.sdc.ci.tests.datatypes.expected.ExpectedExternalAudit;
+import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
+import org.openecomp.sdc.ci.tests.utils.Utils;
+import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
+import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
+import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.AssetRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.LifecycleRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
+import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.AuditValidationUtils;
+import org.openecomp.sdc.ci.tests.utils.validation.ErrorValidationUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class GetSpecificAssetMetadataServlet extends ComponentBaseTest {
+ private static Logger log = LoggerFactory.getLogger(GetAssetServlet.class.getName());
+
+ @Rule
+ public static TestName name = new TestName();
+
+ public GetSpecificAssetMetadataServlet() {
+ super(name, GetSpecificAssetMetadataServlet.class.getName());
+ }
+
+ @BeforeMethod
+ public void setup() throws Exception {
+ AtomicOperationUtils.createDefaultConsumer(true);
+ }
+
+ // get specific asset metadata
+
+ // Resource
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithResourceInstancesSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = ResponseParser.parseToObjectUsingMapper(
+ ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithNonCertifiedResourceInstancesSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+
+ // certify resource2 and add to VF(VF with resource2 0.1, 1.0 and 1.1
+ // versions)
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = ResponseParser.parseToObjectUsingMapper(
+ ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithResourceInstancesVfInSubmitForTestingSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+
+ // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0
+ // versions)
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithResourceInstancesVfInStartCertificationSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+
+ // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0
+ // versions)
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true)
+ .getLeft();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithResourceInstancesCertifiedVFSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+
+ // certify resource2 and add to VF(VF with resource2 1.0, 2.0 and 3.0
+ // versions)
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getResourceAssetMetadataWithNonCertifiedResourceInstancesAndArtifactsSuccess() throws Exception {
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ Resource resource2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ Resource resource3 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VFC, UserRoleEnum.DESIGNER, true).left().value();
+ resource3 = (Resource) AtomicOperationUtils
+ .changeComponentState(resource3, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true)
+ .getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource2, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resource3, resourceVF, UserRoleEnum.DESIGNER,
+ true);
+
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER,
+ true, true);
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF, UserRoleEnum.DESIGNER, true,
+ true);
+ resourceVF = ResponseParser.parseToObjectUsingMapper(
+ ResourceRestUtils.getResource(resourceVF.getUniqueId()).getResponse(), Resource.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.RESOURCES,
+ resourceVF.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ResourceDetailedAssetStructure resourceAssetMetadata = AssetRestUtils.getResourceAssetMetadata(assetResponse);
+ AssetRestUtils.resourceMetadataValidatior(resourceAssetMetadata, resourceVF, AssetTypeEnum.RESOURCES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.RESOURCES, resourceVF);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ // Import CSAR
+
+ // Service
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataSuccess() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ service.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
+ AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataWithResourceInstancesSuccess() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+ service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils
+ .getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(),
+ Service.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ service.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
+ AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataWithNonCertifiedResourceInstancesWithArtifactsSuccess() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ Resource resourceVF2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+
+ // service with 0.1, 0.1 and 1.0 RIs versions
+ service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils
+ .getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(),
+ Service.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ service.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
+ AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataWithCertifiedResourceInstancesAndArtifactsOnRIsAndServiceSuccess()
+ throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ Resource resourceVF2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF2 = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, resourceVF,
+ UserRoleEnum.DESIGNER, true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+
+ // service with resourceVF 1.0(1 art), 2.0(2 art) versions and
+ // resourceVF2 1.0(1 art), service 1 artifact version
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, service,
+ UserRoleEnum.DESIGNER, true, true);
+ service = ResponseParser.parseToObjectUsingMapper(ServiceRestUtils
+ .getService(service.getUniqueId(), ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER)).getResponse(),
+ Service.class);
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ service.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
+ AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataWithResourceInstancesServiceInSubmitForTestingSuccess() throws Exception {
+
+ Service service = AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true).left().value();
+
+ Resource resourceVF = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.VENDOR_LICENSE, resourceVF, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ Resource resourceVF2 = AtomicOperationUtils
+ .createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true).left().value();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.APPC_CONFIG, resourceVF2, UserRoleEnum.DESIGNER,
+ true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF2, service, UserRoleEnum.DESIGNER,
+ true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, resourceVF,
+ UserRoleEnum.DESIGNER, true, true);
+ resourceVF = (Resource) AtomicOperationUtils
+ .changeComponentState(resourceVF, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceVF, service, UserRoleEnum.DESIGNER, true);
+
+ // service with resourceVF 1.0(1 art), 2.0(2 art) versions and
+ // resourceVF2 1.0(1 art), service 1 artifact version
+ AtomicOperationUtils.uploadArtifactByType(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE, service,
+ UserRoleEnum.DESIGNER, true, true);
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ service.getUUID());
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ ServiceDetailedAssetStructure serviceAssetMetadata = AssetRestUtils.getServiceAssetMetadata(assetResponse);
+ AssetRestUtils.serviceMetadataValidatior(serviceAssetMetadata, service, AssetTypeEnum.SERVICES);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultAssetMetadataAudit(AssetTypeEnum.SERVICES, service);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_ASSET_METADATA.getName(), null);
+ }
+
+ @Test // (enabled = false)
+ public void getServiceAssetMetadataServiceNotFound() throws Exception {
+
+ String serviceUuid = "notExistingServiceUuid";
+ RestResponse assetResponse = AssetRestUtils.getAssetMetadataByAssetTypeAndUuid(true, AssetTypeEnum.SERVICES,
+ serviceUuid);
+
+ // Validate audit message
+ ArrayList<String> variables = new ArrayList<>();
+ variables.add(serviceUuid);
+ ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.RESOURCE_NOT_FOUND.name(), variables,
+ assetResponse.getResponse());
+ }
+
+ // Add to service VF instance imported from CSAR
+
+ @Test
+ public void getFilteredResourceAssetSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+
+ ResourceReqDetails resourceDetails = ElementFactory
+ .getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_APP_SERVER);
+ resourceDetails.setName("Resource1");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ RestResponse createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ Resource resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ expectedAssetNamesList.add(resource.getName());
+
+ resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_BORDER);
+ resourceDetails.setName("Resource2");
+ resourceDetails.setResourceType(ResourceTypeEnum.VFC.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.GENERIC_INFRASTRUCTURE);
+ resourceDetails.setName("Resource3");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ resourceDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.APPLICATION_L4_FIREWALL);
+ resourceDetails.setName("Resource4");
+ resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
+ createResource = ResourceRestUtils.createResource(resourceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createResource);
+ resource = ResponseParser.parseToObjectUsingMapper(createResource.getResponse(), Resource.class);
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ resource = (Resource) AtomicOperationUtils
+ .changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ expectedAssetNamesList.add(resource.getName());
+
+ log.debug("4 resources created");
+ String query = "category=Application%20L4%2B";
+ RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.RESOURCES, query);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ResourceAssetStructure> resourceAssetList = AssetRestUtils.getResourceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getResourceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ AssetRestUtils.checkResourceTypeInObjectList(resourceAssetList, ResourceTypeEnum.VF);
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultFilteredAssetListAudit(AssetTypeEnum.RESOURCES, "?" + query);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+
+ }
+
+ @Test
+ public void getFilteredResourceAssetCategoryNotFound() throws Exception {
+
+ String query = "category=Application%20L3%2B";
+ RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.RESOURCES, query);
+ BaseRestUtils.checkErrorResponse(assetResponse, ActionStatus.COMPONENT_CATEGORY_NOT_FOUND, "resource",
+ "category", "Application L3+");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getFilteredAssetListAuditCategoryNotFound(AssetTypeEnum.RESOURCES, "?" + query, "Application L3+");
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+
+ }
+
+ @Test
+ public void getFilteredServiceAssetSuccess() throws Exception {
+
+ List<String> expectedAssetNamesList = new ArrayList<>();
+ ArtifactReqDetails artifactDetails = ElementFactory.getArtifactByType(ArtifactTypeEnum.OTHER,
+ ArtifactTypeEnum.OTHER, true);
+
+ ServiceReqDetails serviceDetails = ElementFactory.getDefaultService();
+ serviceDetails.setName("Service1");
+ RestResponse createService = ServiceRestUtils.createService(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ Service service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+
+ serviceDetails.setName("Service2");
+ createService = ServiceRestUtils.createService(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ RestResponse addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(
+ artifactDetails, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+
+ ServiceReqDetails certifyService = new ServiceReqDetails(service);
+ LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(),
+ ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null,
+ DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ AtomicOperationUtils.distributeService(service, false);
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service3");
+ createService = ServiceRestUtils.createService(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ addInformationalArtifactToService = ArtifactRestUtils.addInformationalArtifactToService(artifactDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), service.getUniqueId());
+ BaseRestUtils.checkSuccess(addInformationalArtifactToService);
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft();
+ certifyService = new ServiceReqDetails(service);
+ LifecycleRestUtils.changeDistributionStatus(certifyService, certifyService.getVersion(),
+ ElementFactory.getDefaultUser(UserRoleEnum.GOVERNOR), null,
+ DistributionStatusEnum.DISTRIBUTION_APPROVED);
+ AtomicOperationUtils.distributeService(service, false);
+ expectedAssetNamesList.add(service.getName());
+
+ serviceDetails.setName("Service4");
+ createService = ServiceRestUtils.createService(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+
+ serviceDetails.setName("Service5");
+ createService = ServiceRestUtils.createService(serviceDetails,
+ ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER));
+ BaseRestUtils.checkCreateResponse(createService);
+ service = ResponseParser.parseToObjectUsingMapper(createService.getResponse(), Service.class);
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft();
+ service = (Service) AtomicOperationUtils
+ .changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft();
+
+ String query = "distributionStatus=Distributed";
+ RestResponse assetResponse = AssetRestUtils.getFilteredComponentList(AssetTypeEnum.SERVICES, query);
+ BaseRestUtils.checkSuccess(assetResponse);
+
+ List<ServiceAssetStructure> resourceAssetList = AssetRestUtils.getServiceAssetList(assetResponse);
+ List<String> getActualAssetNamesList = AssetRestUtils.getServiceNamesList(resourceAssetList);
+ Utils.compareArrayLists(getActualAssetNamesList, expectedAssetNamesList, "Element");
+
+ // Validate audit message
+ ExpectedExternalAudit expectedAssetListAudit = ElementFactory
+ .getDefaultFilteredAssetListAudit(AssetTypeEnum.SERVICES, "?" + query);
+ AuditValidationUtils.validateExternalAudit(expectedAssetListAudit,
+ AuditingActionEnum.GET_FILTERED_ASSET_LIST.getName(), null);
+
+ }
+
+}
diff --git a/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java b/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
new file mode 100644
index 0000000000..f0494fe177
--- /dev/null
+++ b/asdc-tests/src/main/java/org/openecomp/sdc/post/Install.java
@@ -0,0 +1,69 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * SDC
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.sdc.post;
+
+import java.io.File;
+
+import org.openecomp.sdc.be.dao.titan.TitanGraphClient;
+import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
+
+public class Install {
+ public static void main(String[] args) {
+
+ if (args == null || args.length == 0) {
+ System.out.println("Usage: org.openecomp.sdc.post.Install path_to_titan.properties");
+ System.exit(1);
+ }
+ String titanPropsFile = args[0];
+
+ if (!isFileExists(titanPropsFile)) {
+ System.exit(2);
+ }
+
+ if (!createTitanSchema(titanPropsFile)) {
+ System.exit(3);
+ }
+
+ System.exit(0);
+ }
+
+ private static boolean createTitanSchema(String titanPropsFile) {
+ TitanGraphClient titanGraphClient = new TitanGraphClient();
+ TitanOperationStatus status = titanGraphClient.createGraph(titanPropsFile, true);
+ if (TitanOperationStatus.OK == status) {
+ System.out.println("Titan schema ,indexes and default values created successfully.");
+ return true;
+ } else {
+ System.out.println(
+ "Problem while creating titan schema ,indexes and default values. (" + status.name() + ")");
+ return false;
+ }
+ }
+
+ private static boolean isFileExists(String titanPropsFile) {
+ File f = new File(titanPropsFile);
+ if (!f.exists()) {
+ System.out.println(titanPropsFile + " not found");
+ return false;
+ }
+ return true;
+ }
+}