diff --git a/src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceRepoService.java b/src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceRepoService.java index 55db1280b24b88784f07f590bd3cb35878d92c7f..9e79d472e5903d40fea50714d745f4762057ae2b 100644 --- a/src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceRepoService.java +++ b/src/main/java/org/etsi/osl/tmf/ri639/reposervices/ResourceRepoService.java @@ -284,7 +284,7 @@ public class ResourceRepoService { @Transactional public Resource updateResource(String id, @Valid ResourceUpdate resourceUpd, - boolean propagateToSO) { + boolean triggerServiceActionQueue) { Resource resource = this.getResourceEager(id); if (resource == null) { diff --git a/src/main/java/org/etsi/osl/tmf/scm633/api/ServiceSpecificationApiController.java b/src/main/java/org/etsi/osl/tmf/scm633/api/ServiceSpecificationApiController.java index cd488bafedc7f7da986af7456809eff17e01d4c6..12482fb6c40803c28239eb73944481422946567b 100644 --- a/src/main/java/org/etsi/osl/tmf/scm633/api/ServiceSpecificationApiController.java +++ b/src/main/java/org/etsi/osl/tmf/scm633/api/ServiceSpecificationApiController.java @@ -186,18 +186,6 @@ public class ServiceSpecificationApiController implements ServiceSpecificationAp @Parameter(description = "Identifier of the ServiceSpecification", required = true) @PathVariable("id") String id, @Parameter(description = "Comma-separated properties to provide in response") @Valid @RequestParam(value = "fields", required = false) String fields) { try { - - Object attr = request.getSession().getAttribute("SPRING_SECURITY_CONTEXT"); - - if ( attr!=null) { - SecurityContextHolder.setContext( (SecurityContext) attr ); - } - if ( SecurityContextHolder.getContext().getAuthentication() != null ) { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - centralLogger.log( CLevel.INFO, "User " + authentication.getName() + " retrieve spec id: "+ id , compname ); - } else { - centralLogger.log( CLevel.INFO, "Anonymous retrieve spec id: "+ id, compname ); - } return new ResponseEntity(serviceSpecificationRepoService.findByUuid(id), HttpStatus.OK); diff --git a/src/main/java/org/etsi/osl/tmf/scm633/reposervices/ServiceSpecificationRepoService.java b/src/main/java/org/etsi/osl/tmf/scm633/reposervices/ServiceSpecificationRepoService.java index 23a8645c629f5b0107ca410fc312b95d4a9e375d..c0d6f7b35fa6274ffddfcc443b4faf4a3e052a2a 100644 --- a/src/main/java/org/etsi/osl/tmf/scm633/reposervices/ServiceSpecificationRepoService.java +++ b/src/main/java/org/etsi/osl/tmf/scm633/reposervices/ServiceSpecificationRepoService.java @@ -570,10 +570,11 @@ public class ServiceSpecificationRepoService { /** * Also, - * we will add by default all the characteristics of this service to the related bundle parent service + * we will add by default all the characteristics of this service to the related bundle parent service + * Removed to try new approach with rules */ - serviceSpec = copyCharacteristicsOfServiceId( ar.getId(), serviceSpec); + //serviceSpec = copyCharacteristicsOfServiceId( ar.getId(), serviceSpec); } } @@ -619,7 +620,7 @@ public class ServiceSpecificationRepoService { * Also, * we will add by default all the characteristics of this rSpec to the related bundle parent service */ - serviceSpec = copyCharacteristicsOfResourceSpecId( ar.getId(), serviceSpec); + //serviceSpec = copyCharacteristicsOfResourceSpecId( ar.getId(), serviceSpec); } } @@ -696,24 +697,24 @@ public class ServiceSpecificationRepoService { return targetServiceSpec; } - private ServiceSpecification copyCharacteristicsOfResourceSpecId(String sourceResourceSpecid, ServiceSpecification targetServiceSpec) { - - ResourceSpecification rSpec = resourceSpecRepoService.findByUuid( sourceResourceSpecid ); - - if ( rSpec != null ) { - for (ResourceSpecificationCharacteristic sourceChar : rSpec.getResourceSpecCharacteristic()) { - ServiceSpecCharacteristic serviceSpecCharacteristicItem = copyResourceCharacteristic( sourceChar ); - //serviceSpecCharacteristicItem.setName( rSpec.getName() + "::" +sourceChar.getName() ); - serviceSpecCharacteristicItem.setName( sourceChar.getName() ); - - if ( targetServiceSpec.findSpecCharacteristicByName( serviceSpecCharacteristicItem.getName() ) == null ) { - targetServiceSpec.getServiceSpecCharacteristic().add( serviceSpecCharacteristicItem ); - } - } - } - - return targetServiceSpec; - } +// private ServiceSpecification copyCharacteristicsOfResourceSpecId(String sourceResourceSpecid, ServiceSpecification targetServiceSpec) { +// +// ResourceSpecification rSpec = resourceSpecRepoService.findByUuid( sourceResourceSpecid ); +// +// if ( rSpec != null ) { +// for (ResourceSpecificationCharacteristic sourceChar : rSpec.getResourceSpecCharacteristic()) { +// ServiceSpecCharacteristic serviceSpecCharacteristicItem = copyResourceCharacteristic( sourceChar ); +// //serviceSpecCharacteristicItem.setName( rSpec.getName() + "::" +sourceChar.getName() ); +// serviceSpecCharacteristicItem.setName( sourceChar.getName() ); +// +// if ( targetServiceSpec.findSpecCharacteristicByName( serviceSpecCharacteristicItem.getName() ) == null ) { +// targetServiceSpec.getServiceSpecCharacteristic().add( serviceSpecCharacteristicItem ); +// } +// } +// } +// +// return targetServiceSpec; +// } public ServiceSpecification cloneServiceSpecification(String uuid) { ServiceSpecification source = this.findByUuid(uuid); @@ -1410,11 +1411,12 @@ public class ServiceSpecificationRepoService { serviceSpec.setType("ResourceFacingServiceSpecification"); - for (ResourceSpecificationCharacteristic sourceChar : rSpec.getResourceSpecCharacteristic()) { - ServiceSpecCharacteristic serviceSpecCharacteristicItem = copyResourceCharacteristic( sourceChar ); - serviceSpecCharacteristicItem.setName( rSpec.getName() + "::" +sourceChar.getName() ); - serviceSpec.addServiceSpecCharacteristicItem(serviceSpecCharacteristicItem ); - } + +// for (ResourceSpecificationCharacteristic sourceChar : rSpec.getResourceSpecCharacteristic()) { +// ServiceSpecCharacteristic serviceSpecCharacteristicItem = copyResourceCharacteristic( sourceChar ); +// serviceSpecCharacteristicItem.setName( rSpec.getName() + "::" +sourceChar.getName() ); +// serviceSpec.addServiceSpecCharacteristicItem(serviceSpecCharacteristicItem ); +// } ResourceSpecificationRef resourceSpecRef = new ResourceSpecificationRef(); @@ -1427,25 +1429,25 @@ public class ServiceSpecificationRepoService { return serviceSpec; } - private ServiceSpecCharacteristic copyResourceCharacteristic( ResourceSpecificationCharacteristic sourceChar ) { - - ServiceSpecCharacteristic serviceSpecCharacteristicItem = new ServiceSpecCharacteristic(); - serviceSpecCharacteristicItem.setDescription( sourceChar.getDescription()); - serviceSpecCharacteristicItem.valueType( sourceChar.getValueType() ); - serviceSpecCharacteristicItem.configurable(sourceChar.isConfigurable()); - serviceSpecCharacteristicItem.setMinCardinality( sourceChar.getMinCardinality() ); - serviceSpecCharacteristicItem.setMaxCardinality( sourceChar.getMaxCardinality() ); - serviceSpecCharacteristicItem.setValidFor( sourceChar.getValidFor() ); - for (ResourceSpecificationCharacteristicValue cv : sourceChar.getResourceSpecCharacteristicValue()) { - ServiceSpecCharacteristicValue serviceSpecCharacteristicValueItem = new ServiceSpecCharacteristicValue(); - serviceSpecCharacteristicValueItem.setValue( new Any( cv.getValue().getValue(), cv.getValue().getAlias())); - serviceSpecCharacteristicValueItem.isDefault( cv.isIsDefault() ); - serviceSpecCharacteristicValueItem.setUnitOfMeasure( cv.getUnitOfMeasure() ); - serviceSpecCharacteristicItem.addServiceSpecCharacteristicValueItem(serviceSpecCharacteristicValueItem ); - } - return serviceSpecCharacteristicItem; - } - +// private ServiceSpecCharacteristic copyResourceCharacteristic( ResourceSpecificationCharacteristic sourceChar ) { +// +// ServiceSpecCharacteristic serviceSpecCharacteristicItem = new ServiceSpecCharacteristic(); +// serviceSpecCharacteristicItem.setDescription( sourceChar.getDescription()); +// serviceSpecCharacteristicItem.valueType( sourceChar.getValueType() ); +// serviceSpecCharacteristicItem.configurable(sourceChar.isConfigurable()); +// serviceSpecCharacteristicItem.setMinCardinality( sourceChar.getMinCardinality() ); +// serviceSpecCharacteristicItem.setMaxCardinality( sourceChar.getMaxCardinality() ); +// serviceSpecCharacteristicItem.setValidFor( sourceChar.getValidFor() ); +// for (ResourceSpecificationCharacteristicValue cv : sourceChar.getResourceSpecCharacteristicValue()) { +// ServiceSpecCharacteristicValue serviceSpecCharacteristicValueItem = new ServiceSpecCharacteristicValue(); +// serviceSpecCharacteristicValueItem.setValue( new Any( cv.getValue().getValue(), cv.getValue().getAlias())); +// serviceSpecCharacteristicValueItem.isDefault( cv.isIsDefault() ); +// serviceSpecCharacteristicValueItem.setUnitOfMeasure( cv.getUnitOfMeasure() ); +// serviceSpecCharacteristicItem.addServiceSpecCharacteristicValueItem(serviceSpecCharacteristicValueItem ); +// } +// return serviceSpecCharacteristicItem; +// } +// diff --git a/src/main/java/org/etsi/osl/tmf/sim638/api/ServiceApiRouteBuilder.java b/src/main/java/org/etsi/osl/tmf/sim638/api/ServiceApiRouteBuilder.java index c3ca3c8d43f3c0672de014058cd97004159ecfb2..55e38b6687ada1511b065fadd1fb68c4d99f290c 100644 --- a/src/main/java/org/etsi/osl/tmf/sim638/api/ServiceApiRouteBuilder.java +++ b/src/main/java/org/etsi/osl/tmf/sim638/api/ServiceApiRouteBuilder.java @@ -131,7 +131,7 @@ public class ServiceApiRouteBuilder extends RouteBuilder { .log(LoggingLevel.INFO, log, CATALOG_UPD_SERVICE + " message received and will be processed for service inventory!") .to("log:DEBUG?showBody=true&showHeaders=true") .unmarshal().json( JsonLibrary.Jackson, ServiceUpdate.class, true) - .bean( serviceRepoService, "updateService(${header.serviceid}, ${body}, ${header.propagateToSO} )") + .bean( serviceRepoService, "updateService(${header.serviceid}, ${body}, ${header.triggerServiceActionQueue} )") .marshal().json( JsonLibrary.Jackson) .convertBodyTo( String.class ); diff --git a/src/main/java/org/etsi/osl/tmf/sim638/service/ServiceRepoService.java b/src/main/java/org/etsi/osl/tmf/sim638/service/ServiceRepoService.java index 843bcf1a21df58027ca0256bee85358a7b808cb5..d5b97e3b7099e4d0c53b152b699315ee097541a8 100644 --- a/src/main/java/org/etsi/osl/tmf/sim638/service/ServiceRepoService.java +++ b/src/main/java/org/etsi/osl/tmf/sim638/service/ServiceRepoService.java @@ -346,8 +346,16 @@ public class ServiceRepoService { .orElse(null); } + /** + * @param id + * @param servUpd + * @param triggerServiceActionQueue + * @param updatedFromParentService + * @param updatedFromChildService + * @return + */ @Transactional - public Service updateService(String id, @Valid ServiceUpdate servUpd, boolean propagateToSO, Service updatedFromParentService, Service updatedFromChildService ) { + public Service updateService(String id, @Valid ServiceUpdate servUpd, boolean triggerServiceActionQueue, Service updatedFromParentService, Service updatedFromChildService ) { //Service service = this.findByUuid(id); Service service = this.getServiceEager(id); @@ -458,7 +466,7 @@ public class ServiceRepoService { boolean serviceCharacteristicChangedContainsPrimitive = false; String charChangedForNotes = ""; - List childCharacteristicsChanged = new ArrayList<>(); + //List childCharacteristicsChanged = new ArrayList<>(); //logger.info("==> Will update serviceToString: " + service.toString() ); @@ -472,15 +480,18 @@ public class ServiceRepoService { Characteristic origChar = service.getServiceCharacteristicByName( n.getName() ); if ( ( origChar !=null ) && ( origChar.getValue() !=null ) && ( origChar.getValue().getValue() !=null )) { if ( !origChar.getValue().getValue().equals(n.getValue().getValue()) ) { - if ( n.getName().contains("::") ) { - childCharacteristicsChanged.add(n); //the characteristic needs later to be propagated to its children - - } - serviceCharacteristicChanged = true; //change only characteristics of this service - charChangedForNotes += n.getName(); - if ( n.getName().toUpperCase().contains( "PRIMITIVE::" ) ){ - serviceCharacteristicChangedContainsPrimitive = true; - } +// if ( n.getName().contains("::") ) { +// childCharacteristicsChanged.add(n); //the characteristic needs later to be propagated to its children +// +// } + + if ( !n.getName().contains("::") ) { //it is not a child characteristic + serviceCharacteristicChanged = true; //change only characteristics of this service + charChangedForNotes += n.getName() + ", "; + } + if ( n.getName().toUpperCase().contains( "PRIMITIVE::" ) ){ + serviceCharacteristicChangedContainsPrimitive = true; + } } } @@ -490,8 +501,10 @@ public class ServiceRepoService { ); } else { service.addServiceCharacteristicItem(n); - serviceCharacteristicChanged = true; - charChangedForNotes += n.getName() + ", "; + if ( !n.getName().contains("::") ) { //it is not a child characteristic + serviceCharacteristicChanged = true; + charChangedForNotes += n.getName() + ", "; + } } } @@ -561,7 +574,7 @@ public class ServiceRepoService { * Save in ServiceActionQueueItem */ - if (propagateToSO && stateChanged) { + if (triggerServiceActionQueue && stateChanged) { ServiceActionQueueItem saqi = new ServiceActionQueueItem(); saqi.setServiceRefId( id ); saqi.setOriginalServiceInJSON( originaServiceAsJson ); @@ -594,7 +607,7 @@ public class ServiceRepoService { } } - if ( serviceCharacteristicChanged && service.getState().equals( ServiceStateType.ACTIVE) && previousState!=null && previousState.equals( ServiceStateType.ACTIVE) ) { + if ( serviceCharacteristicChanged && service.getState().equals( ServiceStateType.ACTIVE) && previousState!=null && previousState.equals( ServiceStateType.ACTIVE) && triggerServiceActionQueue ) { ServiceActionQueueItem saqi = new ServiceActionQueueItem(); saqi.setServiceRefId( id ); saqi.setOriginalServiceInJSON( originaServiceAsJson ); @@ -602,65 +615,88 @@ public class ServiceRepoService { if ( serviceCharacteristicChangedContainsPrimitive ) { saqi.setAction( ServiceActionQueueAction.EVALUATE_CHARACTERISTIC_CHANGED_MANODAY2 ); } - - - this.addServiceActionQueueItem(saqi); } - if ( serviceCharacteristicChanged) { - /* - * Update any parent service - */ - for (ServiceRelationship serviceRelationship : service.getServiceRelationship()) { - if ( serviceRelationship.getRelationshipType().equals("ChildService") ) { - if ( serviceRelationship.getService() != null ) { - if ( updatedFromParentService == null || - (updatedFromParentService!=null && !updatedFromParentService.getId().equals(serviceRelationship.getService().getId())) ) { //avoid circular - propagateCharacteristicsToParentService(service, serviceRelationship.getService().getId()); - } - - } - } - } - } + /* + * Update any parent service + */ + for (ServiceRelationship serviceRelationship : service.getServiceRelationship()) { + if (serviceRelationship.getRelationshipType().equals("ChildService")) { + if (serviceRelationship.getService() != null) { + + + if (serviceCharacteristicChanged) { + if (updatedFromParentService == null || (updatedFromParentService != null && !updatedFromParentService.getId().equals(serviceRelationship.getService().getId()))) { // avoid circular + ServiceActionQueueItem saqi = new ServiceActionQueueItem(); // this will trigger lcm rule to parent + saqi.setServiceRefId(serviceRelationship.getService().getId()); + try { + saqi.setOriginalServiceInJSON( mapper.writeValueAsString( service ) ); //pass the child service as is + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + saqi.setAction(ServiceActionQueueAction.EVALUATE_CHILD_CHARACTERISTIC_CHANGED); + this.addServiceActionQueueItem(saqi); + } + + } + + if (stateChanged) { + if (updatedFromParentService == null || (updatedFromParentService != null && !updatedFromParentService.getId().equals(serviceRelationship.getService().getId()))) { // avoid circular + ServiceActionQueueItem saqi = new ServiceActionQueueItem(); // this will trigger lcm rule to parent + saqi.setServiceRefId(serviceRelationship.getService().getId()); + try { + saqi.setOriginalServiceInJSON( mapper.writeValueAsString( service ) ); //pass the child service as is + } catch (JsonProcessingException e) { + e.printStackTrace(); + } + saqi.setAction(ServiceActionQueueAction.EVALUATE_CHILD_STATE_CHANGE ); + this.addServiceActionQueueItem(saqi); + } + } + + + + } + } + } - if ( childCharacteristicsChanged.size()>0 ) { - if ( service.getSupportingService() != null ) { //propagate to children - //copy characteristics values from CFS Service to its supporting services. - for (ServiceRef sref : service.getSupportingService() ) { - Service aSupportingService = this.findByUuid( sref.getId() ); - ServiceUpdate supd = new ServiceUpdate(); - boolean foundCharacteristicForChild = false; - for (Characteristic supportingServiceChar : aSupportingService.getServiceCharacteristic() ) { - - for (Characteristic serviceCharacteristic : childCharacteristicsChanged ) { - if ( serviceCharacteristic.getName().contains( aSupportingService.getName() + "::" + supportingServiceChar.getName() )) { - //supportingServiceChar.setValue( serviceCharacteristic.getValue() ); - Characteristic cNew = new Characteristic(); - cNew.setName(supportingServiceChar.getName()); - cNew.value( new Any( serviceCharacteristic.getValue() )); - supd.addServiceCharacteristicItem( cNew ); - foundCharacteristicForChild = true; - } - } - } - - if ( foundCharacteristicForChild ) { - Note n = new Note(); - n.setText("Child Characteristics Changed" ); - n.setAuthor( "SIM638-API" ); - n.setDate( OffsetDateTime.now(ZoneOffset.UTC).toString() ); - supd.addNoteItem( n ); - if ( updatedFromChildService == null || - (updatedFromChildService!=null && !updatedFromChildService.getId().equals( aSupportingService.getId())) ) { //avoid circular - this.updateService( aSupportingService.getId(), supd , false, service, null); //update the service - } - } - } - - } - } +// if ( childCharacteristicsChanged.size()>0 ) { +// if ( service.getSupportingService() != null ) { //propagate to children +// //copy characteristics values from CFS Service to its supporting services. +// for (ServiceRef sref : service.getSupportingService() ) { +// Service aSupportingService = this.findByUuid( sref.getId() ); +// ServiceUpdate supd = new ServiceUpdate(); +// boolean foundCharacteristicForChild = false; +// for (Characteristic supportingServiceChar : aSupportingService.getServiceCharacteristic() ) { +// +// for (Characteristic serviceCharacteristic : childCharacteristicsChanged ) { +// if ( serviceCharacteristic.getName().contains( aSupportingService.getName() + "::" + supportingServiceChar.getName() )) { +// //supportingServiceChar.setValue( serviceCharacteristic.getValue() ); +// Characteristic cNew = new Characteristic(); +// cNew.setName(supportingServiceChar.getName()); +// cNew.value( new Any( serviceCharacteristic.getValue() )); +// supd.addServiceCharacteristicItem( cNew ); +// foundCharacteristicForChild = true; +// } +// } +// } +// +// if ( foundCharacteristicForChild ) { +// Note n = new Note(); +// n.setText("Child Characteristics Changed" ); +// n.setAuthor( "SIM638-API" ); +// n.setDate( OffsetDateTime.now(ZoneOffset.UTC).toString() ); +// supd.addNoteItem( n ); +// if ( updatedFromChildService == null || +// (updatedFromChildService!=null && !updatedFromChildService.getId().equals( aSupportingService.getId())) ) { //avoid circular +// this.updateService( aSupportingService.getId(), supd , false, service, null); //update the service +// } +// } +// } +// +// } +// } @@ -698,19 +734,19 @@ public class ServiceRepoService { * @param service * @param parentService */ - private void propagateCharacteristicsToParentService(Service childService, String parentServiceId) { - - ServiceUpdate servUpd = new ServiceUpdate(); - - for (Characteristic n : childService.getServiceCharacteristic()) { - Characteristic serviceCharacteristicItem = new Characteristic(); - serviceCharacteristicItem.setName( childService.getName() + "::" + n.getName()); - serviceCharacteristicItem.setValue( new Any( n.getValue() )); - servUpd.addServiceCharacteristicItem(serviceCharacteristicItem); - } - - this.updateService( parentServiceId, servUpd, false, null, childService); - } +// private void propagateCharacteristicsToParentService(Service childService, String parentServiceId) { +// +// ServiceUpdate servUpd = new ServiceUpdate(); +// +// for (Characteristic n : childService.getServiceCharacteristic()) { +// Characteristic serviceCharacteristicItem = new Characteristic(); +// serviceCharacteristicItem.setName( childService.getName() + "::" + n.getName()); +// serviceCharacteristicItem.setValue( new Any( n.getValue() )); +// servUpd.addServiceCharacteristicItem(serviceCharacteristicItem); +// } +// +// this.updateService( parentServiceId, servUpd, false, null, childService); +// } public String getServiceEagerAsString(String id) throws JsonProcessingException { Service s = this.getServiceEager(id); @@ -807,8 +843,8 @@ public class ServiceRepoService { logger.debug("Will add ServiceActionQueueItem ServiceRefId: " + item.getServiceRefId() ); //find any similar action inqueue and delete them, so to keep this one as the most recent - //List result = this.serviceActionQueueRepo.findByServiceRefIdAndAction(item.getServiceRefId(), item.getAction()); - //logger.debug("Will add ServiceActionQueueItem ServiceRefId result: " +result.size() ); + List result = this.serviceActionQueueRepo.findByServiceRefIdAndAction(item.getServiceRefId(), item.getAction()); + logger.debug("Will add ServiceActionQueueItem ServiceRefId result: " +result.size() ); this.serviceActionQueueRepo.deleteByServiceRefIdAndAction(item.getServiceRefId(), item.getAction()); return this.serviceActionQueueRepo.save( item); @@ -1101,8 +1137,7 @@ public class ServiceRepoService { n.setDate( OffsetDateTime.now(ZoneOffset.UTC).toString() ); supd.addNoteItem( n ); - this.updateService( aService.getId(), supd , true, null, null); //update the service - + this.updateService( aService.getId(), supd , true, null, null); //update the service } } diff --git a/src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilderEvents.java b/src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilderEvents.java index 64b5eb7999a466c3d34bd611fffdc609b6e46bd0..ac422ef6017f1dc1b3a72b1ceb20fe16427081e7 100644 --- a/src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilderEvents.java +++ b/src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilderEvents.java @@ -41,6 +41,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; @Configuration //@RefreshScope @@ -87,6 +88,7 @@ public class ServiceOrderApiRouteBuilderEvents extends RouteBuilder { /** * @param n */ + @Transactional public void publishEvent(final Notification n, final String objId) { n.setEventType( n.getClass().getName()); logger.info("will send Event for type " + n.getEventType()); diff --git a/src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java b/src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java index 80e1248c526b1b7c9378ba22da2e83455c8f7e15..d7214c4134e38adee1fbce93d8b92e3100e1f5d8 100644 --- a/src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java +++ b/src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java @@ -318,6 +318,7 @@ public class ServiceOrderRepoService { return res; } + @Transactional public ServiceOrder addServiceOrder(@Valid ServiceOrderCreate serviceOrderCreate) { ServiceOrder so = new ServiceOrder(); so.setOrderDate(OffsetDateTime.now(ZoneOffset.UTC)); diff --git a/src/test/java/org/etsi/osl/services/api/ServiceCatalogIntegrationTest.java b/src/test/java/org/etsi/osl/services/api/ServiceCatalogIntegrationTest.java index 56f3a73432b6c1d228a38b5a7a607811bf887080..6a865af5a25be13727697257f5240b843a02174a 100644 --- a/src/test/java/org/etsi/osl/services/api/ServiceCatalogIntegrationTest.java +++ b/src/test/java/org/etsi/osl/services/api/ServiceCatalogIntegrationTest.java @@ -521,17 +521,31 @@ public class ServiceCatalogIntegrationTest { ServiceSpecCharacteristicValue val = new ServiceSpecCharacteristicValue(); val.setValueType( EValueType.ARRAY.toString()); val.setValue( new Any("1" ,"a second value") ); - responsesSpecUpd.getServiceSpecCharacteristic().get(0).getServiceSpecCharacteristicValue().add(val); - ServiceSpecCharRelationship scrObj = responsesSpecUpd.getServiceSpecCharacteristic().get(0).getServiceSpecCharRelationship().toArray( new ServiceSpecCharRelationship[3])[0]; - ServiceSpecCharRelationship scrObj2 = responsesSpecUpd.getServiceSpecCharacteristic().get(0).getServiceSpecCharRelationship().toArray( new ServiceSpecCharRelationship[3])[1]; - ServiceSpecCharRelationship scrObj3 = responsesSpecUpd.getServiceSpecCharacteristic().get(0).getServiceSpecCharRelationship().toArray( new ServiceSpecCharRelationship[3])[2]; + + // Following code related to 'notNullRelationshipIndex' is to fix random test failures due to getServiceSpecCharacteristic + // not having 3 ServiceSpecCharRelationships + int notNullRelationshipIndex = 0; + for (int i=0; i { diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ExportJobApiController633Test.java b/src/test/java/org/etsi/osl/services/api/scm633/ExportJobApiController633Test.java new file mode 100644 index 0000000000000000000000000000000000000000..14a8a40ff6d3965ec67e6c2221fdd5fac3c114a5 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ExportJobApiController633Test.java @@ -0,0 +1,130 @@ +package org.etsi.osl.services.api.scm633; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ExportJobApiController633Test { + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testCreateExportJob() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testExportJob.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String exportJobString = IOUtils.toString(in, "UTF-8"); + ExportJobCreate exportJobCreate = JsonUtils.toJsonObj(exportJobString, ExportJobCreate.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/exportJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( exportJobCreate ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/exportJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( exportJobCreate ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteExportJob() throws Exception { + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/exportJob/testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListExportJob() throws Exception { + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/exportJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/exportJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveExportJob() throws Exception { + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/exportJob?testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/exportJob/testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/services/api/scm633/HubApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/HubApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..048ad19c20ee3c49ee427bf373885f4daa118d15 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/HubApiControllerTest.java @@ -0,0 +1,92 @@ +package org.etsi.osl.services.api.scm633; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class HubApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRegisterListener() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testEventSubscriptionInput.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String eventSubscriptionInputString = IOUtils.toString(in, "UTF-8"); + EventSubscriptionInput eventSubscriptionInput = JsonUtils.toJsonObj(eventSubscriptionInputString, EventSubscriptionInput.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/hub") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( eventSubscriptionInput ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/hub") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( eventSubscriptionInput ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testUnregisterListener() throws Exception { + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/hub/testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ImportJobApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ImportJobApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0d3769881e3381b6d08eeb069f1e9935aa1d23c8 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ImportJobApiControllerTest.java @@ -0,0 +1,130 @@ +package org.etsi.osl.services.api.scm633; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ImportJobApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testCreateImportJob() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testExportJob.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String exportJobString = IOUtils.toString(in, "UTF-8"); + ExportJobCreate exportJobCreate = JsonUtils.toJsonObj(exportJobString, ExportJobCreate.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/importJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( exportJobCreate ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/importJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( exportJobCreate ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteImportJob() throws Exception { + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/importJob/testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListImportJob() throws Exception { + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/importJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/importJob") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveImportJob() throws Exception { + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/importJob?testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/importJob/testId") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(501)); + } +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ListenerApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ListenerApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9ed631a15bb0999c56f5dd8bbf9f03d524a2abad --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ListenerApiControllerTest.java @@ -0,0 +1,392 @@ +package org.etsi.osl.services.api.scm633; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ListenerApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCandidateChangeNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String changeNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCandidateChangeNotification serviceCandidateChangeNotification = JsonUtils.toJsonObj(changeNotificationString, ServiceCandidateChangeNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateChangeNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateChangeNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCandidateCreateNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String createNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCandidateCreateNotification serviceCandidateCreateNotification = JsonUtils.toJsonObj(createNotificationString, ServiceCandidateCreateNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateCreateNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateCreateNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCandidateDeleteNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String deleteNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCandidateDeleteNotification serviceCandidateDeleteNotification = JsonUtils.toJsonObj(deleteNotificationString, ServiceCandidateDeleteNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateDeleteNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCandidateDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateDeleteNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCatalogBatchNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String batchNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCatalogBatchNotification serviceCatalogBatchNotification = JsonUtils.toJsonObj(batchNotificationString, ServiceCatalogBatchNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogBatchNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogBatchNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogBatchNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogBatchNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCatalogChangeNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String changeNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCatalogChangeNotification serviceCatalogChangeNotification = JsonUtils.toJsonObj(changeNotificationString, ServiceCatalogChangeNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogChangeNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogChangeNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCatalogCreateNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String createNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCatalogCreateNotification serviceCatalogCreateNotification = JsonUtils.toJsonObj(createNotificationString, ServiceCatalogCreateNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogCreateNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogCreateNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCatalogDeleteNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String deleteNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCatalogDeleteNotification serviceCatalogDeleteNotification = JsonUtils.toJsonObj(deleteNotificationString, ServiceCatalogDeleteNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogDeleteNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCatalogDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCatalogDeleteNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCategoryChangeNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String changeNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCategoryChangeNotification serviceCategoryChangeNotification = JsonUtils.toJsonObj(changeNotificationString, ServiceCategoryChangeNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryChangeNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryChangeNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCategoryCreateNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String createNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCategoryCreateNotification serviceCategoryCreateNotification = JsonUtils.toJsonObj(createNotificationString, ServiceCategoryCreateNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryCreateNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryCreateNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceCategoryDeleteNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String deleteNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceCategoryDeleteNotification serviceCategoryDeleteNotification = JsonUtils.toJsonObj(deleteNotificationString, ServiceCategoryDeleteNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryDeleteNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceCategoryDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCategoryDeleteNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceSpecificationChangeNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String changeNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceSpecificationChangeNotification serviceSpecificationChangeNotification = JsonUtils.toJsonObj(changeNotificationString, ServiceSpecificationChangeNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationChangeNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationChangeNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationChangeNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceSpecificationCreateNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String createNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceSpecificationCreateNotification serviceSpecificationCreateNotification = JsonUtils.toJsonObj(createNotificationString, ServiceSpecificationCreateNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationCreateNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationCreateNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationCreateNotification ) )) + .andExpect(status().is(501)); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListenToServiceSpecificationDeleteNotification() throws Exception { + + File resourceSpecFile = new File("src/test/resources/testServiceCandidateChangeNotification.json"); + InputStream in = new FileInputStream(resourceSpecFile); + String deleteNotificationString = IOUtils.toString(in, "UTF-8"); + ServiceSpecificationDeleteNotification serviceSpecificationDeleteNotification = JsonUtils.toJsonObj(deleteNotificationString, ServiceSpecificationDeleteNotification.class); + + // Test when providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationDeleteNotification ) )) + .andExpect(status().is(501)); + + // Test when not providing an "Accept" request header + mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/listener/serviceSpecificationDeleteNotification") + .with(SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationDeleteNotification ) )) + .andExpect(status().is(501)); + } +} \ No newline at end of file diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ServiceCandidateApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCandidateApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c8ed3f474d664be8bc421378cd331111f479c8b2 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCandidateApiControllerTest.java @@ -0,0 +1,201 @@ +package org.etsi.osl.services.api.scm633; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.List; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.minidev.json.JSONObject; +import org.apache.commons.io.IOUtils; + + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.etsi.osl.tmf.scm633.reposervices.CandidateRepoService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ServiceCandidateApiControllerTest { + + private static final int FIXED_BOOTSTRAPS_SPECS = 1; + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + CandidateRepoService candidateRepoService; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testCreateServiceCandidate() throws Exception { + + String response = createServiceCandidate(); + + ServiceCandidate responsesServiceCandidate = JsonUtils.toJsonObj(response, ServiceCandidate.class); + assertThat( responsesServiceCandidate.getDescription() ).isEqualTo( "A Test Service Candidate" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteServiceCandidate() throws Exception { + + String response = createServiceCandidate(); + + ServiceCandidate responsesServiceCandidate = JsonUtils.toJsonObj(response, ServiceCandidate.class); + String id = responsesServiceCandidate.getId(); + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/serviceCandidate/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + assertThat( candidateRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListServiceCandidate() throws Exception { + + String response = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceCandidate") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + List serviceCandidateList= objectMapper.readValue(response, new TypeReference>() {}); + + assertThat(serviceCandidateList.size()).isEqualTo(candidateRepoService.findAll().size()); + + String id = candidateRepoService.findAll().get(0).getId(); + + boolean idExists = false; + for (ServiceCandidate sc : serviceCandidateList) { + if ( sc.getId().equals( id ) ) { + idExists= true; + } + } + assertThat( idExists ).isTrue(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testPatchServiceCandidate() throws Exception { + + String response = createServiceCandidate(); + + ServiceCandidate responsesServiceCandidate = JsonUtils.toJsonObj(response, ServiceCandidate.class); + String id = responsesServiceCandidate.getId(); + + JSONObject obj = JsonUtils.toJsonObj(response, JSONObject.class); + obj.remove("uuid"); + obj.remove("id"); + obj.remove("lastUpdate"); + response = JsonUtils.toJsonString(obj); + + ServiceCandidateUpdate serviceCandidateUpdate = JsonUtils.toJsonObj(response, ServiceCandidateUpdate.class); + serviceCandidateUpdate.setDescription("Test Service Candidate new description"); + + String response2 = mvc.perform(MockMvcRequestBuilders.patch("/serviceCatalogManagement/v4/serviceCandidate/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidateUpdate ) )) + .andExpect(status().isOk() ) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("description", is("Test Service Candidate new description"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + ServiceCandidate responsesServiceCandidate2 = JsonUtils.toJsonObj(response2, ServiceCandidate.class); + assertThat( responsesServiceCandidate2.getDescription() ).isEqualTo( "Test Service Candidate new description" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveServiceCandidate() throws Exception { + + String response = createServiceCandidate(); + + ServiceCandidate responsesServiceCandidate = JsonUtils.toJsonObj(response, ServiceCandidate.class); + String id = responsesServiceCandidate.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceCandidate/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + ServiceCandidate responsesServiceCandidate2 = JsonUtils.toJsonObj(response2, ServiceCandidate.class); + assertThat( responsesServiceCandidate2.getDescription() ).isEqualTo( "A Test Service Candidate" ); + } + + private String createServiceCandidate() throws Exception{ + File resourceSpecFile = new File("src/test/resources/testServiceCandidate.txt"); + InputStream in = new FileInputStream(resourceSpecFile); + String serviceCandidateString = IOUtils.toString(in, "UTF-8"); + ServiceCandidateCreate serviceCandidate = JsonUtils.toJsonObj(serviceCandidateString, ServiceCandidateCreate.class); + + assertThat( candidateRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS); + + String response = mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/serviceCandidate") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceCandidate ) )) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("description", is("A Test Service Candidate"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( candidateRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1 ); + return response; + } +} diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ServiceCatalogApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCatalogApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..92b48d54028defe00acaa5f26c1f1f55f3f38219 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCatalogApiControllerTest.java @@ -0,0 +1,186 @@ +package org.etsi.osl.services.api.scm633; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import net.minidev.json.JSONObject; +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.rcm634.model.ResourceCatalog; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.etsi.osl.tmf.scm633.reposervices.CatalogRepoService; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ServiceCatalogApiControllerTest { + + private static final int FIXED_BOOTSTRAPS_CATALOGS = 1; + + @Autowired + private MockMvc mvc; + + @Autowired + private WebApplicationContext context; + + @Autowired + CatalogRepoService catalogRepoService; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteServiceCatalog() throws Exception { + + String response = createServiceCatalog(); + + ResourceCatalog responsesCatalog = JsonUtils.toJsonObj(response, ResourceCatalog.class); + assertThat( responsesCatalog.getName() ).isEqualTo( "Test Catalog" ); + + String id = responsesCatalog.getId(); + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/serviceCatalog/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + assertThat( catalogRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_CATALOGS ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListServiceCatalog() throws Exception { + + createServiceCatalog(); + + String response = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceCatalog") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + List serviceCatalogList = JsonUtils.toJsonObj(response, ArrayList.class); + + assertThat(serviceCatalogList.size()).isEqualTo(FIXED_BOOTSTRAPS_CATALOGS + 1); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testPatchServiceCatalog() throws Exception { + + String response = createServiceCatalog(); + + ServiceCatalog responsesServiceCatalog = JsonUtils.toJsonObj(response, ServiceCatalog.class); + String id = responsesServiceCatalog.getId(); + + JSONObject obj = JsonUtils.toJsonObj(response, JSONObject.class); + obj.remove("uuid"); + obj.remove("id"); + obj.remove("lastUpdate"); + response = JsonUtils.toJsonString(obj); + + ServiceCatalogUpdate ServiceCatalogUpdate = JsonUtils.toJsonObj(response, ServiceCatalogUpdate.class); + ServiceCatalogUpdate.setName( "Test Service Catalog new name" ); + ServiceCatalogUpdate.setVersion("2.x"); + + String response2 = mvc.perform(MockMvcRequestBuilders.patch("/serviceCatalogManagement/v4/serviceCatalog/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( ServiceCatalogUpdate ) )) + .andExpect(status().isOk() ) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("name", is("Test Service Catalog new name"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + ServiceCatalog responsesServiceCatalog2 = JsonUtils.toJsonObj(response2, ServiceCatalog.class); + assertThat( responsesServiceCatalog2.getName() ).isEqualTo( "Test Service Catalog new name" ); + assertThat( responsesServiceCatalog2.getVersion() ).isEqualTo( "2.x" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveServiceCatalog() throws Exception { + + String response = createServiceCatalog(); + + ServiceCatalog responsesServiceCatalog = JsonUtils.toJsonObj(response, ServiceCatalog.class); + String id = responsesServiceCatalog.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceCatalog/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + ServiceCatalog responsesServiceCatalog2 = JsonUtils.toJsonObj(response2, ServiceCatalog.class); + assertThat( responsesServiceCatalog2.getName() ).isEqualTo( "Test Catalog" ); + assertThat( responsesServiceCatalog2.getVersion() ).isEqualTo( "1.8" ); + } + + private String createServiceCatalog() throws Exception{ + assertThat( catalogRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_CATALOGS ); + + File scatalog = new File( "src/test/resources/testResourceCatalog.txt" ); + InputStream in = new FileInputStream( scatalog ); + String resvxf = IOUtils.toString(in, "UTF-8"); + + ServiceCatalogCreate scc = JsonUtils.toJsonObj( resvxf, ServiceCatalogCreate.class); + + String response = mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/serviceCatalog") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( scc ) )) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("name", is("Test Catalog"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( catalogRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_CATALOGS + 1 ); + + return response; + } +} diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ServiceCategoryApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCategoryApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..865ca45fc3cb0b2f30ac468a7ea1fbbe92f92606 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ServiceCategoryApiControllerTest.java @@ -0,0 +1,85 @@ +package org.etsi.osl.services.api.scm633; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.List; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.scm633.model.*; + +import org.etsi.osl.tmf.scm633.reposervices.CategoryRepoService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") + +public class ServiceCategoryApiControllerTest { + + @Autowired + private MockMvc mvc; + + @Autowired + CategoryRepoService categoryRepoService; + + @Autowired + private WebApplicationContext context; + + @Autowired + private ObjectMapper objectMapper; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListServiceCategory() throws Exception { + + String response = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceCategory") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + List serviceCategoryList = objectMapper.readValue(response, new TypeReference>() {}); + + assertThat(serviceCategoryList.size()).isEqualTo(categoryRepoService.findAll().size()); + String id = categoryRepoService.findAll().get(0).getId(); + + boolean idExists = false; + for (ServiceCategory ss : serviceCategoryList) { + if ( ss.getId().equals( id ) ) { + idExists= true; + } + } + assertThat( idExists ).isTrue(); + } +} diff --git a/src/test/java/org/etsi/osl/services/api/scm633/ServiceSpecificationApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/scm633/ServiceSpecificationApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e5aa51e2679c9804c6b0b34e2a7703b5a0d39abb --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/scm633/ServiceSpecificationApiControllerTest.java @@ -0,0 +1,425 @@ +package org.etsi.osl.services.api.scm633; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.*; +import java.util.List; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.minidev.json.JSONObject; +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.common.model.Attachment; +import org.etsi.osl.tmf.rcm634.model.*; +import org.etsi.osl.tmf.rcm634.reposervices.ResourceSpecificationRepoService; +import org.etsi.osl.tmf.scm633.model.*; +import org.etsi.osl.tmf.JsonUtils; + +import org.etsi.osl.tmf.scm633.reposervices.ServiceSpecificationRepoService; +import org.etsi.osl.tmf.stm653.model.ServiceTestSpecification; +import org.etsi.osl.tmf.stm653.model.ServiceTestSpecificationCreate; +import org.etsi.osl.tmf.stm653.reposervices.ServiceTestSpecificationRepoService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK , classes = OpenAPISpringBoot.class) +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ServiceSpecificationApiControllerTest { + + private static final int FIXED_BOOTSTRAPS_SPECS = 1; + + @Autowired + private MockMvc mvc; + + @Autowired + ServiceTestSpecificationRepoService aServiceTestSpecRpoService; + + @Autowired + ResourceSpecificationRepoService resourceSpecificationRepoService; + + @Autowired + private WebApplicationContext context; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + ServiceSpecificationRepoService specRepoService; + + @Before + public void setup() { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteServiceSpecification() throws Exception { + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS ); + String response = createServiceSpecification(); + + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String id = responsesSpec.getId(); + + mvc.perform(MockMvcRequestBuilders.delete("/serviceCatalogManagement/v4/serviceSpecification/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListServiceSpecification() throws Exception { + + String response = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification") + + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + List serviceSpecificationList = objectMapper.readValue(response, new TypeReference>() {}); + + assertThat(serviceSpecificationList.size()).isEqualTo(specRepoService.findAll().size()); + String id = specRepoService.findAll().get(0).getId(); + + boolean idExists = false; + for (ServiceSpecification ss : serviceSpecificationList) { + if ( ss.getId().equals( id ) ) { + idExists= true; + } + } + assertThat( idExists ).isTrue(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testPatchServiceSpecification() throws Exception { + + String response = createServiceSpecification(); + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1); + + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String id = responsesSpec.getId(); + + JSONObject obj = JsonUtils.toJsonObj(response, JSONObject.class); + obj.remove("uuid"); + obj.remove("id"); + obj.remove("lastUpdate"); + response = JsonUtils.toJsonString(obj); + + ServiceSpecificationUpdate ServiceSpecUpdate = JsonUtils.toJsonObj(response, ServiceSpecificationUpdate.class); + ServiceSpecUpdate.setName( "Test Spec new name" ); + ServiceSpecUpdate.setVersion("2.x"); + + String response2 = mvc.perform(MockMvcRequestBuilders.patch("/serviceCatalogManagement/v4/serviceSpecification/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( ServiceSpecUpdate ) )) + .andExpect(status().isOk() ) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("name", is("Test Spec new name"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + ServiceSpecification responsesServiceSpec2 = JsonUtils.toJsonObj(response2, ServiceSpecification.class); + assertThat( responsesServiceSpec2.getName() ).isEqualTo( "Test Spec new name" ); + assertThat( responsesServiceSpec2.getVersion() ).isEqualTo( "2.x" ); + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveServiceSpecification() throws Exception { + + String response = createServiceSpecification(); + + ServiceSpecification responsesServiceSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String id = responsesServiceSpec.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + ServiceSpecification responsesServiceSpec2 = JsonUtils.toJsonObj(response2, ServiceSpecification.class); + assertThat( responsesServiceSpec2.getName() ).isEqualTo( "Test Spec" ); + assertThat( responsesServiceSpec2.getVersion() ).isEqualTo( "1.8.0" ); + } + + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetAttachment() throws Exception { + + // Create a Service Specification + String response = createServiceSpecification(); + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String specId = responsesSpec.getId(); + + // Test method for non-existing logo attachment + String attId = "logo"; + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + specId + "/attachment/" + attId) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound() ) + .andReturn().getResponse().getContentAsString(); + + // Test method for non-existing non-logo attachment + attId = "random"; + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + specId + "/attachment/" + attId) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNotFound() ) + .andReturn().getResponse().getContentAsString(); + + + // Test method for existing attachment + + // Add a new attachment to the Service Specification + String response2 = createAttachmentAndAddToServiceSpecification(specId); + Attachment attachment = JsonUtils.toJsonObj(response2, Attachment.class); + attId = attachment.getId(); + String attName = attachment.getName(); + String attMimeType = attachment.getMimeType(); + + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + specId + "/attachment/" + attId) + ) + .andExpect(content().contentTypeCompatibleWith(MediaType.ALL_VALUE)) + .andExpect(status().isOk() ) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache")) + .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + attName)) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, attMimeType)) + .andReturn().getResponse().getContentAsString(); + } + + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetAttachmentWithFilename() throws Exception { + + // Create a Service Specification + String response = createServiceSpecification(); + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String specId = responsesSpec.getId(); + + String response2 = createAttachmentAndAddToServiceSpecification(specId); + Attachment attachment = JsonUtils.toJsonObj(response2, Attachment.class); + String attId = attachment.getId(); + String attName = attachment.getName(); + String attMimeType = attachment.getMimeType(); + + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + specId + "/attachment/" + attId + "/" + attName) + ) + .andExpect(content().contentTypeCompatibleWith(MediaType.ALL_VALUE)) + .andExpect(status().isOk() ) + .andExpect(header().string(HttpHeaders.CACHE_CONTROL, "no-cache")) + .andExpect(header().string(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + attName)) + .andExpect(header().string(HttpHeaders.CONTENT_TYPE, attMimeType)) + .andReturn().getResponse().getContentAsString(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveServiceSpecificationDescriptor() throws Exception { + + // Test a non-existing spec + mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + "fakeId" + "/sd") + ) + .andExpect(status().isNotFound()) + .andReturn().getResponse().getContentAsString(); + } + + + @WithMockUser(username = "osadmin", roles = { "ADMIN","USER" }) + @Test + public void testSpecFromTestSpec() throws Exception { + + // Creeate a Test Spec + File sspec = new File( "src/test/resources/testServiceTestSpec.json" ); + InputStream in = new FileInputStream( sspec ); + String sspectext = IOUtils.toString(in, "UTF-8"); + ServiceTestSpecificationCreate spec = JsonUtils.toJsonObj( sspectext, ServiceTestSpecificationCreate.class); + + int originalSize = aServiceTestSpecRpoService.findAll().size(); + + String response = mvc.perform(MockMvcRequestBuilders.post("/serviceTestManagement/v4/serviceTestSpecification") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( spec ) )) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("name", is("A test name"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + + assertThat( aServiceTestSpecRpoService.findAll().size() ).isEqualTo( originalSize + 1 ); + ServiceTestSpecification sts = JsonUtils.toJsonObj(response, ServiceTestSpecification.class); + assertThat(sts.getName()).isEqualTo("A test name"); + String stsId = sts.getId(); + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS); + + // Create a Service Spec from the Test Spec + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/specFromTestSpec/" + stsId) + .with( SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1 ); + + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response2, ServiceSpecification.class); + assertThat( responsesSpec.getName() ).isEqualTo( "A test name" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetImageSpecificationRelationshipGraph() throws Exception { + + // Create a Service Specification + String response = createServiceSpecification(); + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + String specId = responsesSpec.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/" + specId + "/relationship_graph") + ) + .andExpect(status().is(302) ) + .andReturn().getResponse().getRedirectedUrl(); + + assertThat( response2 ).contains("/blockdiag/svg/"); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN"}) + @Test + public void testSpecFromResourceSpec() throws Exception { + + File rspec = new File( "src/test/resources/testResourceSpec.json" ); + InputStream in = new FileInputStream( rspec ); + String rspectext = IOUtils.toString(in, "UTF-8"); + ResourceSpecificationCreate rspeccr = JsonUtils.toJsonObj( rspectext, ResourceSpecificationCreate.class); + + int originalSize = resourceSpecificationRepoService.findAll().size(); + + String responseSpec = mvc.perform(MockMvcRequestBuilders.post( "/resourceCatalogManagement/v4/resourceSpecification" ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( rspeccr ) )) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( resourceSpecificationRepoService.findAll().size() ).isEqualTo( originalSize + 1 ); + ResourceSpecification responsesSpec1 = JsonUtils.toJsonObj(responseSpec, PhysicalResourceSpecification.class); + assertThat(responsesSpec1.getName()).isEqualTo("Test Resource Spec"); + String rSpecId = responsesSpec1.getId(); + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceCatalogManagement/v4/serviceSpecification/specFromResourceSpec/" + rSpecId) + .with( SecurityMockMvcRequestPostProcessors.csrf())) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1 ); + + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response2, ServiceSpecification.class); + assertThat( responsesSpec.getName() ).isEqualTo( "Test Resource Spec" ); + } + + + private String createServiceSpecification() throws Exception{ + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS ); + + File sspec = new File( "src/test/resources/testServiceSpec.json" ); + InputStream in = new FileInputStream( sspec ); + String sspectext = IOUtils.toString(in, "UTF-8"); + ServiceSpecificationCreate serviceSpecificationCreate = JsonUtils.toJsonObj( sspectext, ServiceSpecificationCreate.class); + + String response = mvc.perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/serviceSpecification") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( serviceSpecificationCreate ) )) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + assertThat( specRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1 ); + + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + assertThat( responsesSpec.getName() ).isEqualTo( "Test Spec" ); + + return response; + } + + private String createAttachmentAndAddToServiceSpecification(String serviceSpecId) throws Exception { + + Attachment att = new Attachment(); + + File gz = new File( "src/test/resources/cirros_vnf.tar.gz" ); + InputStream ing = new FileInputStream( gz ); + MockMultipartFile prodFile = new MockMultipartFile("afile", "cirros_vnf.tar.gz", "application/x-gzip", IOUtils.toByteArray(ing)); + + String response = mvc.perform(MockMvcRequestBuilders + .multipart("/serviceCatalogManagement/v4/serviceSpecification/" + serviceSpecId + "/attachment" ) + .file(prodFile) + .param("attachment", JsonUtils.toJsonString(att)) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + ) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("name", is("cirros_vnf.tar.gz"))) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Attachment attachment = JsonUtils.toJsonObj( response, Attachment.class); + + assertThat(attachment.getName()).isEqualTo("cirros_vnf.tar.gz"); + assertThat(attachment.getUrl()).contains(serviceSpecId); + + return response; + } +} diff --git a/src/test/java/org/etsi/osl/services/api/so641/CommonTests.java b/src/test/java/org/etsi/osl/services/api/so641/CommonTests.java new file mode 100644 index 0000000000000000000000000000000000000000..2b935d8e4b2986b2fd1ce6d5e3bff654980dcef7 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/so641/CommonTests.java @@ -0,0 +1,142 @@ +/*- + * ========================LICENSE_START================================= + * org.etsi.osl.tmf.api + * %% + * Copyright (C) 2019 - 2024 openslice.io + * %% + * 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.etsi.osl.services.api.so641; + +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.etsi.osl.tmf.so641.api.*; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockHttpServletRequest; + +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class CommonTests { + + @Test + public void testApiException() { + int errorCode = 404; + String errorMessage = "Not Found"; + + ApiException exception = new ApiException(errorCode, errorMessage); + + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testApiOriginFilter() throws IOException, ServletException { + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + FilterChain chain = mock(FilterChain.class); + + ApiOriginFilter filter = new ApiOriginFilter(); + filter.doFilter(request, response, chain); + + verify(response).addHeader("Access-Control-Allow-Origin", "*"); + verify(response).addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + verify(response).addHeader("Access-Control-Allow-Headers", "Content-Type"); + verify(chain).doFilter(request, response); + } + + @Test + public void testApiResponseMessage() { + int[] codes = {ApiResponseMessage.ERROR, ApiResponseMessage.WARNING, ApiResponseMessage.INFO, ApiResponseMessage.OK, ApiResponseMessage.TOO_BUSY, 6}; + + String[] types = {"error", "warning", "info", "ok", "too busy", "unknown"}; + + String[] messages = {"An error occured", "This is a warning", "Given info", "ok", "System is too busy", "unknown code"}; + + for (int i = 0; i < codes.length; i++) { + int code = codes[i]; + String type = types[i]; + String message = messages[i]; + + ApiResponseMessage responseMessage = new ApiResponseMessage(code, message); + + assertEquals(message, responseMessage.getMessage()); + assertEquals(code, responseMessage.getCode()); + assertEquals(type, responseMessage.getType()); + + } + + ApiResponseMessage responseMessage = new ApiResponseMessage(); + responseMessage.setMessage("Error"); + assertEquals("Error", responseMessage.getMessage()); + responseMessage.setType("ok"); + assertEquals("ok", responseMessage.getType()); + responseMessage.setCode(ApiResponseMessage.OK); + assertEquals(ApiResponseMessage.OK, responseMessage.getCode()); + } + + @Test + public void testHubApiController() { + ObjectMapper objectMapper = new ObjectMapper(); + HttpServletRequest request = new MockHttpServletRequest(); + + HubApiController controller = new HubApiController(objectMapper, request); + + Optional returnedObjectMapper = controller.getObjectMapper(); + Optional returnedRequest = controller.getRequest(); + + assertTrue(returnedObjectMapper.isPresent()); + assertTrue(returnedRequest.isPresent()); + + assertEquals(objectMapper, returnedObjectMapper.get()); + assertEquals(request, returnedRequest.get()); + } + + @Test + public void testListenerApiController() { + ObjectMapper objectMapper = new ObjectMapper(); + HttpServletRequest request = new MockHttpServletRequest(); + + ListenerApiController controller = new ListenerApiController(objectMapper, request); + + Optional returnedObjectMapper = controller.getObjectMapper(); + Optional returnedRequest = controller.getRequest(); + + assertTrue(returnedObjectMapper.isPresent()); + assertTrue(returnedRequest.isPresent()); + + assertEquals(objectMapper, returnedObjectMapper.get()); + assertEquals(request, returnedRequest.get()); + } + + @Test + public void testNotFoundException() { + int errorCode = 404; + String errorMessage = "Not Found"; + + NotFoundException exception = new NotFoundException(errorCode, errorMessage); + + assertEquals(errorMessage, exception.getMessage()); + } + +} + diff --git a/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderApiControllerTest.java b/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderApiControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3af3d05b4e6b3c43bd2581ad06ea9c66931a3f67 --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderApiControllerTest.java @@ -0,0 +1,281 @@ +package org.etsi.osl.services.api.so641; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.Optional; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.common.model.service.Note; +import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef; +import org.etsi.osl.tmf.scm633.model.ServiceSpecification; +import org.etsi.osl.tmf.scm633.model.ServiceSpecificationCreate; +import org.etsi.osl.tmf.so641.model.*; +import org.etsi.osl.tmf.so641.reposervices.ServiceOrderRepoService; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.MOCK, + classes = OpenAPISpringBoot.class +) +//@AutoConfigureTestDatabase //this automatically uses h2 +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ServiceOrderApiControllerTest { + + private static final int FIXED_BOOTSTRAPS_SPECS = 0; + + @Autowired + private MockMvc mvc; + + @Autowired + ServiceOrderRepoService serviceOrderRepoService; + + @Autowired + private WebApplicationContext context; + + @Autowired + private ObjectMapper objectMapper; + + @Before + public void setup() throws Exception { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testCreateServiceOrder() throws Exception { + + String response = createServiceOrder(); + + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + assertThat( responsesServiceOrder.getDescription() ).isEqualTo( "A Test Service Order" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testDeleteServiceOrder() throws Exception { + + String response = createServiceOrder(); + + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String id = responsesServiceOrder.getId(); + + mvc.perform(MockMvcRequestBuilders.delete("/serviceOrdering/v4/serviceOrder/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + assertThat( serviceOrderRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testListServiceOrder() throws Exception { + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceOrdering/v4/serviceOrder") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + List serviceOrderList= objectMapper.readValue(response2, new TypeReference>() {}); + assertThat(serviceOrderList.size()).isEqualTo(serviceOrderRepoService.findAll().size()); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testPatchServiceOrder() throws Exception { + + String response = createServiceOrder(); + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + + ServiceOrderUpdate servOrderUpd = new ServiceOrderUpdate(); + servOrderUpd.setState(ServiceOrderStateType.COMPLETED); + servOrderUpd.setCategory("New Test Category"); + servOrderUpd.setDescription("New Test Description"); + + String response2 = mvc.perform(MockMvcRequestBuilders.patch("/serviceOrdering/v4/serviceOrder/" + soId) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content( JsonUtils.toJson( servOrderUpd ) )) + .andExpect(status().isOk() ) + .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andReturn().getResponse().getContentAsString(); + + ServiceOrder responsesServiceOrder2 = JsonUtils.toJsonObj(response2, ServiceOrder.class); + assertThat(responsesServiceOrder2.getState().toString()).isEqualTo("COMPLETED"); + assertThat(responsesServiceOrder2.getDescription()).isEqualTo("New Test Description"); + assertThat(responsesServiceOrder2.getCategory()).isEqualTo("New Test Category"); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testRetrieveServiceOrder() throws Exception { + + String response = createServiceOrder(); + + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String id = responsesServiceOrder.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceOrdering/v4/serviceOrder/" + id ) + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk() ) + .andReturn().getResponse().getContentAsString(); + + ServiceOrder responsesServiceOrder2 = JsonUtils.toJsonObj(response2, ServiceOrder.class); + assertThat( responsesServiceOrder2.getDescription() ).isEqualTo( "A Test Service Order" ); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetImageServiceOrderItemRelationshipGraph() throws Exception { + + // Create a Service Order + String response = createServiceOrder(); + ServiceOrder responsesOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String orderId = responsesOrder.getId(); + + String soiId = ""; + Set serviceOrderItemSet = responsesOrder.getOrderItem(); + + // Find the first element if present + Optional optionalFirstServiceOrderItem = serviceOrderItemSet.stream().findFirst(); + + if (optionalFirstServiceOrderItem.isPresent()) { + soiId = optionalFirstServiceOrderItem.get().getId(); + } + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceOrdering/v4/serviceOrder/" + orderId + "/item/" + soiId + "/relationship_graph") + ) + .andExpect(status().is(302) ) + .andReturn().getResponse().getRedirectedUrl(); + + assertThat( response2 ).contains("/blockdiag/svg/"); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetImageServiceOrderNotesGraph() throws Exception { + + // Create a Service Order + String response = createServiceOrder(); + ServiceOrder responsesOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String orderId = responsesOrder.getId(); + + String response2 = mvc.perform(MockMvcRequestBuilders.get("/serviceOrdering/v4/serviceOrder/" + orderId + "/notes_graph") + ) + .andExpect(status().is(302) ) + .andReturn().getResponse().getRedirectedUrl(); + + assertThat( response2 ).contains("/actdiag/svg/"); + } + + + private String createServiceOrder() throws Exception { + + assertThat( serviceOrderRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS); + + File sspec = new File("src/test/resources/testServiceSpec.json"); + InputStream in = new FileInputStream(sspec); + String sspectext = IOUtils.toString(in, "UTF-8"); + + ServiceSpecificationCreate sspeccr = JsonUtils.toJsonObj(sspectext, ServiceSpecificationCreate.class); + sspeccr.setName("Spec1"); + ServiceSpecification responsesSpec = createServiceSpec( sspeccr); + + ServiceOrderCreate serviceOrder = new ServiceOrderCreate(); + serviceOrder.setCategory("Test Category"); + serviceOrder.setDescription("A Test Service Order"); + serviceOrder.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + serviceOrder.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + + ServiceOrderItem soi = new ServiceOrderItem(); + serviceOrder.getOrderItem().add(soi); + soi.setState(ServiceOrderStateType.ACKNOWLEDGED); + + ServiceRestriction serviceRestriction = new ServiceRestriction(); + ServiceSpecificationRef aServiceSpecificationRef = new ServiceSpecificationRef(); + aServiceSpecificationRef.setId(responsesSpec.getId()); + aServiceSpecificationRef.setName(responsesSpec.getName()); + + serviceRestriction.setServiceSpecification(aServiceSpecificationRef); + serviceRestriction.setName("aServiceRestriction"); + soi.setService(serviceRestriction); + + String response = mvc + .perform(MockMvcRequestBuilders.post("/serviceOrdering/v4/serviceOrder") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(serviceOrder))) + .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + ServiceOrder responseSO = JsonUtils.toJsonObj(response, ServiceOrder.class); + + assertThat( serviceOrderRepoService.findAll().size() ).isEqualTo( FIXED_BOOTSTRAPS_SPECS + 1 ); + assertThat(responseSO.getCategory()).isEqualTo("Test Category"); + assertThat(responseSO.getDescription()).isEqualTo("A Test Service Order"); + + return response; + + } + + + private ServiceSpecification createServiceSpec( ServiceSpecificationCreate serviceSpecificationCreate) throws Exception { + + String response = mvc + .perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/serviceSpecification") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(serviceSpecificationCreate))) + .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + + return responsesSpec; + } +} diff --git a/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderRepoServiceTest.java b/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderRepoServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2cc5b0e9f819bc1a94867eeeca9afb03773014bf --- /dev/null +++ b/src/test/java/org/etsi/osl/services/api/so641/ServiceOrderRepoServiceTest.java @@ -0,0 +1,285 @@ +package org.etsi.osl.services.api.so641; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.*; + +import org.apache.commons.io.IOUtils; + +import org.etsi.osl.tmf.OpenAPISpringBoot; +import org.etsi.osl.tmf.common.model.service.Note; +import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef; +import org.etsi.osl.tmf.scm633.model.ServiceSpecification; +import org.etsi.osl.tmf.scm633.model.ServiceSpecificationCreate; +import org.etsi.osl.tmf.so641.model.*; +import org.etsi.osl.tmf.so641.reposervices.ServiceOrderRepoService; +import org.etsi.osl.tmf.JsonUtils; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.context.WebApplicationContext; + +@RunWith(SpringRunner.class) +@Transactional +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.MOCK, + classes = OpenAPISpringBoot.class +) +//@AutoConfigureTestDatabase //this automatically uses h2 +@AutoConfigureMockMvc +@ActiveProfiles("testing") +public class ServiceOrderRepoServiceTest { + + @Autowired + private MockMvc mvc; + + @Autowired + ServiceOrderRepoService serviceOrderRepoService; + + @Autowired + private WebApplicationContext context; + + @Before + public void setup() throws Exception { + mvc = MockMvcBuilders + .webAppContextSetup(context) + .apply(springSecurity()) + .build(); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testFindAllParams() throws Exception { + + String response = createServiceOrder(); + + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + String state = responsesServiceOrder.getState().toString(); + + // Test with not null params + Map params = new HashMap<>(); + params.put("state", state); + + List serviceOrderList = serviceOrderRepoService.findAllParams(params); + + boolean idExists = false; + for (ServiceOrder so : serviceOrderList) { + if ( so.getId().equals( soId ) ) { + idExists= true; + } + } + assertThat( idExists ).isTrue(); + + // Test with null params + Map paramsEmpty = new HashMap<>(); + List serviceOrderListEmptyParams = serviceOrderRepoService.findAllParams(paramsEmpty); + + boolean idExistsEmptyParams = false; + for (ServiceOrder so : serviceOrderListEmptyParams) { + if ( so.getId().equals( soId ) ) { + idExistsEmptyParams= true; + } + } + assertThat( idExistsEmptyParams ).isTrue(); + assertThat(serviceOrderListEmptyParams.size()).isEqualTo(serviceOrderRepoService.findAll().size()); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testFindAllParamsJsonOrderIDs() throws Exception { + + String response = createServiceOrder(); + String response2 = createServiceOrder(); + + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + + ServiceOrder responsesServiceOrder2 = JsonUtils.toJsonObj(response2, ServiceOrder.class); + String soId2 = responsesServiceOrder2.getId(); + + String state = responsesServiceOrder.getState().toString(); + Map params = new HashMap<>(); + params.put("state", state); + + String soIds = serviceOrderRepoService.findAllParamsJsonOrderIDs(params); + assertThat(soIds).contains(soId); + assertThat(soIds).contains(soId2); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testUpdateServiceOrder() throws Exception { + + String response = createServiceOrder(); + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + + ServiceOrderUpdate servOrderUpd = new ServiceOrderUpdate(); + servOrderUpd.setExpectedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + Note en = new Note(); + en.text("test note2"); + servOrderUpd.addNoteItem(en); + servOrderUpd.addOrderItemItem((new ArrayList<>(responsesServiceOrder.getOrderItem())).get(0)); + servOrderUpd.getOrderItem().get(0).setState(ServiceOrderStateType.INPROGRESS); + servOrderUpd.setState(ServiceOrderStateType.COMPLETED); + servOrderUpd.setCategory("New Test Category"); + servOrderUpd.setDescription("New Test Description"); + servOrderUpd.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + servOrderUpd.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + servOrderUpd.setStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + + List serviceOrderRelationshipList = new ArrayList<>(); + serviceOrderRelationshipList.add(new ServiceOrderRelationship()); + servOrderUpd.setOrderRelationship(serviceOrderRelationshipList); + + ServiceOrder responseSOUpd = serviceOrderRepoService.updateServiceOrder(soId, servOrderUpd); + assertThat(responseSOUpd.getState().toString()).isEqualTo("COMPLETED"); + assertThat(responseSOUpd.getDescription()).isEqualTo("New Test Description"); + } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetServiceOrderEagerAsString() throws Exception { + + String response = createServiceOrder(); + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + + String eager = serviceOrderRepoService.getServiceOrderEagerAsString(soId); + ServiceOrder eagerServiceOrder = JsonUtils.toJsonObj(eager, ServiceOrder.class); + assertThat(eagerServiceOrder.getDescription()).isEqualTo("A Test Service Order"); + assertThat(eagerServiceOrder.getCategory()).isEqualTo("Test Category"); + assertThat(eagerServiceOrder.getId()).isEqualTo(soId); + } + + +// // This test causes "HikariPool-1 - Connection is not available, request timed out after 30000ms" error for other tests +// @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) +// @Test +// public void testAddServiceOrderReturnEager() throws Exception { +// +// ServiceOrderCreate serviceOrder = new ServiceOrderCreate(); +// serviceOrder.setCategory("Test Category"); +// serviceOrder.setDescription("A Test Service Order"); +// serviceOrder.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); +// serviceOrder.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); +// +// Note noteItem = new Note(); +// noteItem.text("Test note"); +// serviceOrder.addNoteItem(noteItem); +// +// ServiceOrderItem soi = new ServiceOrderItem(); +// serviceOrder.getOrderItem().add(soi); +// soi.setState(ServiceOrderStateType.ACKNOWLEDGED); +// +// +// String eager = serviceOrderRepoService.addServiceOrderReturnEager(serviceOrder); +// ServiceOrder eagerServiceOrder = JsonUtils.toJsonObj(eager, ServiceOrder.class); +// assertThat(eagerServiceOrder.getDescription()).isEqualTo("A Test Service Order"); +// assertThat(eagerServiceOrder.getCategory()).isEqualTo("Test Category"); +// } + + + @WithMockUser(username="osadmin", roles = {"ADMIN","USER"}) + @Test + public void testGetImageServiceOrderItemRelationshipGraph() throws Exception { + + String response = createServiceOrder(); + ServiceOrder responsesServiceOrder = JsonUtils.toJsonObj(response, ServiceOrder.class); + String soId = responsesServiceOrder.getId(); + Set serviceOrderItemSet = responsesServiceOrder.getOrderItem(); + + for (ServiceOrderItem soi: serviceOrderItemSet) { + String responseGraph = serviceOrderRepoService.getImageServiceOrderItemRelationshipGraph(soId, soi.getId()); + assertThat( responseGraph ).isNotNull(); + } + } + + + private String createServiceOrder() throws Exception { + + int currSize = serviceOrderRepoService.findAll().size(); + + File sspec = new File("src/test/resources/testServiceSpec.json"); + InputStream in = new FileInputStream(sspec); + String sspectext = IOUtils.toString(in, "UTF-8"); + + ServiceSpecificationCreate sspeccr = JsonUtils.toJsonObj(sspectext, ServiceSpecificationCreate.class); + sspeccr.setName("Spec1"); + ServiceSpecification responsesSpec = createServiceSpec( sspeccr); + + ServiceOrderCreate serviceOrder = new ServiceOrderCreate(); + serviceOrder.setCategory("Test Category"); + serviceOrder.setDescription("A Test Service Order"); + serviceOrder.setRequestedStartDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + serviceOrder.setRequestedCompletionDate(OffsetDateTime.now(ZoneOffset.UTC).toString()); + + ServiceOrderItem soi = new ServiceOrderItem(); + serviceOrder.getOrderItem().add(soi); + soi.setState(ServiceOrderStateType.ACKNOWLEDGED); + + ServiceRestriction serviceRestriction = new ServiceRestriction(); + ServiceSpecificationRef aServiceSpecificationRef = new ServiceSpecificationRef(); + aServiceSpecificationRef.setId(responsesSpec.getId()); + aServiceSpecificationRef.setName(responsesSpec.getName()); + + serviceRestriction.setServiceSpecification(aServiceSpecificationRef); + serviceRestriction.setName("aServiceRestriction"); + soi.setService(serviceRestriction); + + String response = mvc + .perform(MockMvcRequestBuilders.post("/serviceOrdering/v4/serviceOrder") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(serviceOrder))) + .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + ServiceOrder responseSO = JsonUtils.toJsonObj(response, ServiceOrder.class); + + assertThat( serviceOrderRepoService.findAll().size() ).isEqualTo( currSize + 1 ); + assertThat(responseSO.getCategory()).isEqualTo("Test Category"); + assertThat(responseSO.getDescription()).isEqualTo("A Test Service Order"); + + return response; + + } + + + private ServiceSpecification createServiceSpec( ServiceSpecificationCreate serviceSpecificationCreate) throws Exception { + + String response = mvc + .perform(MockMvcRequestBuilders.post("/serviceCatalogManagement/v4/serviceSpecification") + .with( SecurityMockMvcRequestPostProcessors.csrf()) + .contentType(MediaType.APPLICATION_JSON).content(JsonUtils.toJson(serviceSpecificationCreate))) + .andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + ServiceSpecification responsesSpec = JsonUtils.toJsonObj(response, ServiceSpecification.class); + + return responsesSpec; + } +} diff --git a/src/test/resources/testEventSubscriptionInput.json b/src/test/resources/testEventSubscriptionInput.json new file mode 100644 index 0000000000000000000000000000000000000000..bccdb0cdb7f50e92a7ac57abcd18cbe28d5be28e --- /dev/null +++ b/src/test/resources/testEventSubscriptionInput.json @@ -0,0 +1,3 @@ +{ + "query": "test" +} \ No newline at end of file diff --git a/src/test/resources/testExportJob.json b/src/test/resources/testExportJob.json new file mode 100644 index 0000000000000000000000000000000000000000..cb006da88796f2874e9c144291833106c0c747ba --- /dev/null +++ b/src/test/resources/testExportJob.json @@ -0,0 +1,4 @@ +{ + "contentType": "application/json", + "url": "https://my/daily/job/NHCFD6" +} \ No newline at end of file diff --git a/src/test/resources/testServiceCandidate.txt b/src/test/resources/testServiceCandidate.txt new file mode 100644 index 0000000000000000000000000000000000000000..e499cc0699beaec54c04d95e62e7126b83df0599 --- /dev/null +++ b/src/test/resources/testServiceCandidate.txt @@ -0,0 +1,5 @@ +{ + "description": "A Test Service Candidate", + "version": "1.8", + "name": "Test Service Candidate" +} \ No newline at end of file diff --git a/src/test/resources/testServiceCandidateChangeNotification.json b/src/test/resources/testServiceCandidateChangeNotification.json new file mode 100644 index 0000000000000000000000000000000000000000..83442e8e267ea97db23f53bd0557c0845e6ce818 --- /dev/null +++ b/src/test/resources/testServiceCandidateChangeNotification.json @@ -0,0 +1,3 @@ +{ + "eventId": "testId" +} \ No newline at end of file