diff options
author | FrancescoFioraEst <francesco.fiora@est.tech> | 2021-11-11 14:57:23 +0000 |
---|---|---|
committer | FrancescoFioraEst <francesco.fiora@est.tech> | 2021-11-25 13:25:48 +0000 |
commit | a41acc89a8c7177014d1377c4457cd402ed7ee93 (patch) | |
tree | 47eb78295c696d7281bc772e346ec260cd114ce1 | |
parent | 7443b9a5ddca988ad4338e2b6597d6fdce552909 (diff) |
Add support transaction in CL and ServiceTemplate Providers
Add support transaction
in ControlLoopProvider and ServiceTemplateProvider
Issue-ID: POLICY-3798
Change-Id: I0ab79f28231e329e06c16e01427775077b3ac994
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
20 files changed, 798 insertions, 824 deletions
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java index a61b97fa8..7b6787c5d 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java @@ -22,146 +22,173 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; +import java.util.Optional; +import javax.persistence.EntityNotFoundException; import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import lombok.AllArgsConstructor; import lombok.NonNull; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaControlLoop; -import org.onap.policy.models.base.PfAuthorative; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ControlLoopRepository; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaNodeTemplateRepository; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaNodeTemplatesRepository; import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.onap.policy.models.provider.impl.AbstractModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; /** * This class provides information on control loop concepts in the database to callers. */ @Component -public class ControlLoopProvider extends AbstractModelsProvider { +@Transactional +@AllArgsConstructor +public class ControlLoopProvider { + + private final ControlLoopRepository controlLoopRepository; + private final ToscaNodeTemplateRepository toscaNodeTemplateRepository; + private final ToscaNodeTemplatesRepository toscaNodeTemplatesRepository; /** - * Create a provider for control loops. + * Get Control Loop. * - * @param parameters the parameters for database access - * @throws PfModelException on initiation errors + * @param controlLoopId the ID of the control loop to get + * @return the control loop found + * @throws PfModelException on errors getting the control loop */ - public ControlLoopProvider(@NonNull PolicyModelsProviderParameters parameters) throws PfModelException { - super(parameters); - this.init(); + @Transactional(readOnly = true) + public ControlLoop getControlLoop(final ToscaConceptIdentifier controlLoopId) throws PfModelException { + try { + return controlLoopRepository.getById(controlLoopId.asConceptKey()).toAuthorative(); + } catch (EntityNotFoundException e) { + throw new PfModelException(Status.NOT_FOUND, "ControlLoop not found", e); + } } /** - * Get Control Loop. + * Find Control Loop by controlLoopId. + * + * @param name the name of the control loop to get, null to get all control loops + * @param version the version of the control loop to get, null to get all control loops + * @return the control loop found + * @throws PfModelException on errors getting the control loop + */ + @Transactional(readOnly = true) + public Optional<ControlLoop> findControlLoop(@NonNull final String name, @NonNull final String version) + throws PfModelException { + return findControlLoop(new PfConceptKey(name, version)); + } + + /** + * Find Control Loop by controlLoopId. * * @param controlLoopId the ID of the control loop to get * @return the control loop found * @throws PfModelException on errors getting the control loop */ - public ControlLoop getControlLoop(final ToscaConceptIdentifier controlLoopId) throws PfModelException { - var jpaControlLoop = getPfDao().get(JpaControlLoop.class, controlLoopId.asConceptKey()); + @Transactional(readOnly = true) + public Optional<ControlLoop> findControlLoop(final ToscaConceptIdentifier controlLoopId) throws PfModelException { + return findControlLoop(controlLoopId.asConceptKey()); + } - return jpaControlLoop == null ? null : jpaControlLoop.toAuthorative(); + private Optional<ControlLoop> findControlLoop(@NonNull final PfConceptKey key) throws PfModelException { + try { + return controlLoopRepository.findById(key).map(JpaControlLoop::toAuthorative); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Not valid parameter", e); + } } /** - * Update Control Loop. + * Save Control Loop. * * @param controlLoop the control loop to update * @return the updated control loop * @throws PfModelException on errors updating the control loop */ - public ControlLoop updateControlLoop(final ControlLoop controlLoop) throws PfModelException { - return updateControlLoops(Collections.singletonList(controlLoop)).get(0); + public ControlLoop saveControlLoop(final ControlLoop controlLoop) throws PfModelException { + try { + var result = controlLoopRepository + .save(ProviderUtils.getJpaAndValidate(controlLoop, JpaControlLoop::new, "control loop")); + + // Return the saved participant + return result.toAuthorative(); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in save controlLoop", e); + } } /** - * Get Control Loops. + * Get All Control Loops. * - * @param name the name of the control loop to get, null to get all control loops - * @param version the version of the control loop to get, null to get all control loops - * @return the control loops found + * @return all control loops found * @throws PfModelException on errors getting control loops */ - public List<ControlLoop> getControlLoops(final String name, final String version) throws PfModelException { + @Transactional(readOnly = true) + public List<ControlLoop> getControlLoops() throws PfModelException { - return asEntityList(getPfDao().getFiltered(JpaControlLoop.class, name, version)); + return ProviderUtils.asEntityList(controlLoopRepository.findAll()); } /** - * Get filtered control loops. + * Get Control Loops. * - * @param filter the filter for the control loops to get + * @param name the name of the control loop to get, null to get all control loops + * @param version the version of the control loop to get, null to get all control loops * @return the control loops found * @throws PfModelException on errors getting control loops */ - public List<ControlLoop> getFilteredControlLoops(@NonNull final ToscaTypedEntityFilter<ControlLoop> filter) { + @Transactional(readOnly = true) + public List<ControlLoop> getControlLoops(final String name, final String version) throws PfModelException { - return filter.filter( - asEntityList(getPfDao().getFiltered(JpaControlLoop.class, filter.getName(), PfKey.NULL_KEY_VERSION))); + return ProviderUtils.asEntityList(controlLoopRepository.getFiltered(JpaControlLoop.class, name, version)); } /** - * Creates control loops. + * Saves control loops. * * @param controlLoops a specification of the control loops to create * @return the control loops created * @throws PfModelException on errors creating control loops */ - public List<ControlLoop> createControlLoops(@NonNull final List<ControlLoop> controlLoops) throws PfModelException { - - List<JpaControlLoop> jpaControlLoopList = - ProviderUtils.getJpaAndValidateList(controlLoops, JpaControlLoop::new, "control loop"); - - jpaControlLoopList.forEach(jpaControlLoop -> getPfDao().create(jpaControlLoop)); - - // Return the created control loops - List<ControlLoop> returnControlLoops = new ArrayList<>(controlLoops.size()); - - for (ControlLoop controlLoop : controlLoops) { - var jpaControlLoop = getPfDao().get(JpaControlLoop.class, - new PfConceptKey(controlLoop.getName(), controlLoop.getVersion())); - returnControlLoops.add(jpaControlLoop.toAuthorative()); + public List<ControlLoop> saveControlLoops(@NonNull final List<ControlLoop> controlLoops) throws PfModelException { + try { + var result = controlLoopRepository + .saveAll(ProviderUtils.getJpaAndValidateList(controlLoops, JpaControlLoop::new, "control loops")); + + // Return the saved participant + return ProviderUtils.asEntityList(result); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in save ControlLoops", e); } - - return returnControlLoops; } /** - * Updates control loops. + * Saves Instance Properties to the database. * - * @param controlLoops a specification of the control loops to update - * @return the control loops updated - * @throws PfModelException on errors updating control loops + * @param serviceTemplate the service template + * @return a Map of tosca node templates */ - public List<ControlLoop> updateControlLoops(@NonNull final List<ControlLoop> controlLoops) throws PfModelException { - - List<JpaControlLoop> jpaControlLoopList = - ProviderUtils.getJpaAndValidateList(controlLoops, JpaControlLoop::new, "control loop"); + public Map<String, ToscaNodeTemplate> saveInstanceProperties(ToscaServiceTemplate serviceTemplate) { + Map<String, ToscaNodeTemplate> savedNodeTemplates = new HashMap<>(); - // Return the created control loops - List<ControlLoop> returnControlLoops = new ArrayList<>(controlLoops.size()); + var jpaToscaNodeTemplates = new JpaToscaNodeTemplates(); + jpaToscaNodeTemplates.fromAuthorative(List.of(serviceTemplate.getToscaTopologyTemplate().getNodeTemplates())); - jpaControlLoopList.forEach(jpaControlLoop -> { - var returnJpaControlLoop = getPfDao().update(jpaControlLoop); - returnControlLoops.add(returnJpaControlLoop.toAuthorative()); - }); + toscaNodeTemplatesRepository.save(jpaToscaNodeTemplates); + serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().forEach(savedNodeTemplates::put); - return returnControlLoops; + return savedNodeTemplates; } /** @@ -170,42 +197,23 @@ public class ControlLoopProvider extends AbstractModelsProvider { * @param name the name of the control loop to delete * @param version the version of the control loop to delete * @return the control loop deleted - * @throws PfModelRuntimeException on errors deleting the control loop + * @throws PfModelException on errors deleting the control loop */ - public ControlLoop deleteControlLoop(@NonNull final String name, @NonNull final String version) { + public ControlLoop deleteControlLoop(@NonNull final String name, @NonNull final String version) + throws PfModelException { var controlLoopKey = new PfConceptKey(name, version); + var jpaDeleteControlLoop = controlLoopRepository.findById(controlLoopKey); - var jpaDeleteControlLoop = getPfDao().get(JpaControlLoop.class, controlLoopKey); - - if (jpaDeleteControlLoop == null) { + if (jpaDeleteControlLoop.isEmpty()) { String errorMessage = "delete of control loop \"" + controlLoopKey.getId() + "\" failed, control loop does not exist"; - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage); } - getPfDao().delete(jpaDeleteControlLoop); + controlLoopRepository.deleteById(controlLoopKey); - return jpaDeleteControlLoop.toAuthorative(); - } - - /** - * Saves Instance Properties to the database. - * @param serviceTemplate the service template - * @return a Map of tosca node templates - */ - public Map<String, ToscaNodeTemplate> saveInstanceProperties(ToscaServiceTemplate serviceTemplate) { - - Map<String, ToscaNodeTemplate> savedNodeTemplates = new HashMap<>(); - - var jpaToscaNodeTemplates = new JpaToscaNodeTemplates(); - jpaToscaNodeTemplates.fromAuthorative(Collections.singletonList(serviceTemplate.getToscaTopologyTemplate() - .getNodeTemplates())); - - getPfDao().create(jpaToscaNodeTemplates); - serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().forEach(savedNodeTemplates::put); - - return savedNodeTemplates; + return jpaDeleteControlLoop.get().toAuthorative(); } /** @@ -214,23 +222,33 @@ public class ControlLoopProvider extends AbstractModelsProvider { * @param filteredToscaNodeTemplateMap filtered node templates map to delete * @param filteredToscaNodeTemplateList filtered node template list to delete */ - public void deleteInstanceProperties( - Map<String, ToscaNodeTemplate> filteredToscaNodeTemplateMap, - List<ToscaNodeTemplate> filteredToscaNodeTemplateList) { + public void deleteInstanceProperties(Map<String, ToscaNodeTemplate> filteredToscaNodeTemplateMap, + List<ToscaNodeTemplate> filteredToscaNodeTemplateList) { var jpaToscaNodeTemplates = new JpaToscaNodeTemplates(); - jpaToscaNodeTemplates.fromAuthorative(Collections.singletonList(filteredToscaNodeTemplateMap)); + jpaToscaNodeTemplates.fromAuthorative(List.of(filteredToscaNodeTemplateMap)); - getPfDao().create(jpaToscaNodeTemplates); + toscaNodeTemplatesRepository.save(jpaToscaNodeTemplates); filteredToscaNodeTemplateList.forEach(template -> { var jpaToscaNodeTemplate = new JpaToscaNodeTemplate(template); - getPfDao().delete(jpaToscaNodeTemplate); + toscaNodeTemplateRepository.delete(jpaToscaNodeTemplate); }); } /** + * Get All Node Templates. + * + * @return the list of node templates found + * @throws PfModelException on errors getting node templates + */ + @Transactional(readOnly = true) + public List<ToscaNodeTemplate> getAllNodeTemplates() { + return ProviderUtils.asEntityList(toscaNodeTemplateRepository.findAll()); + } + + /** * Get Node Templates. * * @param name the name of the node template to get, null to get all node templates @@ -238,8 +256,10 @@ public class ControlLoopProvider extends AbstractModelsProvider { * @return the node templates found * @throws PfModelException on errors getting node templates */ + @Transactional(readOnly = true) public List<ToscaNodeTemplate> getNodeTemplates(final String name, final String version) { - return asEntityList(getPfDao().getFiltered(JpaToscaNodeTemplate.class, name, version)); + return ProviderUtils + .asEntityList(toscaNodeTemplateRepository.getFiltered(JpaToscaNodeTemplate.class, name, version)); } /** @@ -249,23 +269,11 @@ public class ControlLoopProvider extends AbstractModelsProvider { * @return the node templates found * @throws PfModelException on errors getting node templates */ + @Transactional(readOnly = true) public List<ToscaNodeTemplate> getFilteredNodeTemplates( @NonNull final ToscaTypedEntityFilter<ToscaNodeTemplate> filter) { - return filter.filter(asEntityList( - getPfDao().getFiltered(JpaToscaNodeTemplate.class, filter.getName(), filter.getVersion()))); + return filter.filter(ProviderUtils.asEntityList(toscaNodeTemplateRepository + .getFiltered(JpaToscaNodeTemplate.class, filter.getName(), filter.getVersion()))); } - - /** - * Convert JPA control loop list to an authorative control loop list. - * - * @param <T> the type of TOSCA entity - * @param <J> the type of JPA TOSCA entity - * @param jpaEntityList the list to convert - * @return the authorative list - */ - private <T extends ToscaEntity, J extends PfAuthorative<T>> List<T> asEntityList(List<J> jpaEntityList) { - return jpaEntityList.stream().map(J::toAuthorative).collect(Collectors.toList()); - } - } diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProvider.java index 6a6d20fe7..6b3749fc5 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProvider.java @@ -23,21 +23,26 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provide import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import lombok.RequiredArgsConstructor; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaServiceTemplateRepository; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType; import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; @Component @RequiredArgsConstructor +@Transactional public class ServiceTemplateProvider { - private final PolicyModelsProvider modelsProvider; + private final ToscaServiceTemplateRepository serviceTemplateRepository; /** * Create service template. @@ -48,7 +53,13 @@ public class ServiceTemplateProvider { */ public ToscaServiceTemplate createServiceTemplate(final ToscaServiceTemplate serviceTemplate) throws PfModelException { - return modelsProvider.createServiceTemplate(serviceTemplate); + try { + var result = serviceTemplateRepository.save(ProviderUtils.getJpaAndValidate(serviceTemplate, + JpaToscaServiceTemplate::new, "toscaServiceTemplate")); + return result.toAuthorative(); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in save serviceTemplate", e); + } } /** @@ -60,7 +71,15 @@ public class ServiceTemplateProvider { * @throws PfModelException on errors deleting policy types */ public ToscaServiceTemplate deleteServiceTemplate(final String name, final String version) throws PfModelException { - return modelsProvider.deleteServiceTemplate(name, version); + var serviceTemplateKey = new PfConceptKey(name, version); + var jpaDelete = serviceTemplateRepository.findById(serviceTemplateKey); + if (jpaDelete.isEmpty()) { + String errorMessage = "delete of serviceTemplate \"" + serviceTemplateKey.getId() + + "\" failed, serviceTemplate does not exist"; + throw new PfModelException(Response.Status.BAD_REQUEST, errorMessage); + } + serviceTemplateRepository.deleteById(serviceTemplateKey); + return jpaDelete.get().toAuthorative(); } /** @@ -71,12 +90,26 @@ public class ServiceTemplateProvider { * @return the control loop definitions * @throws PfModelException on errors getting control loop definitions */ + @Transactional(readOnly = true) public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException { - var serviceTemplates = modelsProvider.getServiceTemplateList(name, version); - if (serviceTemplates.isEmpty()) { + var serviceTemplateKey = new PfConceptKey(name, version); + var jpaServiceTemplates = serviceTemplateRepository.findById(serviceTemplateKey); + if (jpaServiceTemplates.isEmpty()) { throw new PfModelException(Status.NOT_FOUND, "Control Loop definitions not found"); } - return serviceTemplates.get(0); + return jpaServiceTemplates.get().toAuthorative(); + } + + /** + * Get service templates. + * + * @return the topology templates found + * @throws PfModelException on errors getting service templates + */ + @Transactional(readOnly = true) + public List<ToscaServiceTemplate> getAllServiceTemplates() throws PfModelException { + var jpaList = serviceTemplateRepository.findAll(); + return ProviderUtils.asEntityList(jpaList); } /** @@ -87,9 +120,11 @@ public class ServiceTemplateProvider { * @return the topology templates found * @throws PfModelException on errors getting service templates */ + @Transactional(readOnly = true) public List<ToscaServiceTemplate> getServiceTemplateList(final String name, final String version) throws PfModelException { - return modelsProvider.getServiceTemplateList(name, version); + var jpaList = serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, name, version); + return ProviderUtils.asEntityList(jpaList); } /** diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProviderTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProviderTest.java index 9805edb86..2b472c835 100644 --- a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProviderTest.java +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProviderTest.java @@ -24,174 +24,255 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.AfterEach; +import java.util.Optional; +import javax.persistence.EntityNotFoundException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; -import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaControlLoop; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ControlLoopRepository; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaNodeTemplateRepository; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaNodeTemplatesRepository; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.YamlJsonTranslator; import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; class ControlLoopProviderTest { private static final String LIST_IS_NULL = "controlLoops is marked .*ull but is null"; + private static final String OBJECT_IS_NULL = "controlLoop is marked non-null but is null"; + + private static final String ID_NAME = "PMSHInstance1"; + private static final String ID_VERSION = "1.0.1"; + private static final String ID_NAME_NOT_EXTST = "not_exist"; + private static final String ID_NAME_NOT_VALID = "not_valid"; + private static final Coder CODER = new StandardCoder(); private static final String CONTROL_LOOP_JSON = "src/test/resources/providers/TestControlLoops.json"; - private static final String UPDATE_CL_JSON = "src/test/resources/providers/UpdateControlLoops.json"; private static final String TOSCA_TEMPLATE_YAML = "examples/controlloop/PMSubscriptionHandling.yaml"; private static final YamlJsonTranslator yamlTranslator = new YamlJsonTranslator(); - private static AtomicInteger dbNameCounter = new AtomicInteger(); - private PolicyModelsProviderParameters parameters; - private ControlLoopProvider controlLoopProvider; private ControlLoops inputControlLoops; - private ControlLoops updateControlLoops; + private List<JpaControlLoop> inputControlLoopsJpa; private String originalJson = ResourceUtils.getResourceAsString(CONTROL_LOOP_JSON); - private String updateClJson = ResourceUtils.getResourceAsString(UPDATE_CL_JSON); @BeforeEach void beforeSetupDao() throws Exception { - - parameters = new PolicyModelsProviderParameters(); - parameters.setDatabaseDriver("org.h2.Driver"); - parameters.setName("PolicyProviderParameterGroup"); - parameters.setImplementation("org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl"); - parameters.setDatabaseUrl("jdbc:h2:mem:controlLoopProviderTestDb" + dbNameCounter.getAndDecrement()); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword("P01icY"); - parameters.setPersistenceUnit("ToscaConceptTest"); - - controlLoopProvider = new ControlLoopProvider(parameters); - inputControlLoops = CODER.decode(originalJson, ControlLoops.class); - updateControlLoops = CODER.decode(updateClJson, ControlLoops.class); - } - - @AfterEach - void teardown() { - controlLoopProvider.close(); + inputControlLoopsJpa = ProviderUtils.getJpaAndValidateList(inputControlLoops.getControlLoopList(), + JpaControlLoop::new, "control loops"); } @Test - void testControlLoopCreate() throws Exception { + void testControlLoopsSave() throws Exception { + var controlLoopRepository = mock(ControlLoopRepository.class); + var controlLoopProvider = new ControlLoopProvider(controlLoopRepository, + mock(ToscaNodeTemplateRepository.class), mock(ToscaNodeTemplatesRepository.class)); + assertThatThrownBy(() -> { - controlLoopProvider.createControlLoops(null); + controlLoopProvider.saveControlLoops(null); }).hasMessageMatching(LIST_IS_NULL); + when(controlLoopRepository.saveAll(inputControlLoopsJpa)).thenReturn(inputControlLoopsJpa); + var createdControlLoops = new ControlLoops(); createdControlLoops - .setControlLoopList(controlLoopProvider.createControlLoops(inputControlLoops.getControlLoopList())); + .setControlLoopList(controlLoopProvider.saveControlLoops(inputControlLoops.getControlLoopList())); assertEquals(inputControlLoops, createdControlLoops); + + when(controlLoopRepository.saveAll(any())).thenThrow(IllegalArgumentException.class); + + assertThatThrownBy(() -> { + controlLoopProvider.saveControlLoops(inputControlLoops.getControlLoopList()); + }).hasMessageMatching("Error in save ControlLoops"); } @Test - void testGetControlLoops() throws Exception { + void testControlLoopSave() throws Exception { + var controlLoopRepository = mock(ControlLoopRepository.class); + var controlLoopProvider = new ControlLoopProvider(controlLoopRepository, + mock(ToscaNodeTemplateRepository.class), mock(ToscaNodeTemplatesRepository.class)); - List<ControlLoop> getResponse; + assertThatThrownBy(() -> { + controlLoopProvider.saveControlLoop(null); + }).hasMessageMatching(OBJECT_IS_NULL); + + when(controlLoopRepository.save(inputControlLoopsJpa.get(0))).thenReturn(inputControlLoopsJpa.get(0)); + + var createdControlLoop = controlLoopProvider.saveControlLoop(inputControlLoops.getControlLoopList().get(0)); + + assertEquals(inputControlLoops.getControlLoopList().get(0), createdControlLoop); + + when(controlLoopRepository.save(any())).thenThrow(IllegalArgumentException.class); + + assertThatThrownBy(() -> { + controlLoopProvider.saveControlLoop(inputControlLoops.getControlLoopList().get(0)); + }).hasMessageMatching("Error in save controlLoop"); + } + + @Test + void testGetControlLoops() throws Exception { + var controlLoopRepository = mock(ControlLoopRepository.class); + var controlLoopProvider = new ControlLoopProvider(controlLoopRepository, + mock(ToscaNodeTemplateRepository.class), mock(ToscaNodeTemplatesRepository.class)); // Return empty list when no data present in db - getResponse = controlLoopProvider.getControlLoops(null, null); + List<ControlLoop> getResponse = controlLoopProvider.getControlLoops(); assertThat(getResponse).isEmpty(); - controlLoopProvider.createControlLoops(inputControlLoops.getControlLoopList()); - var name = inputControlLoops.getControlLoopList().get(0).getName(); - var version = inputControlLoops.getControlLoopList().get(0).getVersion(); + controlLoopProvider.saveControlLoops(inputControlLoops.getControlLoopList()); + + var controlLoop0 = inputControlLoops.getControlLoopList().get(1); + var name = controlLoop0.getName(); + var version = controlLoop0.getVersion(); + var controlLoop1 = inputControlLoops.getControlLoopList().get(1); + + when(controlLoopRepository.getFiltered(eq(JpaControlLoop.class), any(), any())) + .thenReturn(List.of(new JpaControlLoop(controlLoop0), new JpaControlLoop(controlLoop1))); + when(controlLoopRepository.findById(controlLoop0.getKey().asIdentifier().asConceptKey())) + .thenReturn(Optional.of(new JpaControlLoop(controlLoop0))); + when(controlLoopRepository.getById(controlLoop0.getKey().asIdentifier().asConceptKey())) + .thenReturn(new JpaControlLoop(controlLoop0)); + when(controlLoopRepository.getFiltered(JpaControlLoop.class, name, version)) + .thenReturn(List.of(new JpaControlLoop(controlLoop0))); + when(controlLoopRepository.findById(controlLoop1.getKey().asIdentifier().asConceptKey())) + .thenReturn(Optional.of(new JpaControlLoop(controlLoop1))); + assertEquals(1, controlLoopProvider.getControlLoops(name, version).size()); - var cl = new ControlLoop(); - cl = controlLoopProvider.getControlLoop(new ToscaConceptIdentifier("PMSHInstance1", "1.0.1")); + var cl = controlLoopProvider.findControlLoop(new ToscaConceptIdentifier(ID_NAME, ID_VERSION)).get(); + assertEquals(inputControlLoops.getControlLoopList().get(1), cl); + + cl = controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME, ID_VERSION)); assertEquals(inputControlLoops.getControlLoopList().get(1), cl); - assertNull(controlLoopProvider.getControlLoop(new ToscaConceptIdentifier("invalid_name", "1.0.1"))); + when(controlLoopRepository.getById(any())).thenThrow(EntityNotFoundException.class); assertThatThrownBy(() -> { - controlLoopProvider.getFilteredControlLoops(null); - }).hasMessageMatching("filter is marked .*ull but is null"); + controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME_NOT_EXTST, ID_VERSION)); + }).hasMessageMatching("ControlLoop not found"); - final ToscaTypedEntityFilter<ControlLoop> filter = ToscaTypedEntityFilter.<ControlLoop>builder() - .type("org.onap.domain.pmsh.PMSHControlLoopDefinition").build(); - assertEquals(2, controlLoopProvider.getFilteredControlLoops(filter).size()); - } + cl = controlLoopProvider.findControlLoop(ID_NAME, ID_VERSION).get(); + assertEquals(inputControlLoops.getControlLoopList().get(1), cl); - @Test - void testUpdateControlLoops() throws Exception { - assertThatThrownBy(() -> { - controlLoopProvider.updateControlLoops(null); - }).hasMessageMatching("controlLoops is marked .*ull but is null"); + assertThat(controlLoopProvider.findControlLoop(new ToscaConceptIdentifier(ID_NAME_NOT_EXTST, ID_VERSION))) + .isEmpty(); - var existingControlLoops = new ControlLoops(); - existingControlLoops - .setControlLoopList(controlLoopProvider.createControlLoops(inputControlLoops.getControlLoopList())); - var updateResponse = new ControlLoop(); - updateResponse = controlLoopProvider.updateControlLoop(updateControlLoops.getControlLoopList().get(0)); + when(controlLoopRepository.findById(any())).thenThrow(IllegalArgumentException.class); - assertEquals(ControlLoopOrderedState.RUNNING, updateResponse.getOrderedState()); + assertThatThrownBy(() -> { + controlLoopProvider.findControlLoop(ID_NAME_NOT_VALID, ID_VERSION); + }).hasMessageMatching("Not valid parameter"); } @Test void testDeleteControlLoop() throws Exception { + var controlLoopRepository = mock(ControlLoopRepository.class); + var controlLoopProvider = new ControlLoopProvider(controlLoopRepository, + mock(ToscaNodeTemplateRepository.class), mock(ToscaNodeTemplatesRepository.class)); + assertThatThrownBy(() -> { - controlLoopProvider.deleteControlLoop("Invalid_name", "1.0.1"); + controlLoopProvider.deleteControlLoop(ID_NAME_NOT_EXTST, ID_VERSION); }).hasMessageMatching(".*.failed, control loop does not exist"); - ControlLoop deletedCl; - List<ControlLoop> clList = controlLoopProvider.createControlLoops(inputControlLoops.getControlLoopList()); - var name = inputControlLoops.getControlLoopList().get(0).getName(); - var version = inputControlLoops.getControlLoopList().get(0).getVersion(); + var controlLoop = inputControlLoops.getControlLoopList().get(0); + var name = controlLoop.getName(); + var version = controlLoop.getVersion(); - deletedCl = controlLoopProvider.deleteControlLoop(name, version); - assertEquals(clList.get(0), deletedCl); + when(controlLoopRepository.findById(new PfConceptKey(name, version))) + .thenReturn(Optional.of(inputControlLoopsJpa.get(0))); + + ControlLoop deletedCl = controlLoopProvider.deleteControlLoop(name, version); + assertEquals(controlLoop, deletedCl); } @Test void testDeleteAllInstanceProperties() throws Exception { + var controlLoopProvider = new ControlLoopProvider(mock(ControlLoopRepository.class), + mock(ToscaNodeTemplateRepository.class), mock(ToscaNodeTemplatesRepository.class)); var toscaServiceTemplate = testControlLoopRead(); - controlLoopProvider.deleteInstanceProperties( - controlLoopProvider.saveInstanceProperties(toscaServiceTemplate), + controlLoopProvider.deleteInstanceProperties(controlLoopProvider.saveInstanceProperties(toscaServiceTemplate), controlLoopProvider.getNodeTemplates(null, null)); - assertThat(controlLoopProvider.getControlLoops(null, null)).isEmpty(); + assertThat(controlLoopProvider.getControlLoops()).isEmpty(); } @Test void testSaveAndDeleteInstanceProperties() throws Exception { + var toscaNodeTemplatesRepository = mock(ToscaNodeTemplatesRepository.class); + var toscaNodeTemplateRepository = mock(ToscaNodeTemplateRepository.class); + var controlLoopProvider = new ControlLoopProvider(mock(ControlLoopRepository.class), + toscaNodeTemplateRepository, toscaNodeTemplatesRepository); var toscaServiceTest = testControlLoopRead(); - controlLoopProvider.createControlLoops(inputControlLoops.getControlLoopList()); controlLoopProvider.saveInstanceProperties(toscaServiceTest); - assertThat(controlLoopProvider.getNodeTemplates( - "org.onap.policy.controlloop.PolicyControlLoopParticipant", - "2.3.1")).isNotEmpty(); - - controlLoopProvider.deleteInstanceProperties( - controlLoopProvider.saveInstanceProperties(toscaServiceTest), - controlLoopProvider.getNodeTemplates( - "org.onap.policy.controlloop.PolicyControlLoopParticipant", - "2.3.1")); - - assertThat(controlLoopProvider.getNodeTemplates( - "org.onap.policy.controlloop.PolicyControlLoopParticipant", - "2.3.1")).isEmpty(); + verify(toscaNodeTemplatesRepository).save(any()); + + var name = "org.onap.policy.controlloop.PolicyControlLoopParticipant"; + var version = "2.3.1"; + var elem = toscaServiceTest.getToscaTopologyTemplate().getNodeTemplates().get(name); + when(toscaNodeTemplateRepository.getFiltered(JpaToscaNodeTemplate.class, name, version)) + .thenReturn(List.of(new JpaToscaNodeTemplate(elem))); + + var filtered = controlLoopProvider.getNodeTemplates(name, version); + verify(toscaNodeTemplateRepository).getFiltered(JpaToscaNodeTemplate.class, name, version); + + controlLoopProvider.deleteInstanceProperties(controlLoopProvider.saveInstanceProperties(toscaServiceTest), + filtered); + + verify(toscaNodeTemplateRepository).delete(any()); } @Test void testGetNodeTemplates() throws Exception { - //Getting all nodes - List<ToscaNodeTemplate> listNodes = controlLoopProvider.getNodeTemplates(null, null); + var toscaNodeTemplateRepository = mock(ToscaNodeTemplateRepository.class); + var controlLoopProvider = new ControlLoopProvider(mock(ControlLoopRepository.class), + toscaNodeTemplateRepository, mock(ToscaNodeTemplatesRepository.class)); + + var toscaNodeTemplate0 = new JpaToscaNodeTemplate(new PfConceptKey(ID_NAME, ID_VERSION)); + var toscaNodeTemplate1 = new JpaToscaNodeTemplate(new PfConceptKey("PMSHInstance2", ID_VERSION)); + + when(toscaNodeTemplateRepository.getFiltered(JpaToscaNodeTemplate.class, null, null)) + .thenReturn(List.of(toscaNodeTemplate0, toscaNodeTemplate1)); + when(toscaNodeTemplateRepository.findAll()).thenReturn(List.of(toscaNodeTemplate0, toscaNodeTemplate1)); + when(toscaNodeTemplateRepository.getFiltered(JpaToscaNodeTemplate.class, ID_NAME, ID_VERSION)) + .thenReturn(List.of(toscaNodeTemplate0)); + + // Getting all nodes + var listNodes = controlLoopProvider.getNodeTemplates(null, null); + assertNotNull(listNodes); + assertThat(listNodes).hasSize(2); + + listNodes = controlLoopProvider.getNodeTemplates(ID_NAME, ID_VERSION); + assertNotNull(listNodes); + assertThat(listNodes).hasSize(1); + + listNodes = controlLoopProvider.getAllNodeTemplates(); + assertNotNull(listNodes); + assertThat(listNodes).hasSize(2); + + var nodeTemplateFilter = + ToscaTypedEntityFilter.<ToscaNodeTemplate>builder().name(ID_NAME).version(ID_VERSION).build(); + + listNodes = controlLoopProvider.getFilteredNodeTemplates(nodeTemplateFilter); assertNotNull(listNodes); + assertThat(listNodes).hasSize(1); assertThatThrownBy(() -> { controlLoopProvider.getFilteredNodeTemplates(null); @@ -203,8 +284,7 @@ class ControlLoopProviderTest { } private static ToscaServiceTemplate testControlLoopYamlSerialization(String controlLoopFilePath) { - String controlLoopString = ResourceUtils.getResourceAsString(controlLoopFilePath); - ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml(controlLoopString, ToscaServiceTemplate.class); - return serviceTemplate; + var controlLoopString = ResourceUtils.getResourceAsString(controlLoopFilePath); + return yamlTranslator.fromYaml(controlLoopString, ToscaServiceTemplate.class); } } diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProviderTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProviderTest.java index 7f2731abf..523a4fb88 100644 --- a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProviderTest.java +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ServiceTemplateProviderTest.java @@ -29,13 +29,17 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ToscaServiceTemplateRepository; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardYamlCoder; import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; class ServiceTemplateProviderTest { @@ -44,28 +48,33 @@ class ServiceTemplateProviderTest { private static final StandardYamlCoder YAML_TRANSLATOR = new StandardYamlCoder(); + private static ToscaServiceTemplate inputServiceTemplate; + + @BeforeAll + static void loadServiceTemplate() { + inputServiceTemplate = getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); + } + @Test void testGetCommonOrInstancePropertiesFromNodeTypes() throws PfModelException { - var serviceTemplateProvider = new ServiceTemplateProvider(mock(PolicyModelsProvider.class)); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); - var serviceTemplate = getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); - - var result = serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, serviceTemplate); + var result = serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, inputServiceTemplate); assertNotNull(result); assertThat(result).hasSize(8); } @Test void testGetDerivedCommonOrInstanceNodeTemplates() throws PfModelException { - var serviceTemplateProvider = new ServiceTemplateProvider(mock(PolicyModelsProvider.class)); - - var serviceTemplate = getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); var commonOrInstanceNodeTypeProps = - serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, serviceTemplate); + serviceTemplateProvider.getCommonOrInstancePropertiesFromNodeTypes(true, inputServiceTemplate); var result = serviceTemplateProvider.getDerivedCommonOrInstanceNodeTemplates( - serviceTemplate.getToscaTopologyTemplate().getNodeTemplates(), commonOrInstanceNodeTypeProps); + inputServiceTemplate.getToscaTopologyTemplate().getNodeTemplates(), commonOrInstanceNodeTypeProps); assertNotNull(result); assertThat(result).hasSize(8); @@ -73,74 +82,74 @@ class ServiceTemplateProviderTest { @Test void testCreateServiceTemplate() throws PfModelException { - var modelsProvider = mock(PolicyModelsProvider.class); - var serviceTemplateProvider = new ServiceTemplateProvider(modelsProvider); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); - var serviceTemplate = new ToscaServiceTemplate(); - when(modelsProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate); + var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new, + "toscaServiceTemplate"); + when(serviceTemplateRepository.save(jpaServiceTemplate)).thenReturn(jpaServiceTemplate); - var result = serviceTemplateProvider.createServiceTemplate(serviceTemplate); + var result = serviceTemplateProvider.createServiceTemplate(inputServiceTemplate); - assertThat(result).isEqualTo(serviceTemplate); + assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative()); } @Test void testDeleteServiceTemplate() throws PfModelException { - var serviceTemplate = new ToscaServiceTemplate(); - serviceTemplate.setName("Name"); - serviceTemplate.setVersion("1.0.0"); - var modelsProvider = mock(PolicyModelsProvider.class); - when(modelsProvider.deleteServiceTemplate(serviceTemplate.getName(), serviceTemplate.getVersion())) - .thenReturn(serviceTemplate); - - var serviceTemplateProvider = new ServiceTemplateProvider(modelsProvider); - var result = - serviceTemplateProvider.deleteServiceTemplate(serviceTemplate.getName(), serviceTemplate.getVersion()); - - assertThat(result).isEqualTo(serviceTemplate); + var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new, + "toscaServiceTemplate"); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + when(serviceTemplateRepository + .findById(new PfConceptKey(inputServiceTemplate.getName(), inputServiceTemplate.getVersion()))) + .thenReturn(Optional.of(jpaServiceTemplate)); + + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); + var result = serviceTemplateProvider.deleteServiceTemplate(inputServiceTemplate.getName(), + inputServiceTemplate.getVersion()); + + assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative()); } @Test void testGetServiceTemplateListEmpty() throws PfModelException { - var modelsProvider = mock(PolicyModelsProvider.class); - when(modelsProvider.getServiceTemplateList(any(String.class), any(String.class))).thenReturn(List.of()); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + when(serviceTemplateRepository.findById(any())).thenReturn(Optional.empty()); - var serviceTemplateProvider = new ServiceTemplateProvider(modelsProvider); + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); assertThatThrownBy(() -> serviceTemplateProvider.getToscaServiceTemplate("Name", "1.0.0")) .hasMessage("Control Loop definitions not found"); } @Test void testGetServiceTemplateList() throws PfModelException { - var serviceTemplate = new ToscaServiceTemplate(); - serviceTemplate.setName("Name"); - serviceTemplate.setVersion("1.0.0"); - var modelsProvider = mock(PolicyModelsProvider.class); - when(modelsProvider.getServiceTemplateList(serviceTemplate.getName(), serviceTemplate.getVersion())) - .thenReturn(List.of(serviceTemplate)); - - var serviceTemplateProvider = new ServiceTemplateProvider(modelsProvider); - var result = serviceTemplateProvider.getToscaServiceTemplate(serviceTemplate.getName(), - serviceTemplate.getVersion()); - - assertThat(result).isEqualTo(serviceTemplate); + var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new, + "toscaServiceTemplate"); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + when(serviceTemplateRepository + .findById(new PfConceptKey(inputServiceTemplate.getName(), inputServiceTemplate.getVersion()))) + .thenReturn(Optional.of(jpaServiceTemplate)); + + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); + var result = serviceTemplateProvider.getToscaServiceTemplate(inputServiceTemplate.getName(), + inputServiceTemplate.getVersion()); + + assertThat(result).isEqualTo(jpaServiceTemplate.toAuthorative()); } @Test void testGetServiceTemplate() throws PfModelException { - var serviceTemplate = new ToscaServiceTemplate(); - serviceTemplate.setName("Name"); - serviceTemplate.setVersion("1.0.0"); - var modelsProvider = mock(PolicyModelsProvider.class); - when(modelsProvider.getServiceTemplateList(serviceTemplate.getName(), serviceTemplate.getVersion())) - .thenReturn(List.of(serviceTemplate)); + var jpaServiceTemplate = ProviderUtils.getJpaAndValidate(inputServiceTemplate, JpaToscaServiceTemplate::new, + "toscaServiceTemplate"); + var serviceTemplateRepository = mock(ToscaServiceTemplateRepository.class); + when(serviceTemplateRepository.getFiltered(JpaToscaServiceTemplate.class, inputServiceTemplate.getName(), + inputServiceTemplate.getVersion())).thenReturn(List.of(jpaServiceTemplate)); - var serviceTemplateProvider = new ServiceTemplateProvider(modelsProvider); - var result = - serviceTemplateProvider.getServiceTemplateList(serviceTemplate.getName(), serviceTemplate.getVersion()); + var serviceTemplateProvider = new ServiceTemplateProvider(serviceTemplateRepository); + var result = serviceTemplateProvider.getServiceTemplateList(inputServiceTemplate.getName(), + inputServiceTemplate.getVersion()); assertThat(result).hasSize(1); - assertThat(result.get(0)).isEqualTo(serviceTemplate); + assertThat(result.get(0)).isEqualTo(jpaServiceTemplate.toAuthorative()); } /** diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java index eac1ac305..7deba651f 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java @@ -103,7 +103,7 @@ public class CommissioningProvider { } synchronized (lockit) { - serviceTemplateProvider.createServiceTemplate(serviceTemplate); + serviceTemplate = serviceTemplateProvider.createServiceTemplate(serviceTemplate); List<Participant> participantList = participantProvider.getParticipants(); if (!participantList.isEmpty()) { supervisionHandler.handleSendCommissionMessage(serviceTemplate.getName(), serviceTemplate.getVersion()); @@ -254,6 +254,16 @@ public class CommissioningProvider { } /** + * Get All the requested control loop definitions. + * + * @return the control loop definitions + * @throws PfModelException on errors getting control loop definitions + */ + public List<ToscaServiceTemplate> getAllToscaServiceTemplate() throws PfModelException { + return serviceTemplateProvider.getAllServiceTemplates(); + } + + /** * Get the tosca service template with only required sections. * * @param name the name of the template to get, null for all definitions @@ -363,7 +373,7 @@ public class CommissioningProvider { * @return true if exists instance properties */ private boolean verifyIfInstancePropertiesExists() { - return clProvider.getNodeTemplates(null, null).stream() + return clProvider.getAllNodeTemplates().stream() .anyMatch(nodeTemplate -> nodeTemplate.getKey().getName().contains(INSTANCE_TEXT)); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/PolicyModelConfig.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/PolicyModelConfig.java deleted file mode 100644 index 8a151d886..000000000 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/PolicyModelConfig.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.clamp.controlloop.runtime.config; - -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -public class PolicyModelConfig { - - @Bean - public PolicyModelsProviderParameters policyModelsProviderParameters( - ClRuntimeParameterGroup clRuntimeParameterGroup) { - return clRuntimeParameterGroup.getDatabaseProviderParameters(); - } - - @Bean - public PolicyModelsProvider policyModelsProvider(PolicyModelsProviderParameters policyModelsProviderParameters) - throws PfModelException { - return new PolicyModelsProviderFactory().createPolicyModelsProvider(policyModelsProviderParameters); - } -} diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java index 40d9b249d..0d7d88803 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java @@ -27,7 +27,6 @@ import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -106,7 +105,7 @@ public class ControlLoopInstantiationProvider { ControlLoop controlLoop = new ControlLoop(); Map<UUID, ControlLoopElement> controlLoopElements = new HashMap<>(); - ToscaServiceTemplate toscaServiceTemplate = commissioningProvider.getToscaServiceTemplate(null, null); + ToscaServiceTemplate toscaServiceTemplate = commissioningProvider.getAllToscaServiceTemplate().get(0); Map<String, ToscaNodeTemplate> persistedNodeTemplateMap = toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates(); @@ -155,7 +154,7 @@ public class ControlLoopInstantiationProvider { Map<String, ToscaNodeTemplate> filteredToscaNodeTemplateMap = new HashMap<>(); - ToscaServiceTemplate toscaServiceTemplate = commissioningProvider.getToscaServiceTemplate(name, version); + ToscaServiceTemplate toscaServiceTemplate = commissioningProvider.getAllToscaServiceTemplate().get(0); toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates().forEach((key, nodeTemplate) -> { if (!nodeTemplate.getName().contains(instanceName)) { @@ -185,8 +184,8 @@ public class ControlLoopInstantiationProvider { synchronized (lockit) { for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - var checkControlLoop = controlLoopProvider.getControlLoop(controlLoop.getKey().asIdentifier()); - if (checkControlLoop != null) { + var checkControlLoopOpt = controlLoopProvider.findControlLoop(controlLoop.getKey().asIdentifier()); + if (checkControlLoopOpt.isPresent()) { throw new PfModelException(Response.Status.BAD_REQUEST, controlLoop.getKey().asIdentifier() + " already defined"); } @@ -195,7 +194,7 @@ public class ControlLoopInstantiationProvider { if (!validationResult.isValid()) { throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult()); } - controlLoopProvider.createControlLoops(controlLoops.getControlLoopList()); + controlLoopProvider.saveControlLoops(controlLoops.getControlLoopList()); } var response = new InstantiationResponse(); @@ -218,7 +217,7 @@ public class ControlLoopInstantiationProvider { if (!validationResult.isValid()) { throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult()); } - controlLoopProvider.updateControlLoops(controlLoops.getControlLoopList()); + controlLoopProvider.saveControlLoops(controlLoops.getControlLoopList()); } var response = new InstantiationResponse(); @@ -302,19 +301,18 @@ public class ControlLoopInstantiationProvider { public InstantiationResponse deleteControlLoop(String name, String version) throws PfModelException { var response = new InstantiationResponse(); synchronized (lockit) { - List<ControlLoop> controlLoops = controlLoopProvider.getControlLoops(name, version); - if (controlLoops.isEmpty()) { + var controlLoopOpt = controlLoopProvider.findControlLoop(name, version); + if (controlLoopOpt.isEmpty()) { throw new PfModelException(Response.Status.NOT_FOUND, "Control Loop not found"); } - for (ControlLoop controlLoop : controlLoops) { - if (!ControlLoopState.UNINITIALISED.equals(controlLoop.getState())) { - throw new PfModelException(Response.Status.BAD_REQUEST, - "Control Loop State is still " + controlLoop.getState()); - } + var controlLoop = controlLoopOpt.get(); + if (!ControlLoopState.UNINITIALISED.equals(controlLoop.getState())) { + throw new PfModelException(Response.Status.BAD_REQUEST, + "Control Loop State is still " + controlLoop.getState()); } - response.setAffectedControlLoops(Collections - .singletonList(controlLoopProvider.deleteControlLoop(name, version).getKey().asIdentifier())); + response.setAffectedControlLoops( + List.of(controlLoopProvider.deleteControlLoop(name, version).getKey().asIdentifier())); } return response; } @@ -354,17 +352,26 @@ public class ControlLoopInstantiationProvider { if (participants.isEmpty()) { throw new ControlLoopException(Status.BAD_REQUEST, "No participants registered"); } + var validationResult = new BeanValidationResult("InstantiationCommand", command); List<ControlLoop> controlLoops = new ArrayList<>(command.getControlLoopIdentifierList().size()); for (ToscaConceptIdentifier id : command.getControlLoopIdentifierList()) { - var controlLoop = controlLoopProvider.getControlLoop(id); - controlLoop.setCascadedOrderedState(command.getOrderedState()); - controlLoops.add(controlLoop); + var controlLoopOpt = controlLoopProvider.findControlLoop(id); + if (controlLoopOpt.isEmpty()) { + validationResult.addResult("ToscaConceptIdentifier", id, ValidationStatus.INVALID, + "ControlLoop with id " + id + " not found"); + } else { + var controlLoop = controlLoopOpt.get(); + controlLoop.setCascadedOrderedState(command.getOrderedState()); + controlLoops.add(controlLoop); + } + } + if (validationResult.isValid()) { + validationResult = validateIssueControlLoops(controlLoops, participants); } - BeanValidationResult validationResult = validateIssueControlLoops(controlLoops, participants); if (!validationResult.isValid()) { throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult()); } - controlLoopProvider.updateControlLoops(controlLoops); + controlLoopProvider.saveControlLoops(controlLoops); } supervisionHandler.triggerControlLoopSupervision(command.getControlLoopIdentifierList()); @@ -473,8 +480,8 @@ public class ControlLoopInstantiationProvider { synchronized (lockit) { for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - var checkControlLoop = controlLoopProvider.getControlLoop(controlLoop.getKey().asIdentifier()); - if (checkControlLoop != null) { + var checkControlLoopOpt = controlLoopProvider.findControlLoop(controlLoop.getKey().asIdentifier()); + if (checkControlLoopOpt.isPresent()) { throw new PfModelException(Response.Status.BAD_REQUEST, "Control loop with id " + controlLoop.getKey().asIdentifier() + " already defined"); } @@ -482,7 +489,7 @@ public class ControlLoopInstantiationProvider { toscaSavedNodeTemplate = controlLoopProvider.saveInstanceProperties(serviceTemplate); - controlLoopProvider.createControlLoops(controlLoops.getControlLoopList()); + controlLoopProvider.saveControlLoops(controlLoops.getControlLoopList()); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/rest/InstantiationController.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/rest/InstantiationController.java index b65d3b784..d229e68cb 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/rest/InstantiationController.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/rest/InstantiationController.java @@ -186,10 +186,10 @@ public class InstantiationController extends AbstractRestController { // @formatter:on public ResponseEntity<InstancePropertiesResponse> createInstanceProperties( @RequestHeader( - name = REQUEST_ID_NAME, - required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, @ApiParam(value = "Body of instance properties", required = true) @RequestBody ToscaServiceTemplate body) - throws PfModelException { + throws PfModelException { return ResponseEntity.ok().body(provider.createInstanceProperties(body)); } @@ -249,13 +249,14 @@ public class InstantiationController extends AbstractRestController { // @formatter:on public ResponseEntity<InstantiationResponse> deleteInstanceProperties( - @RequestHeader( - name = REQUEST_ID_NAME, - required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Control Loop definition name", required = true) @RequestParam("name") String name, - @ApiParam(value = "Control Loop definition version") @RequestParam( - value = "version", - required = true) String version) throws PfModelException { + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Control Loop definition name", required = true) @RequestParam("name") String name, + @ApiParam(value = "Control Loop definition version") @RequestParam( + value = "version", + required = true) String version) + throws PfModelException { return ResponseEntity.ok().body(provider.deleteInstanceProperties(name, version)); } @@ -447,7 +448,7 @@ public class InstantiationController extends AbstractRestController { @ApiParam(value = "Control Loop definition name", required = true) @RequestParam("name") String name, @ApiParam(value = "Control Loop definition version") @RequestParam( value = "version", - required = false) String version) + required = true) String version) throws PfModelException { return ResponseEntity.ok().body(provider.deleteControlLoop(name, version)); @@ -559,16 +560,16 @@ public class InstantiationController extends AbstractRestController { ) // @formatter:on public ResponseEntity<ControlLoopOrderStateResponse> getInstantiationOrderState( - @RequestHeader( - name = REQUEST_ID_NAME, - required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Control Loop name", required = false) @RequestParam( - value = "name", - required = false) String name, - @ApiParam(value = "Control Loop version", required = false) @RequestParam( - value = "version", - required = false) String version) - throws PfModelException { + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Control Loop name", required = false) @RequestParam( + value = "name", + required = false) String name, + @ApiParam(value = "Control Loop version", required = false) @RequestParam( + value = "version", + required = false) String version) + throws PfModelException { return ResponseEntity.ok().body(provider.getInstantiationOrderState(name, version)); } @@ -620,16 +621,16 @@ public class InstantiationController extends AbstractRestController { ) // @formatter:on public ResponseEntity<ControlLoopPrimedResponse> getControlLoopPriming( - @RequestHeader( - name = REQUEST_ID_NAME, - required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, - @ApiParam(value = "Control Loop definition name", required = false) @RequestParam( - value = "name", - required = false) String name, - @ApiParam(value = "Control Loop definition version", required = false) @RequestParam( - value = "version", - required = false) String version) - throws PfModelException { + @RequestHeader( + name = REQUEST_ID_NAME, + required = false) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId, + @ApiParam(value = "Control Loop definition name", required = false) @RequestParam( + value = "name", + required = false) String name, + @ApiParam(value = "Control Loop definition version", required = false) @RequestParam( + value = "version", + required = false) String version) + throws PfModelException { return ResponseEntity.ok().body(provider.getControlLoopPriming(name, version)); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java index 802413a6a..cd9309422 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java @@ -174,9 +174,9 @@ public class MonitoringProvider { try { List<ControlLoopElement> clElements = new ArrayList<>(); // Fetch all control loop elements for the control loop - var controlLoop = controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(name, version)); - if (controlLoop != null) { - clElements.addAll(controlLoop.getElements().values()); + var controlLoopOpt = controlLoopProvider.findControlLoop(new ToscaConceptIdentifier(name, version)); + if (controlLoopOpt.isPresent()) { + clElements.addAll(controlLoopOpt.get().getElements().values()); // Collect control loop element statistics for each cl element. for (ControlLoopElement clElement : clElements) { clElementStats.addAll(fetchFilteredClElementStatistics(clElement.getParticipantId().getName(), @@ -203,9 +203,9 @@ public class MonitoringProvider { public List<ToscaConceptIdentifier> getAllParticipantIdsPerControlLoop(String name, String version) throws PfModelException { List<ToscaConceptIdentifier> participantIds = new ArrayList<>(); - var controlLoop = controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(name, version)); - if (controlLoop != null) { - for (ControlLoopElement clElement : controlLoop.getElements().values()) { + var controlLoopOpt = controlLoopProvider.findControlLoop(new ToscaConceptIdentifier(name, version)); + if (controlLoopOpt.isPresent()) { + for (ControlLoopElement clElement : controlLoopOpt.get().getElements().values()) { participantIds.add(clElement.getParticipantId()); } } @@ -224,9 +224,9 @@ public class MonitoringProvider { public Map<String, ToscaConceptIdentifier> getAllClElementsIdPerControlLoop(String name, String version) throws PfModelException { Map<String, ToscaConceptIdentifier> clElementId = new HashMap<>(); - var controlLoop = controlLoopProvider.getControlLoop(new ToscaConceptIdentifier(name, version)); - if (controlLoop != null) { - for (ControlLoopElement clElement : controlLoop.getElements().values()) { + var controlLoopOpt = controlLoopProvider.findControlLoop(new ToscaConceptIdentifier(name, version)); + if (controlLoopOpt.isPresent()) { + for (ControlLoopElement clElement : controlLoopOpt.get().getElements().values()) { clElementId.put(clElement.getId().toString(), clElement.getParticipantId()); } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java index 7f0b85588..6af2788e6 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java @@ -114,7 +114,7 @@ public class SupervisionHandler { superviseControlLoop(controlLoop); - controlLoopProvider.updateControlLoop(controlLoop); + controlLoopProvider.saveControlLoop(controlLoop); } catch (PfModelException pfme) { throw new ControlLoopException(pfme.getErrorResponse().getResponseCode(), pfme.getMessage(), pfme); } @@ -269,7 +269,7 @@ public class SupervisionHandler { var updated = updateState(controlLoop, controlLoopAckMessage.getControlLoopResultMap().entrySet()); updated |= setPrimed(controlLoop); if (updated) { - controlLoopProvider.updateControlLoop(controlLoop); + controlLoopProvider.saveControlLoop(controlLoop); } } else { LOGGER.warn("ControlLoop not found in database {}", controlLoopAckMessage.getControlLoopId()); @@ -425,7 +425,7 @@ public class SupervisionHandler { private int getFirstStartPhase(ControlLoop controlLoop) { ToscaServiceTemplate toscaServiceTemplate = null; try { - toscaServiceTemplate = serviceTemplateProvider.getServiceTemplateList(null, null).get(0); + toscaServiceTemplate = serviceTemplateProvider.getAllServiceTemplates().get(0); } catch (PfModelException e) { throw new PfModelRuntimeException(Status.BAD_REQUEST, "Canont load ToscaServiceTemplate from DB", e); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java index 5ebacdac7..01e035b87 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java @@ -130,11 +130,11 @@ public class SupervisionScanner { } try { - var list = serviceTemplateProvider.getServiceTemplateList(null, null); + var list = serviceTemplateProvider.getAllServiceTemplates(); if (list != null && !list.isEmpty()) { ToscaServiceTemplate toscaServiceTemplate = list.get(0); - for (ControlLoop controlLoop : controlLoopProvider.getControlLoops(null, null)) { + for (ControlLoop controlLoop : controlLoopProvider.getControlLoops()) { scanControlLoop(controlLoop, toscaServiceTemplate, counterCheck); } } @@ -241,7 +241,7 @@ public class SupervisionScanner { controlLoop.getOrderedState()); controlLoop.setState(controlLoop.getOrderedState().asState()); - controlLoopProvider.updateControlLoop(controlLoop); + controlLoopProvider.saveControlLoop(controlLoop); // Clear missed report counter on Control Loop clearFaultAndCounter(controlLoop); @@ -254,8 +254,7 @@ public class SupervisionScanner { : maxSpNotCompleted; var firstStartPhase = ControlLoopState.UNINITIALISED2PASSIVE.equals(controlLoop.getState()) - || ControlLoopState.PASSIVE2RUNNING.equals(controlLoop.getState()) ? defaultMin - : defaultMax; + || ControlLoopState.PASSIVE2RUNNING.equals(controlLoop.getState()) ? defaultMin : defaultMax; if (nextSpNotCompleted != phaseMap.getOrDefault(controlLoop.getKey().asIdentifier(), firstStartPhase)) { phaseMap.put(controlLoop.getKey().asIdentifier(), nextSpNotCompleted); diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ControlLoopUpdatePublisher.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ControlLoopUpdatePublisher.java index 32c0638af..24f60eafc 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ControlLoopUpdatePublisher.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ControlLoopUpdatePublisher.java @@ -72,7 +72,7 @@ public class ControlLoopUpdatePublisher extends AbstractParticipantPublisher<Con controlLoopUpdateMsg.setTimestamp(Instant.now()); ToscaServiceTemplate toscaServiceTemplate; try { - toscaServiceTemplate = serviceTemplateProvider.getServiceTemplateList(null, null).get(0); + toscaServiceTemplate = serviceTemplateProvider.getAllServiceTemplates().get(0); } catch (PfModelException pfme) { LOGGER.warn("Get of tosca service template failed, cannot send participantupdate", pfme); return; diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java index 22fb51cb5..843985e7d 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java @@ -22,27 +22,24 @@ package org.onap.policy.clamp.controlloop.runtime.commissioning; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; -import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ServiceTemplateProvider; import org.onap.policy.clamp.controlloop.runtime.instantiation.InstantiationUtils; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.StandardCoder; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaCapabilityType; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType; @@ -58,23 +55,10 @@ class CommissioningProviderTest { "src/test/resources/rest/servicetemplates/pmsh_multiple_cl_tosca.yaml"; private static final String COMMON_TOSCA_SERVICE_TEMPLATE_YAML = "src/test/resources/rest/servicetemplates/full-tosca-with-common-properties.yaml"; - private static final String TEMPLATE_IS_NULL = ".*serviceTemplate is marked non-null but is null"; - private PolicyModelsProvider modelsProvider = null; - private ControlLoopProvider clProvider = null; private static final Coder CODER = new StandardCoder(); private final ObjectMapper mapper = new ObjectMapper(); - @AfterEach - void close() throws Exception { - if (modelsProvider != null) { - modelsProvider.close(); - } - if (clProvider != null) { - clProvider.close(); - } - } - /** * Test the fetching of control loop definitions (ToscaServiceTemplates). * @@ -82,35 +66,20 @@ class CommissioningProviderTest { */ @Test void testGetControlLoopDefinitions() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("getCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var clProvider = mock(ControlLoopProvider.class); var participantProvider = mock(ParticipantProvider.class); + var serviceTemplateProvider = mock(ServiceTemplateProvider.class); - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); - ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); + CommissioningProvider provider = + new CommissioningProvider(serviceTemplateProvider, clProvider, null, participantProvider); List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); assertThat(listOfTemplates).isEmpty(); - provider.createControlLoopDefinitions(serviceTemplate); + when(clProvider.getFilteredNodeTemplates(any())) + .thenReturn(List.of(new ToscaNodeTemplate(), new ToscaNodeTemplate())); listOfTemplates = provider.getControlLoopDefinitions(null, null); assertThat(listOfTemplates).hasSize(2); - - // Test Filtering - listOfTemplates = provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); - assertThat(listOfTemplates).hasSize(1); - for (ToscaNodeTemplate template : listOfTemplates) { - // Other CL elements contain PMSD instead of PMSH in their name - assertThat(template.getName()).doesNotContain("PMSD"); - } - - // Test Wrong Name - listOfTemplates = provider.getControlLoopDefinitions("WrongControlLoopName", "0.0.0"); - assertThat(listOfTemplates).isEmpty(); - } /** @@ -120,25 +89,27 @@ class CommissioningProviderTest { */ @Test void testCreateControlLoopDefinitions() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("createCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var serviceTemplateProvider = mock(ServiceTemplateProvider.class); + var clProvider = mock(ControlLoopProvider.class); var participantProvider = mock(ParticipantProvider.class); - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); - // Test Service template is null - assertThatThrownBy(() -> provider.createControlLoopDefinitions(null)).hasMessageMatching(TEMPLATE_IS_NULL); + CommissioningProvider provider = + new CommissioningProvider(serviceTemplateProvider, clProvider, null, participantProvider); + List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); assertThat(listOfTemplates).isEmpty(); ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); + when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate); // Response should return the number of node templates present in the service template List<ToscaConceptIdentifier> affectedDefinitions = provider.createControlLoopDefinitions(serviceTemplate).getAffectedControlLoopDefinitions(); assertThat(affectedDefinitions).hasSize(13); + + when(clProvider.getFilteredNodeTemplates(any())) + .thenReturn(List.of(new ToscaNodeTemplate(), new ToscaNodeTemplate())); + listOfTemplates = provider.getControlLoopDefinitions(null, null); assertThat(listOfTemplates).hasSize(2); } @@ -150,18 +121,20 @@ class CommissioningProviderTest { */ @Test void testGetToscaServiceTemplate() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("getCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var serviceTemplateProvider = mock(ServiceTemplateProvider.class); + var clProvider = mock(ControlLoopProvider.class); var participantProvider = mock(ParticipantProvider.class); - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); + CommissioningProvider provider = + new CommissioningProvider(serviceTemplateProvider, clProvider, null, participantProvider); ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(COMMON_TOSCA_SERVICE_TEMPLATE_YAML); + when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate); provider.createControlLoopDefinitions(serviceTemplate); + verify(serviceTemplateProvider).createServiceTemplate(serviceTemplate); + + when(serviceTemplateProvider.getToscaServiceTemplate(eq(null), eq(null))).thenReturn(serviceTemplate); ToscaServiceTemplate returnedServiceTemplate = provider.getToscaServiceTemplate(null, null); assertThat(returnedServiceTemplate).isNotNull(); @@ -179,19 +152,20 @@ class CommissioningProviderTest { */ @Test void testGetToscaServiceTemplateReduced() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("getCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var serviceTemplateProvider = mock(ServiceTemplateProvider.class); + var clProvider = mock(ControlLoopProvider.class); var participantProvider = mock(ParticipantProvider.class); - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); + CommissioningProvider provider = + new CommissioningProvider(serviceTemplateProvider, clProvider, null, participantProvider); ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(COMMON_TOSCA_SERVICE_TEMPLATE_YAML); + when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate); provider.createControlLoopDefinitions(serviceTemplate); + when(serviceTemplateProvider.getServiceTemplateList(any(), any())).thenReturn(List.of(serviceTemplate)); + String returnedServiceTemplate = provider.getToscaServiceTemplateReduced(null, null); assertThat(returnedServiceTemplate).isNotNull(); ToscaServiceTemplate parsedServiceTemplate = CODER.decode(returnedServiceTemplate, ToscaServiceTemplate.class); @@ -207,17 +181,15 @@ class CommissioningProviderTest { */ @Test void testGetToscaServiceTemplateSchema() throws Exception { - - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("getCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var serviceTemplateProvider = mock(ServiceTemplateProvider.class); + var clProvider = mock(ControlLoopProvider.class); var participantProvider = mock(ParticipantProvider.class); - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); + CommissioningProvider provider = + new CommissioningProvider(serviceTemplateProvider, clProvider, null, participantProvider); ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(COMMON_TOSCA_SERVICE_TEMPLATE_YAML); + when(serviceTemplateProvider.createServiceTemplate(serviceTemplate)).thenReturn(serviceTemplate); provider.createControlLoopDefinitions(serviceTemplate); @@ -246,89 +218,4 @@ class CommissioningProviderTest { assertThat(localServiceTemplateSchema).isEqualTo(returnedServiceTemplateSchema); } } - - /** - * Test the deletion of control loop definitions (ToscaServiceTemplate). - * - * @throws Exception . - */ - @Test - void testDeleteControlLoopDefinitions() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("deleteCLDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - var participantProvider = mock(ParticipantProvider.class); - - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); - ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); - - List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); - - provider.createControlLoopDefinitions(serviceTemplate); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).hasSize(2); - - provider.deleteControlLoopDefinition(serviceTemplate.getName(), serviceTemplate.getVersion()); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); - } - - /** - * Test the fetching of control loop element definitions. - * - * @throws Exception . - */ - @Test - void testGetControlLoopElementDefinitions() throws Exception { - ClRuntimeParameterGroup clRuntimeParameterGroup = CommonTestData.geParameterGroup("getCLElDefinitions"); - modelsProvider = - CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - var participantProvider = mock(ParticipantProvider.class); - - CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), - clProvider, null, participantProvider); - ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); - - provider.getControlLoopDefinitions(null, null); - - provider.createControlLoopDefinitions(serviceTemplate); - List<ToscaNodeTemplate> controlLoopDefinitionList = - provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); - - List<ToscaNodeTemplate> controlLoopElementNodeTemplates = - provider.getControlLoopElementDefinitions(controlLoopDefinitionList.get(0)); - - // 4 PMSH control loop elements definitions. - assertThat(controlLoopElementNodeTemplates).hasSize(4); - - List<ToscaNodeType> derivedTypes = getDerivedNodeTypes(serviceTemplate); - for (ToscaNodeTemplate template : controlLoopElementNodeTemplates) { - assertTrue(checkNodeType(template, derivedTypes)); - } - } - - private boolean checkNodeType(ToscaNodeTemplate template, List<ToscaNodeType> derivedNodeTypes) { - String controlLoopElementType = "org.onap.policy.clamp.controlloop.ControlLoopElement"; - for (ToscaNodeType derivedType : derivedNodeTypes) { - if (template.getType().equals(derivedType.getName()) || template.getType().equals(controlLoopElementType)) { - return true; - } - } - return false; - } - - private List<ToscaNodeType> getDerivedNodeTypes(ToscaServiceTemplate serviceTemplate) { - String type = "org.onap.policy.clamp.controlloop.ControlLoopElement"; - List<ToscaNodeType> nodeTypes = new ArrayList<>(); - for (ToscaNodeType nodeType : serviceTemplate.getNodeTypes().values()) { - if (nodeType.getDerivedFrom().equals(type)) { - nodeTypes.add(nodeType); - } - } - return nodeTypes; - } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/rest/CommissioningControllerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/rest/CommissioningControllerTest.java index 9d1435e7c..e4a121439 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/rest/CommissioningControllerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/rest/CommissioningControllerTest.java @@ -93,8 +93,7 @@ class CommissioningControllerTest extends CommonRestController { @AfterEach public void cleanDatabase() throws Exception { - deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion()); - deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion()); + deleteEntryInDB(); } @Test @@ -272,33 +271,33 @@ class CommissioningControllerTest extends CommonRestController { @Test void testDelete() throws Exception { - createEntryInDB(); + var serviceTemplateCreated = createEntryInDB(); Invocation.Builder invocationBuilder = super.sendRequest(COMMISSIONING_ENDPOINT + "?name=" - + serviceTemplate.getName() + "&version=" + serviceTemplate.getVersion()); + + serviceTemplateCreated.getName() + "&version=" + serviceTemplateCreated.getVersion()); // Call delete with no info Response resp = invocationBuilder.delete(); assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); - List<ToscaServiceTemplate> templatesInDB = serviceTemplateProvider.getServiceTemplateList(null, null); + List<ToscaServiceTemplate> templatesInDB = serviceTemplateProvider.getAllServiceTemplates(); assertThat(templatesInDB).isEmpty(); - } - private synchronized void createEntryInDB() throws Exception { - deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion()); - serviceTemplateProvider.createServiceTemplate(serviceTemplate); + private synchronized ToscaServiceTemplate createEntryInDB() throws Exception { + deleteEntryInDB(); + return serviceTemplateProvider.createServiceTemplate(serviceTemplate); } // Delete entries from the DB after relevant tests - private synchronized void deleteEntryInDB(String name, String version) throws Exception { - if (!serviceTemplateProvider.getServiceTemplateList(null, null).isEmpty()) { - serviceTemplateProvider.deleteServiceTemplate(name, version); + private synchronized void deleteEntryInDB() throws Exception { + var list = serviceTemplateProvider.getAllServiceTemplates(); + if (!list.isEmpty()) { + serviceTemplateProvider.deleteServiceTemplate(list.get(0).getName(), list.get(0).getVersion()); } } private synchronized void createFullEntryInDbWithCommonProps() throws Exception { - deleteEntryInDB(commonPropertiesServiceTemplate.getName(), commonPropertiesServiceTemplate.getVersion()); + deleteEntryInDB(); serviceTemplateProvider.createServiceTemplate(commonPropertiesServiceTemplate); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java index caad5a4e9..ba1cc0813 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java @@ -24,17 +24,16 @@ package org.onap.policy.clamp.controlloop.runtime.instantiation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; -import java.util.ArrayList; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; +import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; @@ -42,26 +41,15 @@ import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; -import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ClElementStatisticsProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider; -import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantStatisticsProvider; -import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ServiceTemplateProvider; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse; import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider; import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ControlLoopStateChangePublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ControlLoopUpdatePublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantDeregisterAckPublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantRegisterAckPublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantUpdatePublisher; import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; /** @@ -102,80 +90,45 @@ class ControlLoopInstantiationProviderTest { private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); - private static SupervisionHandler supervisionHandler; - private static CommissioningProvider commissioningProvider; - private static ControlLoopProvider clProvider; - private static PolicyModelsProvider modelsProvider; - @BeforeAll public static void setUpBeforeClass() throws Exception { serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_TEMPLATE_YAML); } - /** - * setup Db Provider Parameters. - * - * @throws PfModelException if an error occurs - */ - @BeforeAll - public static void setupDbProviderParameters() throws PfModelException { - ClRuntimeParameterGroup controlLoopParameters = CommonTestData.geParameterGroup("instantproviderdb"); - - modelsProvider = CommonTestData.getPolicyModelsProvider(controlLoopParameters.getDatabaseProviderParameters()); - clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); + @Test + void testIntanceResponses() throws Exception { var participantProvider = Mockito.mock(ParticipantProvider.class); + var clProvider = mock(ControlLoopProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var commissioningProvider = mock(CommissioningProvider.class); - var participantStatisticsProvider = Mockito.mock(ParticipantStatisticsProvider.class); - var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); - commissioningProvider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, - participantProvider); - var monitoringProvider = - new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); - var controlLoopUpdatePublisher = Mockito.mock(ControlLoopUpdatePublisher.class); - var controlLoopStateChangePublisher = Mockito.mock(ControlLoopStateChangePublisher.class); - var participantRegisterAckPublisher = Mockito.mock(ParticipantRegisterAckPublisher.class); - var participantDeregisterAckPublisher = Mockito.mock(ParticipantDeregisterAckPublisher.class); - var participantUpdatePublisher = Mockito.mock(ParticipantUpdatePublisher.class); - var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class); - - supervisionHandler = new SupervisionHandler(clProvider, participantProvider, monitoringProvider, - serviceTemplateProvider, controlLoopUpdatePublisher, controlLoopStateChangePublisher, - participantRegisterAckPublisher, participantDeregisterAckPublisher, participantUpdatePublisher); - } - - @BeforeEach - public void populateDb() throws Exception { - createEntryInDB(); - } - - @AfterAll - public static void closeDbProvider() throws PfModelException { - clProvider.close(); - modelsProvider.close(); - } + when(commissioningProvider.getAllToscaServiceTemplate()).thenReturn(List.of(serviceTemplate)); + when(commissioningProvider.getToscaServiceTemplate(ID_NAME, ID_VERSION)).thenReturn(serviceTemplate); - @AfterEach - public void cleanDatabase() throws Exception { - deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion()); - } - - @Test - void testIntanceResponses() throws PfModelException { - var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); var instancePropertyList = instantiationProvider.createInstanceProperties(serviceTemplate); assertNull(instancePropertyList.getErrorDetails()); var id = new ToscaConceptIdentifier(ID_NAME, ID_VERSION); assertEquals(id, instancePropertyList.getAffectedInstanceProperties().get(0)); + + ControlLoops controlLoops = + InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Crud"); + var controlLoop = controlLoops.getControlLoopList().get(0); + controlLoop.setName(ID_NAME); + controlLoop.setVersion(ID_VERSION); + when(clProvider.getControlLoops(ID_NAME, ID_VERSION)).thenReturn(List.of(controlLoop)); + var instanceOrderState = instantiationProvider.getInstantiationOrderState(ID_NAME, ID_VERSION); assertEquals(ControlLoopOrderedState.UNINITIALISED, instanceOrderState.getOrderedState()); assertEquals(ID_NAME, instanceOrderState.getControlLoopIdentifierList().get(0).getName()); - assertNotNull(clProvider.getControlLoop(id)); + when(clProvider.findControlLoop(ID_NAME, ID_VERSION)).thenReturn(Optional.of(controlLoop)); + when(clProvider.deleteControlLoop(ID_NAME, ID_VERSION)).thenReturn(controlLoop); + var instanceResponse = instantiationProvider.deleteInstanceProperties(ID_NAME, ID_VERSION); assertEquals(ID_NAME, instanceResponse.getAffectedControlLoops().get(0).getName()); - assertNull(clProvider.getControlLoop(id)); + } @Test @@ -184,20 +137,41 @@ class ControlLoopInstantiationProviderTest { var participants = CommonTestData.createParticipants(); when(participantProvider.getParticipants()).thenReturn(participants); - ControlLoops controlLoopsCreate = - InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Crud"); - ControlLoops controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); + var commissioningProvider = mock(CommissioningProvider.class); + var toscaNodeTemplate1 = new ToscaNodeTemplate(); + toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyControlLoopElement"); + toscaNodeTemplate1.setVersion("1.2.3"); + when(commissioningProvider.getControlLoopDefinitions(anyString(), anyString())) + .thenReturn(List.of(toscaNodeTemplate1)); + + var toscaNodeTemplate2 = new ToscaNodeTemplate(); + toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyControlLoopElement"); + toscaNodeTemplate2.setVersion("1.2.3"); + var toscaNodeTemplate3 = new ToscaNodeTemplate(); + toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_ControlLoopElement"); + toscaNodeTemplate3.setVersion("1.2.3"); + var toscaNodeTemplate4 = new ToscaNodeTemplate(); + toscaNodeTemplate4.setName("org.onap.domain.pmsh.PMSH_DCAEMicroservice"); + toscaNodeTemplate4.setVersion("1.2.3"); + + when(commissioningProvider.getControlLoopElementDefinitions(toscaNodeTemplate1)) + .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3, toscaNodeTemplate4)); + + var supervisionHandler = mock(SupervisionHandler.class); + var clProvider = mock(ControlLoopProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); + ControlLoops controlLoopsCreate = + InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Crud"); InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); - assertThat(controlLoopsCreate).isEqualTo(controlLoopsDb); + verify(clProvider).saveControlLoops(controlLoopsCreate.getControlLoopList()); + + for (var controlLoop : controlLoopsCreate.getControlLoopList()) { + when(clProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion())) + .thenReturn(List.of(controlLoop)); - for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { ControlLoops controlLoopsGet = instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); @@ -206,27 +180,25 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoopsUpdate = InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_UPDATE_JSON, "Crud"); - assertThat(controlLoopsUpdate).isNotEqualTo(controlLoopsDb); instantiationResponse = instantiationProvider.updateControlLoops(controlLoopsUpdate); InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsUpdate); - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); - assertThat(controlLoopsUpdate).isEqualTo(controlLoopsDb); + verify(clProvider).saveControlLoops(controlLoopsUpdate.getControlLoopList()); + + for (var controlLoop : controlLoopsUpdate.getControlLoopList()) { + when(clProvider.findControlLoop(controlLoop.getKey().asIdentifier())).thenReturn(Optional.of(controlLoop)); + when(clProvider.findControlLoop(controlLoop.getName(), controlLoop.getVersion())) + .thenReturn(Optional.of(controlLoop)); + when(clProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion())).thenReturn(controlLoop); + } InstantiationCommand instantiationCommand = InstantiationUtils.getInstantiationCommandFromResource(CL_INSTANTIATION_CHANGE_STATE_JSON, "Crud"); instantiationResponse = instantiationProvider.issueControlLoopCommand(instantiationCommand); InstantiationUtils.assertInstantiationResponse(instantiationResponse, instantiationCommand); - for (ToscaConceptIdentifier toscaConceptIdentifier : instantiationCommand.getControlLoopIdentifierList()) { - ControlLoops controlLoopsGet = instantiationProvider.getControlLoops(toscaConceptIdentifier.getName(), - toscaConceptIdentifier.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(instantiationCommand.getOrderedState()) - .isEqualTo(controlLoopsGet.getControlLoopList().get(0).getOrderedState()); - } + verify(supervisionHandler).triggerControlLoopSupervision(instantiationCommand.getControlLoopIdentifierList()); // in order to delete a controlLoop the state must be UNINITIALISED controlLoopsCreate.getControlLoopList().forEach(cl -> cl.setState(ControlLoopState.UNINITIALISED)); @@ -234,27 +206,9 @@ class ControlLoopInstantiationProviderTest { for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } - - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); - } - - private ControlLoops getControlLoopsFromDb(ControlLoops controlLoopsSource) throws Exception { - - ControlLoops controlLoopsDb = new ControlLoops(); - controlLoopsDb.setControlLoopList(new ArrayList<>()); - var participantProvider = Mockito.mock(ParticipantProvider.class); - - var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, - supervisionHandler, participantProvider); - for (ControlLoop controlLoop : controlLoopsSource.getControlLoopList()) { - ControlLoops controlLoopsFromDb = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - controlLoopsDb.getControlLoopList().addAll(controlLoopsFromDb.getControlLoopList()); + verify(clProvider).deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); } - return controlLoopsDb; } @Test @@ -262,10 +216,12 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoops = InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Delete"); - assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); ControlLoop controlLoop0 = controlLoops.getControlLoopList().get(0); var participantProvider = Mockito.mock(ParticipantProvider.class); + var clProvider = mock(ControlLoopProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var commissioningProvider = mock(CommissioningProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -274,26 +230,19 @@ class ControlLoopInstantiationProviderTest { () -> instantiationProvider.deleteControlLoop(controlLoop0.getName(), controlLoop0.getVersion())) .hasMessageMatching(CONTROL_LOOP_NOT_FOUND); - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoops), - controlLoops); - for (ControlLoopState state : ControlLoopState.values()) { if (!ControlLoopState.UNINITIALISED.equals(state)) { assertThatDeleteThrownBy(controlLoops, state); } } - controlLoop0.setState(ControlLoopState.UNINITIALISED); - instantiationProvider.updateControlLoops(controlLoops); for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + when(clProvider.findControlLoop(controlLoop.getName(), controlLoop.getVersion())) + .thenReturn(Optional.of(controlLoop)); + when(clProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion())).thenReturn(controlLoop); - for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); } } @@ -301,11 +250,16 @@ class ControlLoopInstantiationProviderTest { ControlLoop controlLoop = controlLoops.getControlLoopList().get(0); controlLoop.setState(state); var participantProvider = Mockito.mock(ParticipantProvider.class); + var clProvider = mock(ControlLoopProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var commissioningProvider = mock(CommissioningProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); - instantiationProvider.updateControlLoops(controlLoops); + when(clProvider.findControlLoop(controlLoop.getName(), controlLoop.getVersion())) + .thenReturn(Optional.of(controlLoop)); + assertThatThrownBy( () -> instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion())) .hasMessageMatching(String.format(DELETE_BAD_REQUEST, state)); @@ -313,45 +267,82 @@ class ControlLoopInstantiationProviderTest { @Test void testCreateControlLoops_NoDuplicates() throws Exception { + var commissioningProvider = mock(CommissioningProvider.class); + + var toscaNodeTemplate1 = new ToscaNodeTemplate(); + toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyControlLoopElement"); + toscaNodeTemplate1.setVersion("1.2.3"); + when(commissioningProvider.getControlLoopDefinitions(anyString(), anyString())) + .thenReturn(List.of(toscaNodeTemplate1)); + + var toscaNodeTemplate2 = new ToscaNodeTemplate(); + toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyControlLoopElement"); + toscaNodeTemplate2.setVersion("1.2.3"); + var toscaNodeTemplate3 = new ToscaNodeTemplate(); + toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_ControlLoopElement"); + toscaNodeTemplate3.setVersion("1.2.3"); + var toscaNodeTemplate4 = new ToscaNodeTemplate(); + toscaNodeTemplate4.setName("org.onap.domain.pmsh.PMSH_DCAEMicroservice"); + toscaNodeTemplate4.setVersion("1.2.3"); + + when(commissioningProvider.getControlLoopElementDefinitions(toscaNodeTemplate1)) + .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3, toscaNodeTemplate4)); ControlLoops controlLoopsCreate = InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "NoDuplicates"); - ControlLoops controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); - + var clProvider = mock(ControlLoopProvider.class); var participantProvider = Mockito.mock(ParticipantProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); + when(clProvider.findControlLoop(controlLoopsCreate.getControlLoopList().get(0).getKey().asIdentifier())) + .thenReturn(Optional.of(controlLoopsCreate.getControlLoopList().get(0))); + assertThatThrownBy(() -> instantiationProvider.createControlLoops(controlLoopsCreate)).hasMessageMatching( controlLoopsCreate.getControlLoopList().get(0).getKey().asIdentifier() + " already defined"); - - for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } } @Test void testCreateControlLoops_CommissionedClElementNotFound() throws Exception { - + var toscaNodeTemplate1 = new ToscaNodeTemplate(); + toscaNodeTemplate1.setName("org.onap.domain.pmsh.PMSH_MonitoringPolicyControlLoopElement"); + toscaNodeTemplate1.setVersion("1.2.3"); + + var toscaNodeTemplate2 = new ToscaNodeTemplate(); + toscaNodeTemplate2.setName("org.onap.domain.pmsh.PMSH_OperationalPolicyControlLoopElement"); + toscaNodeTemplate2.setVersion("1.2.3"); + var toscaNodeTemplate3 = new ToscaNodeTemplate(); + toscaNodeTemplate3.setName("org.onap.domain.pmsh.PMSH_CDS_ControlLoopElement"); + toscaNodeTemplate3.setVersion("1.2.3"); + var commissioningProvider = mock(CommissioningProvider.class); ControlLoops controlLoops = InstantiationUtils .getControlLoopsFromResource(CL_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON, "ClElementNotFound"); - var participantProvider = Mockito.mock(ParticipantProvider.class); - var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, - participantProvider); + when(commissioningProvider.getControlLoopDefinitions( + controlLoops.getControlLoopList().get(0).getDefinition().getName(), + controlLoops.getControlLoopList().get(0).getDefinition().getVersion())) + .thenReturn(List.of(toscaNodeTemplate1)); - // to validate control Loop, it needs to define ToscaServiceTemplate - // InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + when(commissioningProvider.getControlLoopElementDefinitions(toscaNodeTemplate1)) + .thenReturn(List.of(toscaNodeTemplate1, toscaNodeTemplate2, toscaNodeTemplate3)); - assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); + var clProvider = mock(ControlLoopProvider.class); + var participantProvider = mock(ParticipantProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, + participantProvider); assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) .hasMessageMatching(CONTROLLOOP_ELEMENT_NAME_NOT_FOUND); + + assertThatThrownBy(() -> provider.updateControlLoops(controlLoops)) + .hasMessageMatching(CONTROLLOOP_ELEMENT_NAME_NOT_FOUND); } @Test @@ -359,98 +350,29 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoops = InstantiationUtils .getControlLoopsFromResource(CL_INSTANTIATION_CONTROLLOOP_DEFINITION_NOT_FOUND_JSON, "ClNotFound"); - assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); - var participantProvider = Mockito.mock(ParticipantProvider.class); + var clProvider = mock(ControlLoopProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var commissioningProvider = mock(CommissioningProvider.class); var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); + assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) .hasMessageMatching(CONTROLLOOP_DEFINITION_NOT_FOUND); + + assertThatThrownBy(() -> provider.updateControlLoops(controlLoops)) + .hasMessageMatching(CONTROLLOOP_DEFINITION_NOT_FOUND); } @Test void testIssueControlLoopCommand_OrderedStateInvalid() throws ControlLoopRuntimeException, IOException { var participantProvider = Mockito.mock(ParticipantProvider.class); + var clProvider = mock(ControlLoopProvider.class); + var supervisionHandler = mock(SupervisionHandler.class); + var commissioningProvider = mock(CommissioningProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); assertThatThrownBy(() -> instantiationProvider.issueControlLoopCommand(new InstantiationCommand())) .hasMessageMatching(ORDERED_STATE_INVALID); } - - @Test - void testInstantiationVersions() throws Exception { - // create controlLoops V1 - ControlLoops controlLoopsV1 = - InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V1"); - assertThat(getControlLoopsFromDb(controlLoopsV1).getControlLoopList()).isEmpty(); - - var participantProvider = Mockito.mock(ParticipantProvider.class); - var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, - supervisionHandler, participantProvider); - - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV1), - controlLoopsV1); - - // create controlLoops V2 - ControlLoops controlLoopsV2 = - InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V2"); - assertThat(getControlLoopsFromDb(controlLoopsV2).getControlLoopList()).isEmpty(); - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV2), - controlLoopsV2); - - // GET controlLoops V2 - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); - } - - // DELETE controlLoops V1 - for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } - - // GET controlLoops V1 is not available - for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); - } - - // GET controlLoops V2 is still available - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); - } - - // DELETE controlLoops V2 - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } - - // GET controlLoops V2 is not available - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); - } - } - - private synchronized void deleteEntryInDB(String name, String version) throws Exception { - if (!modelsProvider.getServiceTemplateList(null, null).isEmpty()) { - modelsProvider.deleteServiceTemplate(name, version); - } - } - - private synchronized void createEntryInDB() throws Exception { - try { - deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion()); - modelsProvider.createServiceTemplate(serviceTemplate); - } catch (Exception e) { - e.printStackTrace(); - } - } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java index 0fc473106..ebd25c3c1 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java @@ -35,10 +35,13 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ServiceTemplateProvider; +import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.ControlLoopOrderStateResponse; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.ControlLoopPrimedResponse; +import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstancePropertiesResponse; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse; import org.onap.policy.clamp.controlloop.runtime.instantiation.ControlLoopInstantiationProvider; @@ -64,6 +67,9 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; @TestPropertySource(locations = {"classpath:application_test.properties"}) class InstantiationControllerTest extends CommonRestController { + private static final String ID_NAME = "PMSH_Instance1"; + private static final String ID_VERSION = "1.2.3"; + private static final String CL_INSTANTIATION_CREATE_JSON = "src/test/resources/rest/controlloops/ControlLoops.json"; private static final String CL_INSTANTIATION_UPDATE_JSON = @@ -76,10 +82,10 @@ class InstantiationControllerTest extends CommonRestController { "src/test/resources/rest/servicetemplates/pmsh_multiple_cl_tosca.yaml"; private static final String INSTANTIATION_ENDPOINT = "instantiation"; - private static final String INSTANTIATION_COMMAND_ENDPOINT = "instantiation/command"; - private static final String PRIMING_ENDPOINT = "controlLoopPriming"; + private static final String INSTANTIATION_PROPERTIES = "instanceProperties"; + private static final String INSTANTIATION_STATE = "instantiationState"; private static ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); @@ -112,7 +118,7 @@ class InstantiationControllerTest extends CommonRestController { @AfterEach public void cleanDatabase() throws Exception { - deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion()); + deleteEntryInDB(); } @Test @@ -256,7 +262,8 @@ class InstantiationControllerTest extends CommonRestController { @Test void testDelete_NoResultWithThisName() throws Exception { - Invocation.Builder invocationBuilder = super.sendRequest(INSTANTIATION_ENDPOINT + "?name=noResultWithThisName"); + Invocation.Builder invocationBuilder = + super.sendRequest(INSTANTIATION_ENDPOINT + "?name=noResultWithThisName&version=1.0.1"); Response resp = invocationBuilder.delete(); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), resp.getStatus()); InstantiationResponse instResponse = resp.readEntity(InstantiationResponse.class); @@ -298,8 +305,7 @@ class InstantiationControllerTest extends CommonRestController { Invocation.Builder invocationBuilder = super.sendRequest(INSTANTIATION_ENDPOINT + "?name=" + controlLoopFromRsc.getKey().getName()); Response resp = invocationBuilder.delete(); - // should be BAD_REQUEST - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), resp.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), resp.getStatus()); } } @@ -349,14 +355,43 @@ class InstantiationControllerTest extends CommonRestController { } } - private synchronized void deleteEntryInDB(String name, String version) throws Exception { - if (!serviceTemplateProvider.getServiceTemplateList(null, null).isEmpty()) { - serviceTemplateProvider.deleteServiceTemplate(name, version); + @Test + void testIntanceProperties() throws Exception { + Invocation.Builder invocationBuilder = super.sendRequest(INSTANTIATION_PROPERTIES); + Response resp = invocationBuilder.post(Entity.json(serviceTemplate)); + assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); + var instancePropertyList = resp.readEntity(InstancePropertiesResponse.class); + assertNull(instancePropertyList.getErrorDetails()); + var id = new ToscaConceptIdentifier(ID_NAME, ID_VERSION); + assertEquals(id, instancePropertyList.getAffectedInstanceProperties().get(0)); + + invocationBuilder = super.sendRequest(INSTANTIATION_STATE + "?name=" + ID_NAME + "&version=" + ID_VERSION); + resp = invocationBuilder.buildGet().invoke(); + assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); + var instanceOrderState = resp.readEntity(ControlLoopOrderStateResponse.class); + assertEquals(ControlLoopOrderedState.UNINITIALISED, instanceOrderState.getOrderedState()); + assertEquals(ID_NAME, instanceOrderState.getControlLoopIdentifierList().get(0).getName()); + ControlLoops controlLoopsGet = instantiationProvider.getControlLoops(ID_NAME, ID_VERSION); + assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); + + invocationBuilder = super.sendRequest(INSTANTIATION_PROPERTIES + "?name=" + ID_NAME + "&version=" + ID_VERSION); + resp = invocationBuilder.delete(); + assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); + var instanceResponse = resp.readEntity(InstantiationResponse.class); + assertEquals(ID_NAME, instanceResponse.getAffectedControlLoops().get(0).getName()); + controlLoopsGet = instantiationProvider.getControlLoops(ID_NAME, ID_VERSION); + assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); + } + + private synchronized void deleteEntryInDB() throws Exception { + var list = serviceTemplateProvider.getAllServiceTemplates(); + if (!list.isEmpty()) { + serviceTemplateProvider.deleteServiceTemplate(list.get(0).getName(), list.get(0).getVersion()); } } private synchronized void createEntryInDB() throws Exception { - deleteEntryInDB(serviceTemplate.getName(), serviceTemplate.getVersion()); + deleteEntryInDB(); serviceTemplateProvider.createServiceTemplate(serviceTemplate); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java index 2233e862c..cbc4c7104 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java @@ -35,9 +35,9 @@ import java.time.Instant; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import javax.ws.rs.core.Response; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -48,8 +48,6 @@ import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ClElementStatisticsProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantStatisticsProvider; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -85,8 +83,6 @@ class TestMonitoringProvider { private static ClElementStatisticsList inputClElementStatistics; private static ClElementStatisticsList invalidClElementInput; - private ControlLoopProvider clProvider = null; - @BeforeAll public static void beforeSetupStatistics() throws CoderException { // Reading input json for statistics data @@ -98,19 +94,11 @@ class TestMonitoringProvider { invalidClElementInput = CODER.decode(new File(INVALID_CL_ELEMENT_JSON_INPUT), ClElementStatisticsList.class); } - @AfterEach - void close() throws Exception { - if (clProvider != null) { - clProvider.close(); - } - } - @Test void testCreateParticipantStatistics() throws Exception { var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class); var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); - ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("createparStat"); - clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + var clProvider = mock(ControlLoopProvider.class); MonitoringProvider provider = new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); @@ -152,8 +140,7 @@ class TestMonitoringProvider { when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME2), any(), any(), any(), eq(null), eq(SORT_DESC), eq(1))).thenReturn(List.of(inputParticipantStatistics.getStatisticsList().get(2))); - ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getparStat"); - clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + var clProvider = mock(ControlLoopProvider.class); var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); MonitoringProvider provider = new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); @@ -190,8 +177,7 @@ class TestMonitoringProvider { when(clElementStatisticsProvider.createClElementStatistics(eq(null))) .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, CL_LIST_IS_NULL)); - ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("createelemstat"); - clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + var clProvider = mock(ControlLoopProvider.class); var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class); MonitoringProvider provider = @@ -218,8 +204,12 @@ class TestMonitoringProvider { void testGetClElementStatistics() throws Exception { var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class); var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); - ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getelemstat"); - clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + var clProvider = mock(ControlLoopProvider.class); + + when(clElementStatisticsProvider.getFilteredClElementStatistics(eq(ID_NAME1), any(), any(), any(), anyMap(), + eq(SORT_DESC), eq(0))) + .thenReturn(List.of(inputClElementStatistics.getClElementStatistics().get(0), + inputClElementStatistics.getClElementStatistics().get(1))); when(clElementStatisticsProvider.getFilteredClElementStatistics(eq(ID_NAME1), any(), any(), any(), anyMap(), eq(SORT_DESC), eq(0))) @@ -266,7 +256,8 @@ class TestMonitoringProvider { var element = new ControlLoopElement(); element.setParticipantId(new ToscaConceptIdentifier(ID_NAME1, ID_VERSION1)); controlLoop.setElements(Map.of(UUID.randomUUID(), element)); - when(mockClProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME2, ID_VERSION1))).thenReturn(controlLoop); + when(mockClProvider.findControlLoop(new ToscaConceptIdentifier(ID_NAME2, ID_VERSION1))) + .thenReturn(Optional.of(controlLoop)); when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME1), eq(ID_VERSION1), any(), any(), eq(null), eq(SORT_DESC), eq(0))) @@ -300,7 +291,8 @@ class TestMonitoringProvider { new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, mockClProvider); // Mock controlloop data to be returned for the given CL Id - when(mockClProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME3, ID_VERSION1))).thenReturn(mockCL); + when(mockClProvider.findControlLoop(new ToscaConceptIdentifier(ID_NAME3, ID_VERSION1))) + .thenReturn(Optional.of(mockCL)); when(clElementStatisticsProvider.getFilteredClElementStatistics(eq(ID_NAME1), eq(ID_VERSION1), any(), any(), anyMap(), eq(SORT_DESC), eq(0))) diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java index 5ed4a4fc0..21a826743 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java @@ -92,7 +92,7 @@ class SupervisionHandlerTest { handler.triggerControlLoopSupervision(List.of(identifier)); verify(controlLoopUpdatePublisher).send(any(ControlLoop.class)); - verify(controlLoopProvider).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider).saveControlLoop(any(ControlLoop.class)); } @Test @@ -134,7 +134,7 @@ class SupervisionHandlerTest { handler.handleControlLoopStateChangeAckMessage(controlLoopAckMessage); - verify(controlLoopProvider).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider).saveControlLoop(any(ControlLoop.class)); } @Test @@ -152,7 +152,7 @@ class SupervisionHandlerTest { handler.handleControlLoopUpdateAckMessage(controlLoopAckMessage); - verify(controlLoopProvider).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider).saveControlLoop(any(ControlLoop.class)); } @Test @@ -290,14 +290,15 @@ class SupervisionHandlerTest { var controlLoop = controlLoopsCreate.getControlLoopList().get(0); controlLoop.setOrderedState(orderedState); - var controlLoopStateChangePublisher = mock(ControlLoopStateChangePublisher.class); - + when(controlLoopProvider.findControlLoop(identifier)).thenReturn(Optional.of(controlLoop)); when(controlLoopProvider.getControlLoop(identifier)).thenReturn(controlLoop); var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class); when(serviceTemplateProvider.getServiceTemplateList(any(), any())) .thenReturn(List.of(InstantiationUtils.getToscaServiceTemplate(TOSCA_TEMPLATE_YAML))); + var controlLoopStateChangePublisher = mock(ControlLoopStateChangePublisher.class); + return new SupervisionHandler(controlLoopProvider, participantProvider, monitoringProvider, serviceTemplateProvider, controlLoopUpdatePublisher, controlLoopStateChangePublisher, participantRegisterAckPublisher, participantDeregisterAckPublisher, participantUpdatePublisher); diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java index 62029f009..b7a3fe005 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java @@ -61,7 +61,7 @@ class SupervisionScannerTest { @BeforeAll public static void setUpBeforeAll() throws Exception { ToscaServiceTemplate serviceTemplate = InstantiationUtils.getToscaServiceTemplate(TOSCA_SERVICE_TEMPLATE_YAML); - when(serviceTemplateProvider.getServiceTemplateList(null, null)).thenReturn(List.of(serviceTemplate)); + when(serviceTemplateProvider.getAllServiceTemplates()).thenReturn(List.of(serviceTemplate)); } @Test @@ -76,14 +76,14 @@ class SupervisionScannerTest { var controlLoops = InstantiationUtils.getControlLoopsFromResource(CONTROLLOOP_JSON, "Crud").getControlLoopList(); - when(controlLoopProvider.getControlLoops(null, null)).thenReturn(controlLoops); + when(controlLoopProvider.getControlLoops()).thenReturn(controlLoops); var supervisionScanner = new SupervisionScanner(controlLoopProvider, serviceTemplateProvider, controlLoopStateChangePublisher, controlLoopUpdatePublisher, participantProvider, participantStatusReqPublisher, participantUpdatePublisher, clRuntimeParameterGroup); supervisionScanner.run(false); - verify(controlLoopProvider, times(0)).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider, times(0)).saveControlLoop(any(ControlLoop.class)); } @Test @@ -93,7 +93,7 @@ class SupervisionScannerTest { controlLoops.get(0).setState(ControlLoopState.UNINITIALISED2PASSIVE); controlLoops.get(0).setOrderedState(ControlLoopOrderedState.UNINITIALISED); var controlLoopProvider = mock(ControlLoopProvider.class); - when(controlLoopProvider.getControlLoops(null, null)).thenReturn(controlLoops); + when(controlLoopProvider.getControlLoops()).thenReturn(controlLoops); var controlLoopUpdatePublisher = mock(ControlLoopUpdatePublisher.class); var controlLoopStateChangePublisher = mock(ControlLoopStateChangePublisher.class); @@ -107,14 +107,14 @@ class SupervisionScannerTest { participantStatusReqPublisher, participantUpdatePublisher, clRuntimeParameterGroup); supervisionScanner.run(false); - verify(controlLoopProvider, times(1)).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider, times(1)).saveControlLoop(any(ControlLoop.class)); } @Test void testScanner() throws PfModelException { var controlLoopProvider = mock(ControlLoopProvider.class); var controlLoop = new ControlLoop(); - when(controlLoopProvider.getControlLoops(null, null)).thenReturn(List.of(controlLoop)); + when(controlLoopProvider.getControlLoops()).thenReturn(List.of(controlLoop)); var participantProvider = mock(ParticipantProvider.class); var participant = new Participant(); @@ -134,7 +134,7 @@ class SupervisionScannerTest { supervisionScanner.handleParticipantStatus(participant.getKey().asIdentifier()); supervisionScanner.run(true); - verify(controlLoopProvider, times(0)).updateControlLoop(any(ControlLoop.class)); + verify(controlLoopProvider, times(0)).saveControlLoop(any(ControlLoop.class)); verify(participantStatusReqPublisher, times(0)).send(any(ToscaConceptIdentifier.class)); } @@ -156,7 +156,7 @@ class SupervisionScannerTest { } var controlLoopProvider = mock(ControlLoopProvider.class); - when(controlLoopProvider.getControlLoops(null, null)).thenReturn(controlLoops); + when(controlLoopProvider.getControlLoops()).thenReturn(controlLoops); var participantProvider = mock(ParticipantProvider.class); var controlLoopUpdatePublisher = mock(ControlLoopUpdatePublisher.class); @@ -178,7 +178,7 @@ class SupervisionScannerTest { void testScanParticipant() throws PfModelException { var controlLoopProvider = mock(ControlLoopProvider.class); var controlLoop = new ControlLoop(); - when(controlLoopProvider.getControlLoops(null, null)).thenReturn(List.of(controlLoop)); + when(controlLoopProvider.getControlLoops()).thenReturn(List.of(controlLoop)); var clRuntimeParameterGroup = CommonTestData.geParameterGroup("dbScanParticipant"); clRuntimeParameterGroup.getParticipantParameters().getUpdateParameters().setMaxWaitMs(-1); diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java index b64bd9fbe..a465aa254 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java @@ -25,13 +25,13 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.UUID; -import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -46,10 +46,8 @@ import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.Parti import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantDeregisterAck; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantRegisterAck; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdateAck; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider; import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; -import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; import org.onap.policy.clamp.controlloop.runtime.util.rest.CommonRestController; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.event.comm.TopicSink; @@ -63,7 +61,6 @@ class SupervisionMessagesTest extends CommonRestController { private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; private static final String TOPIC = "my-topic"; private static SupervisionHandler supervisionHandler; - private static ControlLoopProvider clProvider; /** * setup Db Provider Parameters. @@ -72,10 +69,7 @@ class SupervisionMessagesTest extends CommonRestController { */ @BeforeAll public static void setupDbProviderParameters() throws PfModelException { - ClRuntimeParameterGroup controlLoopParameters = CommonTestData.geParameterGroup("instantproviderdb"); - - clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); - + var clProvider = mock(ControlLoopProvider.class); var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class); var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); var monitoringProvider = @@ -92,11 +86,6 @@ class SupervisionMessagesTest extends CommonRestController { participantRegisterAckPublisher, participantDeregisterAckPublisher, participantUpdatePublisher); } - @AfterAll - public static void closeDbProvider() throws PfModelException { - clProvider.close(); - } - @Test void testSendParticipantRegisterAck() throws Exception { final ParticipantRegisterAck participantRegisterAckMsg = new ParticipantRegisterAck(); @@ -106,7 +95,7 @@ class SupervisionMessagesTest extends CommonRestController { synchronized (lockit) { ParticipantRegisterAckPublisher clRegisterAckPublisher = new ParticipantRegisterAckPublisher(); - clRegisterAckPublisher.active(Collections.singletonList(Mockito.mock(TopicSink.class))); + clRegisterAckPublisher.active(List.of(Mockito.mock(TopicSink.class))); assertThatCode(() -> clRegisterAckPublisher.send(participantRegisterAckMsg)).doesNotThrowAnyException(); } } @@ -173,6 +162,51 @@ class SupervisionMessagesTest extends CommonRestController { verify(topicSink).send(anyString()); } + @Test + void testParticipantUpdatePublisherDecomisioning() { + var publisher = new ParticipantUpdatePublisher(mock(ServiceTemplateProvider.class)); + var topicSink = mock(TopicSink.class); + publisher.active(List.of(topicSink)); + publisher.sendDecomisioning(); + verify(topicSink).send(anyString()); + } + + @Test + void testParticipantUpdatePublisherComissioning() { + var publisher = new ParticipantUpdatePublisher(mock(ServiceTemplateProvider.class)); + var topicSink = mock(TopicSink.class); + publisher.active(List.of(topicSink)); + publisher.sendComissioningBroadcast("NAME", "1.0.0"); + verify(topicSink, times(0)).send(anyString()); + } + + @Test + void testParticipantStatusReqPublisher() { + var publisher = new ParticipantStatusReqPublisher(); + var topicSink = mock(TopicSink.class); + publisher.active(List.of(topicSink)); + publisher.send(getParticipantId()); + verify(topicSink).send(anyString()); + } + + @Test + void testParticipantRegisterAckPublisher() { + var publisher = new ParticipantRegisterAckPublisher(); + var topicSink = mock(TopicSink.class); + publisher.active(List.of(topicSink)); + publisher.send(UUID.randomUUID(), getParticipantId(), getParticipantType()); + verify(topicSink).send(anyString()); + } + + @Test + void testParticipantDeregisterAckPublisher() { + var publisher = new ParticipantDeregisterAckPublisher(); + var topicSink = mock(TopicSink.class); + publisher.active(List.of(topicSink)); + publisher.send(UUID.randomUUID()); + verify(topicSink).send(anyString()); + } + private ControlLoop getControlLoop() { var controlLoop = new ControlLoop(); controlLoop.setName("NAME"); |