diff options
58 files changed, 1193 insertions, 1335 deletions
diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java index 7b14dc627..721960779 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/main/ApexMain.java @@ -59,7 +59,7 @@ public class ApexMain { @Getter private ApexParameters apexParameters; - private ApexParameterHandler apexParameterHandler = new ApexParameterHandler(); + private final ApexParameterHandler apexParameterHandler = new ApexParameterHandler(); @Getter @Setter(lombok.AccessLevel.PRIVATE) diff --git a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java index dcae42f2f..c0b752fb1 100644 --- a/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java +++ b/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImpl.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2021 Nordix Foundation. + * Modifications Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -82,7 +82,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // The Apex engine workers this engine service is handling private final Map<AxArtifactKey, EngineWorker> engineWorkerMap = Collections - .synchronizedMap(new LinkedHashMap<AxArtifactKey, EngineWorker>()); + .synchronizedMap(new LinkedHashMap<>()); // Event queue for events being sent into the Apex engines, it used by all engines within a // group. @@ -99,13 +99,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven * This constructor instantiates engine workers and adds them to the set of engine workers to be managed. The * constructor is private to prevent subclassing. * - * @param engineServiceKey the engine service key - * @param threadCount the thread count, the number of engine workers to start + * @param engineServiceKey the engine service key + * @param threadCount the thread count, the number of engine workers to start * @param periodicEventPeriod the period in milliseconds at which periodic events are generated - * @throws ApexException on worker instantiation errors */ private EngineServiceImpl(final AxArtifactKey engineServiceKey, final int threadCount, - final long periodicEventPeriod) { + final long periodicEventPeriod) { LOGGER.entry(engineServiceKey, threadCount); this.engineServiceKey = engineServiceKey; @@ -114,7 +113,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Start engine workers for (var engineCounter = 0; engineCounter < threadCount; engineCounter++) { final var engineWorkerKey = new AxArtifactKey(engineServiceKey.getName() + '-' + engineCounter, - engineServiceKey.getVersion()); + engineServiceKey.getVersion()); engineWorkerMap.put(engineWorkerKey, new EngineWorker(engineWorkerKey, queue, atFactory)); LOGGER.info("Created apex engine {} .", engineWorkerKey.getId()); } @@ -135,14 +134,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven */ public static EngineServiceImpl create(final EngineServiceParameters config) throws ApexException { if (config == null) { - LOGGER.warn("Engine service configuration parameters is null"); - throw new ApexException("engine service configuration parameters are null"); + logWarnAndThrowException("Engine service configuration parameters are null"); } final ValidationResult validation = config.validate(); if (!validation.isValid()) { - LOGGER.warn("Invalid engine service configuration parameters: {}" + validation.getResult()); - throw new ApexException("Invalid engine service configuration parameters: " + validation); + logWarnAndThrowException("Invalid engine service configuration parameters: " + validation); } final AxArtifactKey engineServiceKey = config.getEngineKey(); @@ -226,7 +223,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven */ @Override public AxArtifactKey getApexModelKey() { - if (engineWorkerMap.size() == 0) { + if (engineWorkerMap.isEmpty()) { return null; } @@ -234,32 +231,29 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven } /** - * Method to create model. - * - * @param incomingEngineServiceKey incoming engine service key - * @param apexModelString apex model string - * @return apexPolicyModel the policy model - * @throws ApexException apex exception - */ + * Method to create model. + * + * @param incomingEngineServiceKey incoming engine service key + * @param apexModelString apex model string + * @return apexPolicyModel the policy model + * @throws ApexException apex exception + */ public static AxPolicyModel createModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString) throws ApexException { // Check if the engine service key specified is sane if (incomingEngineServiceKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if the Apex model specified is sane - if (apexModelString == null || apexModelString.trim().length() == 0) { + if (apexModelString == null || apexModelString.trim().isEmpty()) { String emptyModelMessage = "model for updating engine service with key " - + incomingEngineServiceKey.getId() + " is empty"; - LOGGER.warn(emptyModelMessage); - throw new ApexException(emptyModelMessage); + + incomingEngineServiceKey.getId() + " is empty"; + logWarnAndThrowException(emptyModelMessage); } // Read the Apex model into memory using the Apex Model Reader - AxPolicyModel apexPolicyModel = null; + AxPolicyModel apexPolicyModel; try { final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); apexPolicyModel = modelReader.read(new ByteArrayInputStream(apexModelString.getBytes())); @@ -276,7 +270,7 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven */ @Override public void updateModel(final AxArtifactKey incomingEngineServiceKey, final String apexModelString, - final boolean forceFlag) throws ApexException { + final boolean forceFlag) throws ApexException { AxPolicyModel apexPolicyModel = createModel(incomingEngineServiceKey, apexModelString); // Update the model @@ -290,30 +284,26 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven */ @Override public void updateModel(final AxArtifactKey incomingEngineServiceKey, final AxPolicyModel apexModel, - final boolean forceFlag) throws ApexException { + final boolean forceFlag) throws ApexException { LOGGER.entry(incomingEngineServiceKey); // Check if the engine service key specified is sane if (incomingEngineServiceKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if the Apex model specified is sane if (apexModel == null) { - LOGGER.warn("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is null"); - throw new ApexException("model for updating on engine service with key " + incomingEngineServiceKey.getId() - + " is null"); + String message = "model for updating on engine service with key " + incomingEngineServiceKey.getId() + + " is null"; + logWarnAndThrowException(message); } // Check if the key on the update request is correct if (!this.engineServiceKey.equals(incomingEngineServiceKey)) { - LOGGER.warn("engine service key " + incomingEngineServiceKey.getId() + " does not match the key" - + engineServiceKey.getId() + " of this engine service"); - throw new ApexException("engine service key " + incomingEngineServiceKey.getId() + " does not match the key" - + engineServiceKey.getId() + " of this engine service"); + String message = "engine service key " + incomingEngineServiceKey.getId() + " does not match the key" + + engineServiceKey.getId() + " of this engine service"; + logWarnAndThrowException(message); } // Check model compatibility @@ -334,12 +324,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven * Execute the model update on the engine instances. * * @param incomingEngineServiceKey the engine service key to update - * @param apexModel the model to update the engines with - * @param forceFlag if true, ignore compatibility problems + * @param apexModel the model to update the engines with + * @param forceFlag if true, ignore compatibility problems * @throws ApexException on model update errors */ private void executeModelUpdate(final AxArtifactKey incomingEngineServiceKey, final AxPolicyModel apexModel, - final boolean forceFlag) throws ApexException { + final boolean forceFlag) throws ApexException { if (!isStopped()) { stopEngines(incomingEngineServiceKey); @@ -369,32 +359,32 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven final var notRunningEngineIdBuilder = new StringBuilder(); for (final Entry<AxArtifactKey, EngineWorker> engineWorkerEntry : engineWorkerMap.entrySet()) { if (engineWorkerEntry.getValue().getState() != AxEngineState.READY - && engineWorkerEntry.getValue().getState() != AxEngineState.EXECUTING) { + && engineWorkerEntry.getValue().getState() != AxEngineState.EXECUTING) { notRunningEngineIdBuilder.append(engineWorkerEntry.getKey().getId()); notRunningEngineIdBuilder.append('('); notRunningEngineIdBuilder.append(engineWorkerEntry.getValue().getState()); notRunningEngineIdBuilder.append(") "); } } - if (notRunningEngineIdBuilder.length() > 0) { + if (!notRunningEngineIdBuilder.isEmpty()) { final var errorString = "engine start error on model update on engine service with key " - + incomingEngineServiceKey.getId() + ", engines not running are: " - + notRunningEngineIdBuilder.toString().trim(); - LOGGER.warn(errorString); - throw new ApexException(errorString); + + incomingEngineServiceKey.getId() + ", engines not running are: " + + notRunningEngineIdBuilder.toString().trim(); + logWarnAndThrowException(errorString); } } /** * Stop engines for a model update. + * * @param incomingEngineServiceKey the engine service key for the engines that are to be stopped * @throws ApexException on errors stopping engines */ private void stopEngines(final AxArtifactKey incomingEngineServiceKey) throws ApexException { // Stop all engines on this engine service stop(); - final long stoptime = System.currentTimeMillis(); - while (!isStopped() && System.currentTimeMillis() - stoptime < MAX_STOP_WAIT_TIME) { + final long stopTime = System.currentTimeMillis(); + while (!isStopped() && System.currentTimeMillis() - stopTime < MAX_STOP_WAIT_TIME) { ThreadUtilities.sleep(ENGINE_SERVICE_STOP_START_WAIT_INTERVAL); } // Check if all engines are stopped @@ -407,33 +397,33 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven notStoppedEngineIdBuilder.append(") "); } } - if (notStoppedEngineIdBuilder.length() > 0) { + if (!notStoppedEngineIdBuilder.isEmpty()) { final var errorString = "cannot update model on engine service with key " - + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME - + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); - LOGGER.warn(errorString); - throw new ApexException(errorString); + + incomingEngineServiceKey.getId() + ", engines not stopped after " + MAX_STOP_WAIT_TIME + + "ms are: " + notStoppedEngineIdBuilder.toString().trim(); + logWarnAndThrowException(errorString); } } /** * Issue compatibility warning or error message. - * @param apexModel The model name - * @param forceFlag true if we are forcing the update + * + * @param apexModel The model name + * @param forceFlag true if we are forcing the update * @param currentModel the existing model that is loaded * @throws ContextException on compatibility errors */ private void handleIncompatibility(final AxPolicyModel apexModel, final boolean forceFlag, - final AxPolicyModel currentModel) throws ContextException { + final AxPolicyModel currentModel) throws ContextException { if (forceFlag) { - LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); + LOGGER.warn("apex model update forced, supplied model with key \"{}\" " + + "is not a compatible model update from the existing engine model with key \"{}\"", + apexModel.getKey().getId(), currentModel.getKey().getId()); } else { throw new ContextException("apex model update failed, supplied model with key \"" - + apexModel.getKey().getId() - + "\" is not a compatible model update from the existing engine model with key \"" - + currentModel.getKey().getId() + "\""); + + apexModel.getKey().getId() + + "\" is not a compatible model update from the existing engine model with key \"" + + currentModel.getKey().getId() + "\""); } } @@ -470,16 +460,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.entry(engineKey); if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - String message = ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyPreambleNotFoundException(engineKey); } // Start the engine @@ -523,15 +509,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.entry(engineKey); if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); - throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throwEngineKeyPreambleNotFoundException(engineKey); } // Stop the engine @@ -565,15 +548,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven LOGGER.entry(engineKey); if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); - throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throwEngineKeyPreambleNotFoundException(engineKey); } // Clear the engine @@ -606,14 +586,13 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven @Override public boolean isStarted(final AxArtifactKey engineKey) { if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); + logWarningEngineKeyNotSpecified(); return false; } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + logWarningEngineKeyPreambleNotFound(engineKey); return false; } return engineWorkerMap.get(engineKey).isStarted(); @@ -641,14 +620,13 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven @Override public boolean isStopped(final AxArtifactKey engineKey) { if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); + logWarningEngineKeyNotSpecified(); return true; } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + logWarningEngineKeyPreambleNotFound(engineKey); return true; } return engineWorkerMap.get(engineKey).isStopped(); @@ -661,13 +639,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public void startPeriodicEvents(final long period) throws ApexException { // Check if periodic events are already started if (periodicEventGenerator != null) { - String message = "Periodic event geneation already running on engine " + engineServiceKey.getId() + ", " - + periodicEventGenerator.toString(); - LOGGER.warn(message); - throw new ApexException(message); + String message = "Periodic event generation already running on engine " + engineServiceKey.getId() + ", " + + periodicEventGenerator.toString(); + logWarnAndThrowException(message); } - // Set up periodic event execution, its a Java Timer/TimerTask + // Set up periodic event execution, it's a Java Timer/TimerTask periodicEventGenerator = new ApexPeriodicEventGenerator(this.getEngineServiceEventInterface(), period); // Record the periodic event period because it may have been set over the Web Socket admin @@ -682,8 +659,8 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven public void stopPeriodicEvents() throws ApexException { // Check if periodic events are already started if (periodicEventGenerator == null) { - LOGGER.warn("Periodic event geneation not running on engine " + engineServiceKey.getId()); - throw new ApexException("Periodic event geneation not running on engine " + engineServiceKey.getId()); + String message = "Periodic event generation not running on engine " + engineServiceKey.getId(); + logWarnAndThrowException(message); } // Stop periodic events @@ -698,15 +675,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven @Override public String getStatus(final AxArtifactKey engineKey) throws ApexException { if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); - throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throwEngineKeyPreambleNotFoundException(engineKey); } // Return the information for this worker return engineWorkerMap.get(engineKey).getStatus(engineKey); @@ -714,7 +688,6 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven /** * {@inheritDoc}. - * */ @Override public List<AxEngineModel> getEngineStats() { @@ -731,15 +704,12 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven @Override public String getRuntimeInfo(final AxArtifactKey engineKey) throws ApexException { if (engineKey == null) { - String message = ENGINE_KEY_NOT_SPECIFIED; - LOGGER.warn(message); - throw new ApexException(message); + throwEngineKeyNotSpecifiedException(); } // Check if we have this key on our map if (!engineWorkerMap.containsKey(engineKey)) { - LOGGER.warn(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); - throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + throwEngineKeyPreambleNotFoundException(engineKey); } // Return the information for this worker @@ -752,14 +722,14 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven @Override public void sendEvent(final ApexEvent event) { if (event == null) { - LOGGER.warn("Null events cannot be processed, in engine service " + engineServiceKey.getId()); + LOGGER.warn("Null events cannot be processed, in engine service {}", engineServiceKey.getId()); return; } // Check if we have this key on our map if (getState() == AxEngineState.STOPPED) { - LOGGER.warn("event " + event.getName() + " not processed, no engines on engine service " - + engineServiceKey.getId() + " are running"); + LOGGER.warn("event {} not processed, no engines on engine service {} are running", event.getName(), + engineServiceKey.getId()); return; } @@ -770,4 +740,27 @@ public final class EngineServiceImpl implements EngineService, EngineServiceEven // Add the incoming event to the queue, the next available worker will process it queue.add(event); } + + private static void logWarningEngineKeyNotSpecified() { + LOGGER.warn(ENGINE_KEY_NOT_SPECIFIED); + } + + private static void throwEngineKeyNotSpecifiedException() throws ApexException { + logWarningEngineKeyNotSpecified(); + throw new ApexException(ENGINE_KEY_NOT_SPECIFIED); + } + + private static void throwEngineKeyPreambleNotFoundException(AxArtifactKey engineKey) throws ApexException { + logWarningEngineKeyPreambleNotFound(engineKey); + throw new ApexException(ENGINE_KEY_PREAMBLE + engineKey.getId() + NOT_FOUND_SUFFIX); + } + + private static void logWarningEngineKeyPreambleNotFound(AxArtifactKey engineKey) { + LOGGER.warn(ENGINE_KEY_PREAMBLE + "{}" + NOT_FOUND_SUFFIX, engineKey.getId()); + } + + private static void logWarnAndThrowException(String message) throws ApexException { + LOGGER.warn(message); + throw new ApexException(message); + } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexEventTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexEventTest.java index 0f17bf193..ae6aac660 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexEventTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexEventTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,10 +28,10 @@ import java.util.Properties; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class ApexEventTest { +class ApexEventTest { private final Random random = new Random(); private ApexEvent apexEvent; @@ -40,63 +40,63 @@ public class ApexEventTest { * * @throws Exception when object is created */ - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { apexEvent = new ApexEvent("name", "version", "namespace", "source", "target", ""); } @Test - public void invalidEventName() { + void invalidEventName() { final String name = "++" + RandomStringUtils.randomAlphabetic(5); Assertions.assertThatCode(() -> - apexEvent = new ApexEvent(name, "version", "namespace", "source", "target", "")) + apexEvent = new ApexEvent(name, "version", "namespace", "source", "target", "")) .isInstanceOf(ApexEventException.class); } @Test - public void invalidEventVersion() { + void invalidEventVersion() { final String version = "++" + RandomStringUtils.randomAlphabetic(5); Assertions.assertThatCode(() -> - apexEvent = new ApexEvent("name", version, "namespace", "source", "target", "")) + apexEvent = new ApexEvent("name", version, "namespace", "source", "target", "")) .isInstanceOf(ApexEventException.class); } @Test - public void invalidEventNamespace() { + void invalidEventNamespace() { final String namespace = "++" + RandomStringUtils.randomAlphabetic(5); Assertions.assertThatCode(() -> - apexEvent = new ApexEvent("name", "version", namespace, "source", "target", "")) + apexEvent = new ApexEvent("name", "version", namespace, "source", "target", "")) .isInstanceOf(ApexEventException.class); } @Test - public void invalidEventSource() { + void invalidEventSource() { final String source = "++" + RandomStringUtils.randomAlphabetic(5); Assertions.assertThatCode(() -> - apexEvent = new ApexEvent("name", "version", "namespace", source, "target", "")) + apexEvent = new ApexEvent("name", "version", "namespace", source, "target", "")) .isInstanceOf(ApexEventException.class); } @Test - public void invalidEventTarget() { + void invalidEventTarget() { final String target = "++" + RandomStringUtils.randomAlphabetic(5); Assertions.assertThatCode(() -> - apexEvent = new ApexEvent("name", "version", "namespace", "source", target, "")) + apexEvent = new ApexEvent("name", "version", "namespace", "source", target, "")) .isInstanceOf(ApexEventException.class); } @Test - public void invalidEventStatus() { + void invalidEventStatus() { final String toscaPolicyState = "INVALID_STATUS"; Assertions.assertThatCode(() -> - apexEvent = new ApexEvent("name", "version", "namespace", "source", "target", toscaPolicyState)) - .isInstanceOf(ApexEventException.class); + apexEvent = new ApexEvent("name", "version", "namespace", "source", "target", toscaPolicyState)) + .isInstanceOf(ApexEventException.class); } @Test - public void setExecutionId() { + void setExecutionId() { final int executionId = random.nextInt(); apexEvent.setExecutionId(executionId); final long actual = apexEvent.getExecutionId(); @@ -104,7 +104,7 @@ public class ApexEventTest { } @Test - public void setExecutionProperties() { + void setExecutionProperties() { final Properties properties = new Properties(); apexEvent.setExecutionProperties(properties); final Properties actual = apexEvent.getExecutionProperties(); @@ -112,7 +112,7 @@ public class ApexEventTest { } @Test - public void setExceptionMessage() { + void setExceptionMessage() { final String message = RandomStringUtils.randomAlphabetic(25); apexEvent.setExceptionMessage(message); final String actual = apexEvent.getExceptionMessage(); @@ -120,7 +120,7 @@ public class ApexEventTest { } @Test - public void put() { + void put() { final String key = RandomStringUtils.randomAlphabetic(5); final Object event = new Object(); apexEvent.put(key, event); @@ -129,7 +129,7 @@ public class ApexEventTest { } @Test - public void put2() { + void put2() { final String key = "_#+@" + RandomStringUtils.randomAlphabetic(5); final Object event = new Object(); apexEvent.put(key, event); @@ -138,7 +138,7 @@ public class ApexEventTest { } @Test - public void putAll() { + void putAll() { final String key1 = RandomStringUtils.randomAlphabetic(5); final String key2 = RandomStringUtils.randomAlphabetic(6); final Object event1 = new Object(); @@ -152,7 +152,7 @@ public class ApexEventTest { } @Test - public void putAllOneInvalidKey() { + void putAllOneInvalidKey() { final String key1 = RandomStringUtils.randomAlphabetic(5); final String key2 = "_#+@" + RandomStringUtils.randomAlphabetic(6); final String key3 = RandomStringUtils.randomAlphabetic(7); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGeneratorTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGeneratorTest.java index ee72e6ea4..017941414 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGeneratorTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/ApexPeriodicEventGeneratorTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,16 +22,16 @@ package org.onap.policy.apex.service.engine.event; import java.util.Random; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface; -public class ApexPeriodicEventGeneratorTest { +class ApexPeriodicEventGeneratorTest { private final Random random = new Random(); @Test - public void run() throws ApexEventException { + void run() { final EngineServiceEventInterface engineServiceEventInterface = Mockito.mock(EngineServiceEventInterface.class); // don't want the timer to fire, so make it wait at least two seconds diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventConverterTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventConverterTest.java index 6e346a2a0..5b20b6fc5 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventConverterTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventConverterTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020,2023 Nordix Foundation + * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,7 +24,7 @@ package org.onap.policy.apex.service.engine.event; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.Apex2JsonEventConverter; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; @@ -33,10 +33,10 @@ import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParame * Test the JSON event converter corner cases. * */ -public class JsonEventConverterTest { - @SuppressWarnings("deprecation") +class JsonEventConverterTest { + @Test - public void testJsonEventConverter() { + void testJsonEventConverter() { Apex2JsonEventConverter converter = new Apex2JsonEventConverter(); assertThatThrownBy(() -> converter.init(null)) @@ -52,11 +52,11 @@ public class JsonEventConverterTest { .hasMessage("error converting event \"1\" to a string"); assertThatThrownBy(() -> converter.toApexEvent(null, "[{\"aKey\": 1},{\"aKey\": 2}]")) .hasMessageStartingWith("Failed to unmarshal JSON event") - .getCause().hasMessageStartingWith("event received without mandatory parameter \"name\" " + .cause().hasMessageContaining("event received without mandatory parameter \"name\" " + "on configuration or on event"); assertThatThrownBy(() -> converter.toApexEvent(null, "[1,2,3]")) .hasMessageStartingWith("Failed to unmarshal JSON event") - .getCause().hasMessageStartingWith("incoming event ([1,2,3]) is a JSON object array " + .cause().hasMessageContaining("incoming event ([1,2,3]) is a JSON object array " + "containing an invalid object 1.0"); assertThatThrownBy(() -> converter.fromApexEvent(null)) .hasMessage("event processing failed, Apex event is null"); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerForPojoTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerForPojoTest.java index 3bee638d8..076fd6e12 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerForPojoTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerForPojoTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020,2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2020, 2022-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,15 +22,15 @@ package org.onap.policy.apex.service.engine.event; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.List; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; @@ -52,19 +52,19 @@ import org.slf4j.ext.XLoggerFactory; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class JsonEventHandlerForPojoTest { +class JsonEventHandlerForPojoTest { private static final XLogger logger = XLoggerFactory.getXLogger(JsonEventHandlerForPojoTest.class); /** * Setup event model. * - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. * @throws ApexModelException the apex model exception */ - @BeforeClass - public static void setupEventModel() throws IOException, ApexModelException { + @BeforeAll + static void setupEventModel() throws IOException, ApexModelException { final String policyModelString = - TextFileUtils.getTextFileAsString("src/test/resources/policymodels/PojoEventModel.json"); + TextFileUtils.getTextFileAsString("src/test/resources/policymodels/PojoEventModel.json"); final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<AxPolicyModel>(AxPolicyModel.class); modelReader.setValidate(false); final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes())); @@ -76,8 +76,8 @@ public class JsonEventHandlerForPojoTest { /** * Initialize default schema parameters. */ - @BeforeClass - public static void initializeDefaultSchemaParameters() { + @BeforeAll + static void initializeDefaultSchemaParameters() { ParameterService.clear(); final SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); @@ -87,8 +87,8 @@ public class JsonEventHandlerForPojoTest { /** * Teardown default schema parameters. */ - @AfterClass - public static void teardownDefaultSchemaParameters() { + @AfterAll + static void teardownDefaultSchemaParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); ModelService.clear(); } @@ -97,10 +97,10 @@ public class JsonEventHandlerForPojoTest { * Test POJO to apex event and back. * * @throws ApexException the apex exception - * @throws IOException on IO exceptions + * @throws IOException on IO exceptions */ @Test - public void testJsonPojoToApexEvent() throws ApexException, IOException { + void testJsonPojoToApexEvent() throws ApexException, IOException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); assertNotNull(jsonEventConverter); @@ -109,7 +109,7 @@ public class JsonEventHandlerForPojoTest { jsonEventConverter.init(pars); final String apexEventJsonStringIn = - TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json"); + TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json"); logger.debug("input event\n" + apexEventJsonStringIn); @@ -148,10 +148,10 @@ public class JsonEventHandlerForPojoTest { * Test POJO List to apex event and back. * * @throws ApexException the apex exception - * @throws IOException on IO exceptions + * @throws IOException on IO exceptions */ @Test - public void testJsonPojoListToApexEvent() throws ApexException, IOException { + void testJsonPojoListToApexEvent() throws ApexException, IOException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); assertNotNull(jsonEventConverter); @@ -160,7 +160,7 @@ public class JsonEventHandlerForPojoTest { jsonEventConverter.init(pars); final String apexEventJsonStringIn = - TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoListEvent.json"); + TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoListEvent.json"); logger.debug("input event\n" + apexEventJsonStringIn); @@ -200,11 +200,11 @@ public class JsonEventHandlerForPojoTest { * Test POJO event with bad configurations. * * @throws ApexException the apex exception - * @throws IOException on IO exceptions + * @throws IOException on IO exceptions */ @SuppressWarnings("deprecation") @Test - public void testJsonBadPojoApexEvent() throws ApexException, IOException { + void testJsonBadPojoApexEvent() throws ApexException, IOException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); assertNotNull(jsonEventConverter); @@ -213,7 +213,7 @@ public class JsonEventHandlerForPojoTest { jsonEventConverter.init(pars); final String apexEventJsonStringIn = - TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json"); + TextFileUtils.getTextFileAsString("src/test/resources/events/TestPojoEvent.json"); logger.debug("input event\n" + apexEventJsonStringIn); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerTest.java index a724b6da2..59b022a7c 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventHandlerTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020,2023 Nordix Foundation. + * Modifications Copyright (C) 2020, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,19 +23,19 @@ package org.onap.policy.apex.service.engine.event; 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.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; @@ -58,19 +58,19 @@ import org.slf4j.ext.XLoggerFactory; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class JsonEventHandlerTest { +class JsonEventHandlerTest { private static final XLogger logger = XLoggerFactory.getXLogger(JsonEventHandlerTest.class); /** * Setup event model. * - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException Signals that an I/O exception has occurred. * @throws ApexModelException the apex model exception */ - @BeforeClass - public static void setupEventModel() throws IOException, ApexModelException { + @BeforeAll + static void setupEventModel() throws IOException, ApexModelException { final String policyModelString = - TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json"); + TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json"); final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<AxPolicyModel>(AxPolicyModel.class); final AxPolicyModel apexPolicyModel = modelReader.read(new ByteArrayInputStream(policyModelString.getBytes())); @@ -81,8 +81,8 @@ public class JsonEventHandlerTest { /** * Initialize default schema parameters. */ - @BeforeClass - public static void initializeDefaultSchemaParameters() { + @BeforeAll + static void initializeDefaultSchemaParameters() { ParameterService.clear(); final SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); @@ -92,8 +92,8 @@ public class JsonEventHandlerTest { /** * Teardown default schema parameters. */ - @AfterClass - public static void teardownDefaultSchemaParameters() { + @AfterAll + static void teardownDefaultSchemaParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); ModelService.clear(); } @@ -104,7 +104,7 @@ public class JsonEventHandlerTest { * @throws ApexException the apex exception */ @Test - public void testJsontoApexEvent() throws ApexException { + void testJsontoApexEvent() throws ApexException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); assertNotNull(jsonEventConverter); jsonEventConverter.init(new JsonEventProtocolParameters()); @@ -138,7 +138,7 @@ public class JsonEventHandlerTest { */ @SuppressWarnings("deprecation") @Test - public void testJsontoApexBadEvent() throws ApexException { + void testJsontoApexBadEvent() throws ApexException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); assertNotNull(jsonEventConverter); jsonEventConverter.init(new JsonEventProtocolParameters()); @@ -222,7 +222,7 @@ public class JsonEventHandlerTest { jsonEventConverter.toApexEvent(null, apexEventJsonStringIn); }).hasMessageStartingWith("Failed to unmarshal JSON event") .getCause().hasMessageStartingWith("error parsing BasicEvent:0.0.1 " - + "event from Json. Field \"intPar\" is missing, but is mandatory."); + + "event from Json. Field \"intPar\" is missing, but is mandatory."); apexEventJsonStringIn1 = SupportJsonEventGenerator.jsonEventNullFields(); event = jsonEventConverter.toApexEvent(null, apexEventJsonStringIn1).get(0); assertEquals(null, event.get("TestSlogan")); @@ -244,7 +244,7 @@ public class JsonEventHandlerTest { * @throws ApexException the apex exception */ @Test - public void testApexEventToJson() throws ApexException { + void testApexEventToJson() throws ApexException { final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter(); jsonEventConverter.init(new JsonEventProtocolParameters()); assertNotNull(jsonEventConverter); @@ -253,8 +253,8 @@ public class JsonEventHandlerTest { basicEventMap.put("intPar", 12345); final ApexEvent basicEvent = - new ApexEvent("BasicEvent", "0.0.1", "org.onap.policy.apex.events", "test", "apex", - AxToscaPolicyProcessingStatus.ENTRY.name()); + new ApexEvent("BasicEvent", "0.0.1", "org.onap.policy.apex.events", "test", "apex", + AxToscaPolicyProcessingStatus.ENTRY.name()); basicEvent.putAll(basicEventMap); final String apexEvent0000JsonString = (String) jsonEventConverter.fromApexEvent(basicEvent); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventProtocolPrametersTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventProtocolParametersTest.java index bf19d3f0b..fa93c3789 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventProtocolPrametersTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonEventProtocolParametersTest.java @@ -1,41 +1,41 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2024 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.apex.service.engine.event; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; /** * Test the JSON event parameters. - * */ -public class JsonEventProtocolPrametersTest { +class JsonEventProtocolParametersTest { @Test - public void testJsonParameters() { + void testJsonParameters() { assertNotNull(new JsonEventProtocolParameters()); - + JsonEventProtocolParameters params = new JsonEventProtocolParameters(); params.setLabel("MyLabel"); @@ -44,22 +44,22 @@ public class JsonEventProtocolPrametersTest { params.setEventProtocolPluginClass("MyPluginClass"); assertEquals("MyPluginClass", params.getEventProtocolPluginClass()); - + params.setNameAlias("MyNameAlias"); assertEquals("MyNameAlias", params.getNameAlias()); - + params.setVersionAlias("MyVersionAlias"); assertEquals("MyVersionAlias", params.getVersionAlias()); - + params.setNameSpaceAlias("MyNameSpaceAlias"); assertEquals("MyNameSpaceAlias", params.getNameSpaceAlias()); - + params.setSourceAlias("MySourceAlias"); assertEquals("MySourceAlias", params.getSourceAlias()); - + params.setTargetAlias("MyTargetAlias"); assertEquals("MyTargetAlias", params.getTargetAlias()); - + params.setPojoField("MyPojoField"); assertEquals("MyPojoField", params.getPojoField()); } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java index 3bdcf53d9..a7d77fb33 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/JsonTaggedEventConsumerTest.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +22,15 @@ package org.onap.policy.apex.service.engine.event; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.CharacterDelimitedTextBlockReader; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.TextBlock; @@ -37,64 +38,61 @@ import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer * Test JSON Tagged Event Consumer. * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class JsonTaggedEventConsumerTest { +class JsonTaggedEventConsumerTest { @Test - public void testGarbageText() throws IOException { - verifyNoEvent("testGarbageText", "hello there"); + void testGarbageText() throws IOException { + verifyNoEvent("hello there"); } @Test - public void testPartialEvent() throws IOException { - verifyNoEvent("testGarbageText", "\"TestTimestamp\": 1469781869268}"); + void testPartialEvent() throws IOException { + verifyNoEvent("\"TestTimestamp\": 1469781869268}"); } @Test - public void testFullEvent() throws IOException { - verifyMulti("testFullEvent", "{TestTimestamp\": 1469781869268}", "{TestTimestamp\": 1469781869268}"); + void testFullEvent() throws IOException { + verifyMulti("{TestTimestamp\": 1469781869268}"); } @Test - public void testFullEventGarbageBefore() throws IOException { - verifyMulti("testFullEventGarbageBefore", "Garbage{TestTimestamp\": 1469781869268}", - "{TestTimestamp\": 1469781869268}"); + void testFullEventGarbageBefore() throws IOException { + verifyMulti("Garbage{TestTimestamp\": 1469781869268}"); } @Test - public void testFullEventGarbageBeforeAfter() throws IOException { - verifyMulti("testFullEventGarbageBeforeAfter", "Garbage{TestTimestamp\": 1469781869268}Rubbish", - "{TestTimestamp\": 1469781869268}"); + void testFullEventGarbageBeforeAfter() throws IOException { + verifyMulti("Garbage{TestTimestamp\": 1469781869268}Rubbish"); } @Test - public void testFullEventGarbageAfter() throws IOException { - verifyMulti("testFullEventGarbageAfter", "{TestTimestamp\": 1469781869268}Rubbish", - "{TestTimestamp\": 1469781869268}"); + void testFullEventGarbageAfter() throws IOException { + verifyMulti("{TestTimestamp\": 1469781869268}Rubbish"); } - private void verifyNoEvent(String testName, String input) throws IOException { + private void verifyNoEvent(String input) throws IOException { final InputStream jsonInputStream = new ByteArrayInputStream(input.getBytes()); final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); taggedReader.init(jsonInputStream); final TextBlock textBlock = taggedReader.readTextBlock(); - assertNull(testName, textBlock.getText()); - assertTrue(testName, textBlock.isEndOfText()); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); } - private void verifyMulti(String testName, String input, String expected) throws IOException { + private void verifyMulti(String input) throws IOException { final InputStream jsonInputStream = new ByteArrayInputStream(input.getBytes()); final CharacterDelimitedTextBlockReader taggedReader = new CharacterDelimitedTextBlockReader('{', '}'); taggedReader.init(jsonInputStream); TextBlock textBlock = taggedReader.readTextBlock(); - assertEquals(testName, expected, textBlock.getText()); - assertFalse(testName, textBlock.isEndOfText()); + assertEquals("{TestTimestamp\": 1469781869268}", textBlock.getText()); + assertFalse(textBlock.isEndOfText()); textBlock = taggedReader.readTextBlock(); - assertNull(testName, textBlock.getText()); - assertTrue(testName, textBlock.isEndOfText()); + assertNull(textBlock.getText()); + assertTrue(textBlock.isEndOfText()); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PeeredReferenceTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PeeredReferenceTest.java index cadb5c8a1..1e9c4a586 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PeeredReferenceTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PeeredReferenceTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,18 @@ package org.onap.policy.apex.service.engine.event; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer.ApexFileEventProducer; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -public class PeeredReferenceTest { +class PeeredReferenceTest { @Test - public void getPeeredConsumer() { + void getPeeredConsumer() { final ApexFileEventConsumer eventConsumer = new ApexFileEventConsumer(); final ApexFileEventProducer eventProducer = new ApexFileEventProducer(); final EventHandlerPeeredMode peeredMode = EventHandlerPeeredMode.REQUESTOR; @@ -43,7 +43,7 @@ public class PeeredReferenceTest { } @Test - public void getPeeredProducer() { + void getPeeredProducer() { final ApexEventConsumer eventConsumer = new ApexFileEventConsumer(); final ApexEventProducer eventProducer = new ApexFileEventProducer(); final EventHandlerPeeredMode peeredMode = EventHandlerPeeredMode.SYNCHRONOUS; diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PluginFactoriesTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PluginFactoriesTest.java index 514b3b1e5..bf894dce5 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PluginFactoriesTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/PluginFactoriesTest.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +22,10 @@ package org.onap.policy.apex.service.engine.event; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Map.Entry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.EventConsumerFactory; import org.onap.policy.apex.service.engine.event.impl.EventProducerFactory; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; @@ -35,13 +36,14 @@ import org.onap.policy.common.parameters.ParameterException; /** * Test Plugin Factories. + * * @author Liam Fallon (liam.fallon@ericsson.com) * @author John Keeney (john.keeney@ericsson.com) */ -public class PluginFactoriesTest { +class PluginFactoriesTest { @Test - public void testEventConsumerFactory() throws ApexEventException, ParameterException { + void testEventConsumerFactory() throws ApexEventException, ParameterException { final String[] args = {"-p", "src/test/resources/parameters/factoryGoodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -49,13 +51,13 @@ public class PluginFactoriesTest { for (final Entry<String, EventHandlerParameters> ce : parameters.getEventInputParameters().entrySet()) { final ApexEventConsumer consumer = new EventConsumerFactory().createConsumer( - parameters.getEngineServiceParameters().getName() + "_consumer_" + ce.getKey(), ce.getValue()); + parameters.getEngineServiceParameters().getName() + "_consumer_" + ce.getKey(), ce.getValue()); assertNotNull(consumer); } for (final Entry<String, EventHandlerParameters> pe : parameters.getEventOutputParameters().entrySet()) { final ApexEventProducer producer = new EventProducerFactory().createProducer( - parameters.getEngineServiceParameters().getName() + "_producer_" + pe.getKey(), pe.getValue()); + parameters.getEngineServiceParameters().getName() + "_producer_" + pe.getKey(), pe.getValue()); assertNotNull(producer); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/SynchronousEventCacheTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/SynchronousEventCacheTest.java index dd960b298..f8de7f561 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/SynchronousEventCacheTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/SynchronousEventCacheTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -25,25 +25,26 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import java.util.Random; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.eventrequestor.EventRequestorConsumer; import org.onap.policy.apex.service.engine.event.impl.eventrequestor.EventRequestorProducer; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -public class SynchronousEventCacheTest { +class SynchronousEventCacheTest { + private final Random random = new Random(); private ApexEventConsumer consumer; private ApexEventProducer producer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { consumer = new EventRequestorConsumer(); producer = new EventRequestorProducer(); } @Test - public void removedCachedFromApexNotExists() { + void removedCachedFromApexNotExists() { int timeout = random.nextInt(100); int executionId = random.nextInt(); final SynchronousEventCache cache = @@ -54,7 +55,7 @@ public class SynchronousEventCacheTest { } @Test - public void removeCachedFromApex() { + void removeCachedFromApex() { int timeout = random.nextInt(100); int executionId = random.nextInt(); final SynchronousEventCache cache = @@ -67,7 +68,7 @@ public class SynchronousEventCacheTest { } @Test - public void removedCachedToApexNotExists() { + void removedCachedToApexNotExists() { int timeout = random.nextInt(100); int executionId = random.nextInt(); final SynchronousEventCache cache = @@ -78,7 +79,7 @@ public class SynchronousEventCacheTest { } @Test - public void removeCachedToApex() { + void removeCachedToApex() { int timeout = random.nextInt(100); int executionId = random.nextInt(); final SynchronousEventCache cache = @@ -91,7 +92,7 @@ public class SynchronousEventCacheTest { } @Test - public void apexExistsFromApexNo() { + void apexExistsFromApexNo() { int executionId = random.nextInt(); final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0); @@ -101,7 +102,7 @@ public class SynchronousEventCacheTest { } @Test - public void apexExistsFromApexYes() { + void apexExistsFromApexYes() { int executionId = random.nextInt(); final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0); @@ -112,7 +113,7 @@ public class SynchronousEventCacheTest { } @Test - public void apexExistsToApexNo() { + void apexExistsToApexNo() { int executionId = random.nextInt(); final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0); @@ -122,7 +123,7 @@ public class SynchronousEventCacheTest { } @Test - public void apexExistsToApexYes() { + void apexExistsToApexYes() { int executionId = random.nextInt(); final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0); @@ -133,7 +134,7 @@ public class SynchronousEventCacheTest { } @Test - public void addEventsFromApexDuplicatedExecutionId() { + void addEventsFromApexDuplicatedExecutionId() { int timeout = random.nextInt(100); int executionId = random.nextInt(); final SynchronousEventCache cache = @@ -144,11 +145,11 @@ public class SynchronousEventCacheTest { final var obj2 = new Object(); assertThatCode(() -> cache.cacheSynchronizedEventFromApex(executionId, obj2)) - .isInstanceOf(ApexEventRuntimeException.class); + .isInstanceOf(ApexEventRuntimeException.class); } @Test - public void stop() { + void stop() { int timeout = random.nextInt(100); final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, timeout); @@ -157,7 +158,7 @@ public class SynchronousEventCacheTest { } @Test - public void stopNotEmpty() { + void stopNotEmpty() { final SynchronousEventCache cache = new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 2000); assertThatCode(() -> { diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactoryTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactoryTest.java index 976376e5a..5bff54225 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactoryTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventConsumerFactoryTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,27 +20,27 @@ package org.onap.policy.apex.service.engine.event.impl; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventConsumer; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; -public class EventConsumerFactoryTest { +class EventConsumerFactoryTest { private EventConsumerFactory factory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new EventConsumerFactory(); } @Test - public void createConsumerNoTechnologyParameter() { + void createConsumerNoTechnologyParameter() { final String name = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters parameters = new EventHandlerParameters(); @@ -49,7 +49,7 @@ public class EventConsumerFactoryTest { } @Test - public void createConsumerNoConsumerPlugin() { + void createConsumerNoConsumerPlugin() { final String name = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters parameters = new EventHandlerParameters(); parameters.setCarrierTechnologyParameters(new RestPluginCarrierTechnologyParameters()); @@ -59,7 +59,7 @@ public class EventConsumerFactoryTest { } @Test - public void createConsumerWrongPluginClassName() { + void createConsumerWrongPluginClassName() { final String name = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters parameters = new EventHandlerParameters(); final RestPluginCarrierTechnologyParameters technologyParameters = @@ -72,7 +72,7 @@ public class EventConsumerFactoryTest { } @Test - public void createConsumer() throws ApexEventException { + void createConsumer() throws ApexEventException { final String name = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters parameters = new EventHandlerParameters(); parameters.setCarrierTechnologyParameters(new SuperDooperCarrierTechnologyParameters()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactoryTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactoryTest.java index 7e3cb5478..edd050e26 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactoryTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProducerFactoryTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,27 +20,27 @@ package org.onap.policy.apex.service.engine.event.impl; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventProducer; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.carriertechnology.RestPluginCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; -public class EventProducerFactoryTest { +class EventProducerFactoryTest { private EventProducerFactory factory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new EventProducerFactory(); } @Test - public void createConsumerNoTechnologyParameter() { + void createConsumerNoTechnologyParameter() { final EventHandlerParameters parameters = new EventHandlerParameters(); final String name = RandomStringUtils.randomAlphabetic(4); @@ -49,7 +49,7 @@ public class EventProducerFactoryTest { } @Test - public void createConsumerNoConsumerPlugin() { + void createConsumerNoConsumerPlugin() { final EventHandlerParameters parameters = new EventHandlerParameters(); final String name = RandomStringUtils.randomAlphabetic(4); parameters.setCarrierTechnologyParameters(new RestPluginCarrierTechnologyParameters()); @@ -59,7 +59,7 @@ public class EventProducerFactoryTest { } @Test - public void createConsumerWrongProducerPluginName() { + void createConsumerWrongProducerPluginName() { final EventHandlerParameters parameters = new EventHandlerParameters(); final RestPluginCarrierTechnologyParameters technologyParameters = new RestPluginCarrierTechnologyParameters(); @@ -72,7 +72,7 @@ public class EventProducerFactoryTest { } @Test - public void createConsumer() throws ApexEventException { + void createConsumer() throws ApexEventException { final EventHandlerParameters parameters = new EventHandlerParameters(); parameters.setCarrierTechnologyParameters(new SuperDooperCarrierTechnologyParameters()); final String name = RandomStringUtils.randomAlphabetic(4); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProtocolFactoryTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProtocolFactoryTest.java index 8ed3a9fec..9fd74e28f 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProtocolFactoryTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/EventProtocolFactoryTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,27 +20,27 @@ package org.onap.policy.apex.service.engine.event.impl; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventProtocolConverter; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -public class EventProtocolFactoryTest { +class EventProtocolFactoryTest { private EventProtocolFactory factory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new EventProtocolFactory(); } @Test - public void createConsumerNoConsumerPlugin() { + void createConsumerNoConsumerPlugin() { final EventProtocolParameters parameters = new ApexEventProtocolParameters(); parameters.setEventProtocolPluginClass(""); final String name = RandomStringUtils.randomAlphabetic(9); @@ -50,7 +50,7 @@ public class EventProtocolFactoryTest { } @Test - public void createConsumer2() { + void createConsumer2() { final EventProtocolParameters parameters = new ApexEventProtocolParameters(); final String name = RandomStringUtils.randomAlphabetic(9); parameters.setEventProtocolPluginClass("java.lang.Object"); @@ -60,7 +60,7 @@ public class EventProtocolFactoryTest { } @Test - public void createConsumer() { + void createConsumer() { final EventProtocolParameters parameters = new JsonEventProtocolParameters(); final String name = RandomStringUtils.randomAlphabetic(9); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/Apex2ApexEventConverterTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/Apex2ApexEventConverterTest.java index 9a61f8739..210358fed 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/Apex2ApexEventConverterTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/Apex2ApexEventConverterTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,55 +23,55 @@ package org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import java.util.List; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.model.basicmodel.concepts.AxToscaPolicyProcessingStatus; import org.onap.policy.apex.service.engine.event.ApexEvent; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventList; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -public class Apex2ApexEventConverterTest { +class Apex2ApexEventConverterTest { private Apex2ApexEventConverter converter; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { converter = new Apex2ApexEventConverter(); } @Test - public void initWithNull() { + void initWithNull() { assertThatThrownBy(() -> converter.init(null)) .isInstanceOf(ApexEventRuntimeException.class); } @Test - public void init() { + void init() { assertThatNoException() .isThrownBy(() -> converter.init(new ApexEventProtocolParameters())); } @Test - public void toApexEventWithNull() { + void toApexEventWithNull() { final String eventName = RandomStringUtils.randomAlphanumeric(5); assertThatThrownBy(() -> converter.toApexEvent(eventName, null)) .isInstanceOf(ApexEventException.class); } @Test - public void toApexEventWithNonApexEvent() { + void toApexEventWithNonApexEvent() { final String eventName = RandomStringUtils.randomAlphanumeric(5); assertThatThrownBy(() -> converter.toApexEvent(eventName, new Object())) .isInstanceOf(ApexEventException.class); } @Test - public void toApexEmptyEvent() throws ApexEventException { + void toApexEmptyEvent() throws ApexEventException { final String eventName = RandomStringUtils.randomAlphanumeric(4); final String name = RandomStringUtils.randomAlphanumeric(5); final String version = RandomStringUtils.randomAlphanumeric(6); @@ -86,7 +86,7 @@ public class Apex2ApexEventConverterTest { } @Test - public void toApexEventWithApexAndOtherFields() throws ApexEventException { + void toApexEventWithApexAndOtherFields() throws ApexEventException { final String eventName = RandomStringUtils.randomAlphanumeric(4); final String name1 = RandomStringUtils.randomAlphanumeric(5); final String version1 = RandomStringUtils.randomAlphanumeric(6); @@ -105,7 +105,7 @@ public class Apex2ApexEventConverterTest { } @Test - public void toApexEventWithApexAndList() throws ApexEventException { + void toApexEventWithApexAndList() throws ApexEventException { final String eventName = RandomStringUtils.randomAlphanumeric(4); final String name1 = RandomStringUtils.randomAlphanumeric(5); final String version1 = RandomStringUtils.randomAlphanumeric(6); @@ -135,7 +135,7 @@ public class Apex2ApexEventConverterTest { } @Test - public void toApexEventWithApexAndListAndOtherFields() throws ApexEventException { + void toApexEventWithApexAndListAndOtherFields() throws ApexEventException { final String eventName = RandomStringUtils.randomAlphanumeric(4); final String name1 = RandomStringUtils.randomAlphanumeric(5); final String version1 = RandomStringUtils.randomAlphanumeric(6); @@ -166,13 +166,13 @@ public class Apex2ApexEventConverterTest { } @Test - public void fromApexEventNull() { + void fromApexEventNull() { assertThatThrownBy(() -> converter.fromApexEvent(null)) .isInstanceOf(ApexEventException.class); } @Test - public void fromApexEvent() throws ApexEventException { + void fromApexEvent() throws ApexEventException { final String name1 = RandomStringUtils.randomAlphanumeric(5); final String version1 = RandomStringUtils.randomAlphanumeric(6); final String nameSpace1 = "a" + RandomStringUtils.randomAlphanumeric(7); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParametersTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParametersTest.java index 8b39b0a74..d0d3de2fb 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParametersTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/apexprotocolplugin/ApexEventProtocolParametersTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,15 +19,15 @@ package org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class ApexEventProtocolParametersTest { +class ApexEventProtocolParametersTest { @Test - public void testNoArgConstructor() { + void testNoArgConstructor() { final ApexEventProtocolParameters apexEventProtocolParameters = new ApexEventProtocolParameters(); final String actual = apexEventProtocolParameters.getLabel(); final String pluginClass = apexEventProtocolParameters.getEventProtocolPluginClass(); @@ -37,7 +37,7 @@ public class ApexEventProtocolParametersTest { } @Test - public void testConstructor() { + void testConstructor() { final String expected = RandomStringUtils.randomAlphabetic(6); final ApexEventProtocolParameters apexEventProtocolParameters = new ApexEventProtocolParameters(expected); final String actual = apexEventProtocolParameters.getLabel(); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverterTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverterTest.java index 4d36b7be4..03b622a5e 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverterTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/enevent/ApexEvent2EnEventConverterTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,13 +21,13 @@ package org.onap.policy.apex.service.engine.event.impl.enevent; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.List; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.core.engine.event.EnEvent; import org.onap.policy.apex.model.basicmodel.concepts.ApexException; import org.onap.policy.apex.model.basicmodel.concepts.AxToscaPolicyProcessingStatus; @@ -36,24 +36,24 @@ import org.onap.policy.apex.service.engine.event.ApexEvent; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; -public class ApexEvent2EnEventConverterTest { +class ApexEvent2EnEventConverterTest { private ApexEvent2EnEventConverter converter; private final Random random = new Random(); - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { converter = new ApexEvent2EnEventConverter(null); } @Test - public void toApexEventNull() { + void toApexEventNull() { final String eventName = RandomStringUtils.randomAlphabetic(3); assertThatThrownBy(() -> converter.toApexEvent(eventName, null)) .isInstanceOf(ApexEventException.class); } @Test - public void toApexEventWrongClass() throws ApexException { + void toApexEventWrongClass() throws ApexException { final String eventName = RandomStringUtils.randomAlphabetic(3); final String name = RandomStringUtils.randomAlphanumeric(5); final String version = RandomStringUtils.randomAlphanumeric(6); @@ -69,7 +69,7 @@ public class ApexEvent2EnEventConverterTest { } @Test - public void toApex() throws ApexException { + void toApex() throws ApexException { // prepare String values for events final String name = RandomStringUtils.randomAlphabetic(5); final String version = RandomStringUtils.randomAlphabetic(6); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParametersTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParametersTest.java index 878756383..63248045b 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParametersTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorCarrierTechnologyParametersTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -20,23 +20,23 @@ package org.onap.policy.apex.service.engine.event.impl.eventrequestor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; -public class EventRequestorCarrierTechnologyParametersTest { +class EventRequestorCarrierTechnologyParametersTest { @Test - public void getName() { + void getName() { final EventRequestorCarrierTechnologyParameters parameters = new EventRequestorCarrierTechnologyParameters(); final String actual = parameters.getName(); assertEquals(EventRequestorCarrierTechnologyParameters.EVENT_REQUESTOR_CARRIER_TECHNOLOGY_LABEL, actual); } @Test - public void validate() { + void validate() { final EventRequestorCarrierTechnologyParameters parameters = new EventRequestorCarrierTechnologyParameters(); final ValidationResult actual = parameters.validate(); assertNotNull(actual); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorConsumerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorConsumerTest.java index dd44da7dd..fc79d1dca 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorConsumerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorConsumerTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,11 @@ package org.onap.policy.apex.service.engine.event.impl.eventrequestor; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.PeeredReference; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; @@ -32,16 +32,16 @@ import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -public class EventRequestorConsumerTest { +class EventRequestorConsumerTest { private EventRequestorConsumer consumer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { consumer = new EventRequestorConsumer(); } @Test - public void initNoCarrierTechnologyParameters() { + void initNoCarrierTechnologyParameters() { final String consumerName = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); @@ -50,7 +50,7 @@ public class EventRequestorConsumerTest { } @Test - public void initNoPeered() { + void initNoPeered() { final String consumerName = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters()); @@ -60,7 +60,7 @@ public class EventRequestorConsumerTest { } @Test - public void getName() throws ApexEventException { + void getName() throws ApexEventException { final String consumerName = RandomStringUtils.randomAlphabetic(6); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters()); @@ -73,7 +73,7 @@ public class EventRequestorConsumerTest { } @Test - public void getSetPeeeredReference() { + void getSetPeeeredReference() { final PeeredReference peeredReference = new PeeredReference(EventHandlerPeeredMode.REQUESTOR, new ApexFileEventConsumer(), new ApexFileEventProducer()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorProducerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorProducerTest.java index 5abf28ee6..0613efa5b 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorProducerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/eventrequestor/EventRequestorProducerTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,17 +21,17 @@ package org.onap.policy.apex.service.engine.event.impl.eventrequestor; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventProducer; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; @@ -41,8 +41,9 @@ import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode; -@RunWith(MockitoJUnitRunner.class) -public class EventRequestorProducerTest { +@ExtendWith(MockitoExtension.class) +class EventRequestorProducerTest { + private final Random random = new Random(); private EventRequestorProducer producer; @@ -51,13 +52,13 @@ public class EventRequestorProducerTest { @Mock private EventRequestorConsumer apexConsumer; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { producer = new EventRequestorProducer(); } @Test - public void initWithEmptyParams() { + void initWithEmptyParams() { final String producerName = RandomStringUtils.random(4); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); @@ -66,7 +67,7 @@ public class EventRequestorProducerTest { } @Test - public void initNotPeered() { + void initNotPeered() { final String producerName = RandomStringUtils.random(4); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters()); @@ -76,7 +77,7 @@ public class EventRequestorProducerTest { } @Test - public void getName() throws ApexEventException { + void getName() throws ApexEventException { final String expected = RandomStringUtils.random(4); final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters(); eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters()); @@ -89,7 +90,7 @@ public class EventRequestorProducerTest { } @Test - public void getSetPeeredReference() { + void getSetPeeredReference() { final PeeredReference peeredReference = new PeeredReference(EventHandlerPeeredMode.SYNCHRONOUS, apexConsumer, apexProducer); producer.setPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS, peeredReference); @@ -99,7 +100,7 @@ public class EventRequestorProducerTest { } @Test - public void sendEventNoRequestor() { + void sendEventNoRequestor() { final int id = random.nextInt(1000); assertThatThrownBy(() -> producer.sendEvent(id, null, null, null)) @@ -107,7 +108,7 @@ public class EventRequestorProducerTest { } @Test - public void sendEventNoEventRequestorConsumer() { + void sendEventNoEventRequestorConsumer() { final int id = random.nextInt(1000); final ApexFileEventConsumer fileEventConsumer = Mockito.mock(ApexFileEventConsumer.class); @@ -122,7 +123,7 @@ public class EventRequestorProducerTest { } @Test - public void sendEvent() { + void sendEvent() { final int id = random.nextInt(1000); final PeeredReference reference = @@ -134,7 +135,7 @@ public class EventRequestorProducerTest { } @Test - public void sendEventCached() { + void sendEventCached() { final int id = random.nextInt(1000); // Set event cache diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParametersTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParametersTest.java index 26445c1fb..86bd7952f 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParametersTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/FileCarrierTechnologyParametersTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,38 +22,40 @@ package org.onap.policy.apex.service.engine.event.impl.filecarrierplugin; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ParameterRuntimeException; import org.onap.policy.common.parameters.ValidationResult; -public class FileCarrierTechnologyParametersTest { +class FileCarrierTechnologyParametersTest { + private final Random random = new Random(); private static final String APEX_RELATIVE_FILE_ROOT = "APEX_RELATIVE_FILE_ROOT"; private final String defaultApesRelativeFileRoot = System.getProperty(APEX_RELATIVE_FILE_ROOT); private FileCarrierTechnologyParameters parameters; private File tempFile; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { parameters = new FileCarrierTechnologyParameters(); } /** * Cleaning after testing. */ - @After - public void tearDown() { + @AfterEach + void tearDown() { if (tempFile != null) { - tempFile.delete(); + assertTrue(tempFile.delete()); } if (defaultApesRelativeFileRoot != null) { System.setProperty(APEX_RELATIVE_FILE_ROOT, defaultApesRelativeFileRoot); @@ -63,7 +65,7 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void getSetFileName() { + void getSetFileName() { final String fileName = RandomStringUtils.random(10); parameters.setFileName(fileName); assertThat(parameters.getFileName()) @@ -71,86 +73,86 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void isStandardIo() { + void isStandardIo() { assertThat(parameters.isStandardIo()).isFalse(); } @Test - public void isStandardError() { + void isStandardError() { assertThat(parameters.isStandardError()).isFalse(); } @Test - public void isStreamingMode() { + void isStreamingMode() { assertThat(parameters.isStreamingMode()).isFalse(); } @Test - public void setStandardIo() { + void setStandardIo() { final boolean standardIo = random.nextBoolean(); parameters.setStandardIo(standardIo); assertThat(parameters.isStandardIo()).isEqualTo(standardIo); } @Test - public void setStandardError() { + void setStandardError() { final boolean standardError = random.nextBoolean(); parameters.setStandardError(standardError); assertThat(parameters.isStandardError()).isEqualTo(standardError); } @Test - public void getStartDelay() { + void getStartDelay() { assertThat(parameters.getStartDelay()).isZero(); } @Test - public void setStartDelay() { + void setStartDelay() { final long delay = random.nextInt(); parameters.setStartDelay(delay); assertThat(parameters.getStartDelay()).isEqualTo(delay); } @Test - public void getLabel() { + void getLabel() { final String label = RandomStringUtils.random(10); parameters.setLabel(label); assertThat(parameters.getLabel()).isEqualTo(label); } @Test - public void setName() { + void setName() { final String name = RandomStringUtils.random(10); assertThatThrownBy(() -> parameters.setName(name)).isInstanceOf(ParameterRuntimeException.class); } @Test - public void getName() { + void getName() { final String label = RandomStringUtils.random(10); parameters.setLabel(label); assertThat(parameters.getName()).isEqualTo(label); } @Test - public void getStreamingMode() { + void getStreamingMode() { assertThat(parameters.isStreamingMode()).isFalse(); } @Test - public void setStreamingMode() { + void setStreamingMode() { final boolean streamingMode = random.nextBoolean(); parameters.setStreamingMode(streamingMode); assertThat(parameters.isStreamingMode()).isEqualTo(streamingMode); } @Test - public void validateFileNameNull() { + void validateFileNameNull() { final ValidationResult result = parameters.validate(); assertThat(result.isValid()).isFalse(); } @Test - public void validateFileNameAbsolutePath() throws IOException { + void validateFileNameAbsolutePath() throws IOException { tempFile = File.createTempFile("test_", ".tmp"); parameters.setFileName(tempFile.getAbsolutePath()); final ValidationResult result = parameters.validate(); @@ -158,7 +160,7 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void validateFileNameAbsolutePathNotExisting() { + void validateFileNameAbsolutePathNotExisting() { parameters.setFileName(RandomStringUtils.randomAlphabetic(5) + ".tmp"); System.setProperty(APEX_RELATIVE_FILE_ROOT, System.getProperty("user.home")); final ValidationResult result = parameters.validate(); @@ -166,14 +168,14 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void validateDirectoryName() { + void validateDirectoryName() { parameters.setFileName(System.getProperty("user.dir")); final ValidationResult result = parameters.validate(); assertThat(result.isValid()).isFalse(); } @Test - public void validateParentNotDirectory() { + void validateParentNotDirectory() { final URL resource = FileCarrierTechnologyParameters.class .getResource("FileCarrierTechnologyParameters.class"); assumeTrue(resource != null && "file".equalsIgnoreCase(resource.getProtocol())); @@ -186,7 +188,7 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void validateParentDoesNOtExists() { + void validateParentDoesNOtExists() { final File fileParent = new File(System.getProperty("user.home"), RandomStringUtils.randomAlphabetic(6)); final String fileName = RandomStringUtils.randomAlphabetic(5); final String absolutePath = new File(fileParent, fileName).getAbsolutePath(); @@ -196,27 +198,21 @@ public class FileCarrierTechnologyParametersTest { } @Test - public void validateDirectorNoSystemVariableSet() { - final ValidationResult result = parameters.validate(); - assertThat(result.isValid()).isFalse(); - } - - @Test - public void validateStandardIo() { + void validateStandardIo() { parameters.setStandardIo(true); final ValidationResult result = parameters.validate(); assertThat(result.isValid()).isTrue(); } @Test - public void validateStandardError() { + void validateStandardError() { parameters.setStandardError(true); final ValidationResult result = parameters.validate(); assertThat(result.isValid()).isTrue(); } @Test - public void validateNegativeDelay() { + void validateNegativeDelay() { final long delay = random.nextInt() * -1; parameters.setStartDelay(delay); final ValidationResult result = parameters.validate(); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumerTest.java index 91e705624..385cbbb8a 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/ApexFileEventConsumerTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.File; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperCarrierTechnologyParameters; @@ -36,7 +36,7 @@ import org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnolo import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolTextTokenDelimitedParameters; -public class ApexFileEventConsumerTest { +class ApexFileEventConsumerTest { private ApexFileEventConsumer consumer; private EventHandlerParameters handlerParameters; private File tempFile; @@ -46,8 +46,8 @@ public class ApexFileEventConsumerTest { * * @throws Exception while file cannot be created */ - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { consumer = new ApexFileEventConsumer(); handlerParameters = new EventHandlerParameters(); tempFile = File.createTempFile("afec", ".tmp"); @@ -55,14 +55,14 @@ public class ApexFileEventConsumerTest { } @Test - public void initNoConsumerParameters() { + void initNoConsumerParameters() { final String name = RandomStringUtils.randomAlphanumeric(4); assertThatThrownBy(() -> consumer.init(name, null, null)) .isInstanceOf(ApexEventException.class); } @Test - public void initWrongCarrier() { + void initWrongCarrier() { final String name = RandomStringUtils.randomAlphanumeric(4); final CarrierTechnologyParameters technologyParameters = new SuperDooperCarrierTechnologyParameters(); handlerParameters.setCarrierTechnologyParameters(technologyParameters); @@ -72,32 +72,32 @@ public class ApexFileEventConsumerTest { } @Test - public void initWithoutReceiver() { + void initWithoutReceiver() { final String name = RandomStringUtils.randomAlphanumeric(4); - final EventHandlerParameters handlerParameters = new EventHandlerParameters(); + final EventHandlerParameters parameters = new EventHandlerParameters(); final FileCarrierTechnologyParameters technologyParameters = new FileCarrierTechnologyParameters(); technologyParameters.setFileName(tempFile.getAbsolutePath()); final EventProtocolTextTokenDelimitedParameters params = new SuperTokenDelimitedEventProtocolParameters(); - handlerParameters.setCarrierTechnologyParameters(technologyParameters); - handlerParameters.setEventProtocolParameters(params); + parameters.setCarrierTechnologyParameters(technologyParameters); + parameters.setEventProtocolParameters(params); - assertThatCode(() -> consumer.init(name, handlerParameters, null)) + assertThatCode(() -> consumer.init(name, parameters, null)) .doesNotThrowAnyException(); } @Test - public void getName() throws ApexEventException { + void getName() throws ApexEventException { final String name = RandomStringUtils.randomAlphabetic(5); - final EventHandlerParameters handlerParameters = new EventHandlerParameters(); + final EventHandlerParameters parameters = new EventHandlerParameters(); final FileCarrierTechnologyParameters technologyParameters = new FileCarrierTechnologyParameters(); technologyParameters.setFileName(tempFile.getAbsolutePath()); final EventProtocolTextTokenDelimitedParameters params = new SuperTokenDelimitedEventProtocolParameters(); - handlerParameters.setCarrierTechnologyParameters(technologyParameters); - handlerParameters.setEventProtocolParameters(params); + parameters.setCarrierTechnologyParameters(technologyParameters); + parameters.setEventProtocolParameters(params); - consumer.init(name, handlerParameters, null); + consumer.init(name, parameters, null); assertThat(consumer.getName()).isEqualTo(name); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReaderTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReaderTest.java index 6c595072f..b230d52ab 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReaderTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/HeaderDelimitedTextBlockReaderTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,23 +27,23 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HeaderDelimitedTextBlockReaderTest { +class HeaderDelimitedTextBlockReaderTest { @Test - public void readTextBlockWithDelimeter() throws IOException { + void readTextBlockWithDelimiter() throws IOException { final String startToken = RandomStringUtils.randomAlphabetic(5); final String endToken = RandomStringUtils.randomAlphabetic(6); - final boolean delimeter = true; + final boolean delimiter = true; final String text = RandomStringUtils.randomAlphanumeric(20); final String expected = startToken + text; // Prepare the stream final InputStream stream = new ByteArrayInputStream(expected.getBytes(StandardCharsets.UTF_8)); final HeaderDelimitedTextBlockReader reader = - new HeaderDelimitedTextBlockReader(startToken, endToken, delimeter); + new HeaderDelimitedTextBlockReader(startToken, endToken, delimiter); reader.init(stream); final TextBlock textBlock = reader.readTextBlock(); @@ -51,10 +51,10 @@ public class HeaderDelimitedTextBlockReaderTest { } @Test - public void readTextBlockWithEndTokenDelimeter() throws IOException { + void readTextBlockWithEndTokenDelimiter() throws IOException { final String startToken = RandomStringUtils.randomAlphabetic(5); final String endToken = RandomStringUtils.randomAlphabetic(6); - final boolean delimeter = true; + final boolean delimiter = true; final String text = RandomStringUtils.randomAlphanumeric(20); final String input = startToken + "\n" + text + "\n" + endToken + "\n" + text; final String expected = startToken + "\n" + text + "\n" + endToken; @@ -62,7 +62,7 @@ public class HeaderDelimitedTextBlockReaderTest { final InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); final HeaderDelimitedTextBlockReader reader = - new HeaderDelimitedTextBlockReader(startToken, endToken, delimeter); + new HeaderDelimitedTextBlockReader(startToken, endToken, delimiter); reader.init(stream); final TextBlock textBlock = reader.readTextBlock(); @@ -70,16 +70,16 @@ public class HeaderDelimitedTextBlockReaderTest { } @Test - public void readTextBlockWithoutDelimeter() throws IOException { + void readTextBlockWithoutDelimiter() throws IOException { final String startToken = RandomStringUtils.randomAlphabetic(5); final String endToken = RandomStringUtils.randomAlphabetic(6); - final boolean delimeter = false; + final boolean delimiter = false; final String text = RandomStringUtils.randomAlphanumeric(20); // Prepare the stream final InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); final HeaderDelimitedTextBlockReader reader = - new HeaderDelimitedTextBlockReader(startToken, endToken, delimeter); + new HeaderDelimitedTextBlockReader(startToken, endToken, delimiter); reader.init(stream); final TextBlock textBlock = reader.readTextBlock(); @@ -87,10 +87,10 @@ public class HeaderDelimitedTextBlockReaderTest { } @Test - public void readTextBlockWithEndTokenWithoutDelimeter() throws IOException { + void readTextBlockWithEndTokenWithoutDelimiter() throws IOException { final String startToken = RandomStringUtils.randomAlphabetic(5); final String endToken = RandomStringUtils.randomAlphabetic(6); - final boolean delimeter = false; + final boolean delimiter = false; final String text = RandomStringUtils.randomAlphanumeric(20); final String input = startToken + "\n" + text + "\n" + endToken + "\n" + text; final String expected = startToken + "\n" + text + "\n" + endToken; @@ -98,7 +98,7 @@ public class HeaderDelimitedTextBlockReaderTest { final InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); final HeaderDelimitedTextBlockReader reader = - new HeaderDelimitedTextBlockReader(startToken, endToken, delimeter); + new HeaderDelimitedTextBlockReader(startToken, endToken, delimiter); reader.init(stream); final TextBlock textBlock = reader.readTextBlock(); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockReaderFactoryTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockReaderFactoryTest.java index 4fa42a727..0072535fb 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockReaderFactoryTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockReaderFactoryTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,24 +26,24 @@ import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.impl.apexprotocolplugin.ApexEventProtocolParameters; import org.onap.policy.apex.service.engine.event.impl.jsonprotocolplugin.JsonEventProtocolParameters; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperTokenDelimitedEventProtocolParameters; import org.onap.policy.apex.service.parameters.eventprotocol.EventProtocolParameters; -public class TextBlockReaderFactoryTest { +class TextBlockReaderFactoryTest { private TextBlockReaderFactory factory; - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() { factory = new TextBlockReaderFactory(); } @Test - public void getTaggedReaderTextCharDelimitedParametersParams() throws ApexEventException { + void getTaggedReaderTextCharDelimitedParametersParams() throws ApexEventException { final String text = RandomStringUtils.randomAlphanumeric(22); final InputStream inputStream = prepareInputStream(text); final EventProtocolParameters parameters = new JsonEventProtocolParameters(); @@ -53,7 +53,7 @@ public class TextBlockReaderFactoryTest { } @Test - public void getTaggedReaderTextTokenDelimitedParams() throws ApexEventException { + void getTaggedReaderTextTokenDelimitedParams() throws ApexEventException { final String text = RandomStringUtils.randomAlphanumeric(22); final InputStream inputStream = prepareInputStream(text); new ApexEventProtocolParameters(); @@ -64,7 +64,7 @@ public class TextBlockReaderFactoryTest { } @Test - public void getTaggedReaderNotSupportedParams() { + void getTaggedReaderNotSupportedParams() { final String text = RandomStringUtils.randomAlphanumeric(22); final InputStream inputStream = prepareInputStream(text); final EventProtocolParameters parameters = new ApexEventProtocolParameters(); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockTest.java index 4390c3f3a..ff12c8860 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/consumer/TextBlockTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,17 +19,17 @@ package org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TextBlockTest { +class TextBlockTest { private final Random random = new Random(); @Test - public void isEndOfText() { + void isEndOfText() { final boolean endOfText = random.nextBoolean(); final TextBlock textBlock = new TextBlock(endOfText, null); @@ -37,7 +37,7 @@ public class TextBlockTest { } @Test - public void getText() { + void getText() { final boolean endOfText = random.nextBoolean(); final String text = RandomStringUtils.randomAlphanumeric(8); final TextBlock textBlock = new TextBlock(endOfText, text); @@ -46,7 +46,7 @@ public class TextBlockTest { } @Test - public void setText() { + void setText() { final boolean endOfText = random.nextBoolean(); final String text = RandomStringUtils.randomAlphanumeric(8); final TextBlock textBlock = new TextBlock(endOfText, null); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducerTest.java index 1ac1cdd7c..89ffca74b 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/event/impl/filecarrierplugin/producer/ApexFileEventProducerTest.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2021. Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,16 +28,16 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Random; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.ApexEventException; import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperCarrierTechnologyParameters; import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters; -public class ApexFileEventProducerTest { +class ApexFileEventProducerTest { private final PrintStream out = System.out; private final Random random = new Random(); private ApexFileEventProducer eventProducer; @@ -47,27 +47,27 @@ public class ApexFileEventProducerTest { /** * Prepare for testing. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { eventProducer = new ApexFileEventProducer(); parameters = new EventHandlerParameters(); technologyParameters = new FileCarrierTechnologyParameters(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { System.setOut(out); } @Test - public void initNullParams() { + void initNullParams() { final String name = RandomStringUtils.randomAlphabetic(5); assertThatThrownBy(() -> eventProducer.init(name, null)) .isInstanceOf(ApexEventException.class); } @Test - public void initParamsInvalidCarrier() { + void initParamsInvalidCarrier() { final String name = RandomStringUtils.randomAlphabetic(5); parameters.setCarrierTechnologyParameters(new SuperDooperCarrierTechnologyParameters()); assertThatThrownBy(() -> eventProducer.init(name, parameters)) @@ -75,7 +75,7 @@ public class ApexFileEventProducerTest { } @Test - public void initParamsWithStandardError() { + void initParamsWithStandardError() { final String name = RandomStringUtils.randomAlphabetic(5); technologyParameters.setStandardError(true); @@ -86,7 +86,7 @@ public class ApexFileEventProducerTest { } @Test - public void initParamsWithStandardIo() { + void initParamsWithStandardIo() { final String name = RandomStringUtils.randomAlphabetic(5); technologyParameters.setStandardIo(true); @@ -96,7 +96,7 @@ public class ApexFileEventProducerTest { } @Test - public void initParamsWithFileIsDirectory() { + void initParamsWithFileIsDirectory() { final String name = RandomStringUtils.randomAlphabetic(5); final String fileName = System.getProperty("user.dir"); @@ -108,24 +108,14 @@ public class ApexFileEventProducerTest { } @Test - public void initParamsWithDelay() { - final String name = RandomStringUtils.randomAlphabetic(5); - technologyParameters.setStandardIo(true); - parameters.setCarrierTechnologyParameters(technologyParameters); - - assertThatCode(() -> eventProducer.init(name, parameters)) - .doesNotThrowAnyException(); - } - - @Test - public void sendEventWrongEvent() throws ApexEventException { + void sendEventWrongEvent() throws ApexEventException { final long executionId = random.nextLong(); final String eventName = RandomStringUtils.randomAlphanumeric(4); final String producerName = RandomStringUtils.randomAlphanumeric(5); final Object event = new Object(); technologyParameters.setStandardIo(true); - final EventHandlerParameters parameters = new EventHandlerParameters(); + parameters = new EventHandlerParameters(); parameters.setCarrierTechnologyParameters(technologyParameters); ApexFileEventProducer apexFileEventProducer = new ApexFileEventProducer(); @@ -135,7 +125,7 @@ public class ApexFileEventProducerTest { } @Test - public void sendEvent() throws ApexEventException { + void sendEvent() throws ApexEventException { // Prepare output stream to read data final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); @@ -143,7 +133,7 @@ public class ApexFileEventProducerTest { // Prepare producer final String producerName = RandomStringUtils.randomAlphanumeric(5); technologyParameters.setStandardIo(true); - final EventHandlerParameters parameters = new EventHandlerParameters(); + parameters = new EventHandlerParameters(); parameters.setCarrierTechnologyParameters(technologyParameters); eventProducer.init(producerName, parameters); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArgumentsTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArgumentsTest.java index b5b68c9fc..5232c3845 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArgumentsTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexCommandLineArgumentsTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,11 +24,10 @@ package org.onap.policy.apex.service.engine.main; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.cmd.CommandLineException; /** @@ -36,14 +35,15 @@ import org.onap.policy.common.utils.cmd.CommandLineException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ApexCommandLineArgumentsTest { - @After - public void clearRelativeFileRoot() { +class ApexCommandLineArgumentsTest { + + @AfterEach + void clearRelativeFileRoot() { System.clearProperty("APEX_RELATIVE_FILE_ROOT"); } @Test - public void testCommandLineArguments() throws ApexException, CommandLineException { + void testCommandLineArguments() throws CommandLineException { final ApexCommandLineArguments apexArguments = new ApexCommandLineArguments(); final String[] args01 = {"-h"}; @@ -68,74 +68,74 @@ public class ApexCommandLineArgumentsTest { } @Test - public void testCommandLineArgumentsExceptions() throws ApexException, CommandLineException { + void testCommandLineArgumentsExceptions() throws CommandLineException { final ApexCommandLineArguments apexArguments = new ApexCommandLineArguments(); final String[] args00 = {""}; apexArguments.parse(args00); - assertThatThrownBy(() -> apexArguments.validateInputFiles()) - .hasMessage("Tosca Policy file was not specified as an argument"); + assertThatThrownBy(apexArguments::validateInputFiles) + .hasMessage("Tosca Policy file was not specified as an argument"); final String[] args05 = {"-a"}; assertThatThrownBy(() -> apexArguments.parse(args05)).hasMessage("invalid command line arguments specified") - .hasRootCauseMessage("Unrecognized option: -a"); + .hasRootCauseMessage("Unrecognized option: -a"); final String[] args07 = {"-p", "goodbye", "-h", "aaa"}; assertThatThrownBy(() -> apexArguments.parse(args07)) - .hasMessage("too many command line arguments specified: [-p, goodbye, -h, aaa]"); + .hasMessage("too many command line arguments specified: [-p, goodbye, -h, aaa]"); } @Test - public void testCommandLineFileParameters() throws ApexException, CommandLineException { + void testCommandLineFileParameters() throws CommandLineException { final ApexCommandLineArguments apexArguments = new ApexCommandLineArguments(); final String[] args02 = {"-p", "src/test/resources/parameters/goodParams.json"}; apexArguments.parse(args02); - assertThatCode(() -> apexArguments.validateInputFiles()).doesNotThrowAnyException(); + assertThatCode(apexArguments::validateInputFiles).doesNotThrowAnyException(); } @Test - public void testCommandLineFileParametersExceptions() throws ApexException, CommandLineException { + void testCommandLineFileParametersExceptions() { final ApexCommandLineArguments apexArguments = new ApexCommandLineArguments(); final String[] args00 = {"-c", "zooby"}; assertThatThrownBy(() -> apexArguments.parse(args00)).hasMessage("invalid command line arguments specified") - .hasRootCauseMessage("Unrecognized option: -c"); + .hasRootCauseMessage("Unrecognized option: -c"); final String[] args01 = {"-p"}; assertThatThrownBy(() -> apexArguments.parse(args01)).hasMessage("invalid command line arguments specified") - .hasRootCauseMessage("Missing argument for option: p"); + .hasRootCauseMessage("Missing argument for option: p"); final String[] args03 = {"-p", "src/test/resources/parameters/goodParams.json", "-m", "zooby"}; assertThatThrownBy(() -> apexArguments.parse(args03)).hasMessage("invalid command line arguments specified") - .hasRootCauseMessage("Unrecognized option: -m"); + .hasRootCauseMessage("Unrecognized option: -m"); } @Test - public void testCommandLineRelativeRootParameters() throws ApexException, CommandLineException { + void testCommandLineRelativeRootParameters() throws CommandLineException { final ApexCommandLineArguments apexArguments = new ApexCommandLineArguments(); final String[] args00 = {"-p", "src/test/resources/parameters/goodParams.json", "-rfr", "zooby"}; apexArguments.parse(args00); - assertThatThrownBy(() -> apexArguments.validateInputFiles()) - .hasMessageContaining("zooby\" does not exist or is not a directory"); + assertThatThrownBy(apexArguments::validateInputFiles) + .hasMessageContaining("zooby\" does not exist or is not a directory"); final String[] args01 = {"-rfr"}; assertThatThrownBy(() -> apexArguments.parse(args01)).hasMessage("invalid command line arguments specified") - .hasRootCauseMessage("Missing argument for option: rfr"); + .hasRootCauseMessage("Missing argument for option: rfr"); final String[] args02 = {"-p", "src/test/resources/parameters/goodParams.json", "-rfr", "pom.xml"}; apexArguments.parse(args02); - assertThatThrownBy(() -> apexArguments.validateInputFiles()) - .hasMessageContaining("pom.xml\" does not exist or is not a directory"); + assertThatThrownBy(apexArguments::validateInputFiles) + .hasMessageContaining("pom.xml\" does not exist or is not a directory"); final String[] args03 = {"-p", "src/test/resources/parameters/goodParams.json", "-rfr", "target"}; apexArguments.parse(args03); - assertThatCode(() -> apexArguments.validateInputFiles()).doesNotThrowAnyException(); + assertThatCode(apexArguments::validateInputFiles).doesNotThrowAnyException(); final String[] args04 = {"-p", "parameters/goodParamsRelative.json", "-rfr", "src/test/resources"}; apexArguments.parse(args04); - assertThatCode(() -> apexArguments.validateInputFiles()).doesNotThrowAnyException(); + assertThatCode(apexArguments::validateInputFiles).doesNotThrowAnyException(); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java index 29a3e0f00..f09dfd785 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexMainTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2020-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -25,25 +25,25 @@ package org.onap.policy.apex.service.engine.main; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.model.basicmodel.service.ModelService; import org.onap.policy.common.parameters.ParameterService; /** * Test the ApexMain class. */ -public class ApexMainTest { +class ApexMainTest { + private final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); private final PrintStream stdout = System.out; private ApexMain apexMain1; @@ -54,8 +54,8 @@ public class ApexMainTest { * * @throws Exception if an error occurs */ - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { System.setOut(new PrintStream(outContent)); } @@ -64,8 +64,8 @@ public class ApexMainTest { * * @throws Exception if an error occurs */ - @After - public void teardown() throws Exception { + @AfterEach + void teardown() throws Exception { if (null != apexMain1) { apexMain1.shutdown(); } @@ -76,46 +76,46 @@ public class ApexMainTest { } @Test - public void testNullParameters() throws ApexException { + void testNullParameters() { ApexMain.main(null); await().atMost(200, TimeUnit.MILLISECONDS).until(() -> outContent.toString() - .contains("Tosca Policy file was not specified as an argument")); + .contains("Tosca Policy file was not specified as an argument")); assertThat(outContent.toString()) .contains("Tosca Policy file was not specified as an argument"); } @Test - public void testBadArguments() throws ApexException { - String[] args = { "-whee" }; + void testBadArguments() { + String[] args = {"-whee"}; apexMain1 = new ApexMain(args); await().atMost(200, TimeUnit.MILLISECONDS).until(() -> outContent.toString() - .contains("invalid command line arguments specified")); + .contains("invalid command line arguments specified")); assertNotNull(apexMain1); } @Test - public void testHelp() throws ApexException { - String[] args = { "-h" }; + void testHelp() { + String[] args = {"-h"}; apexMain1 = new ApexMain(args); await().atMost(200, TimeUnit.MILLISECONDS).until(() -> outContent.toString() - .contains("usage: org.onap.policy.apex.service.engine.main.ApexMain [options...]")); + .contains("usage: org.onap.policy.apex.service.engine.main.ApexMain [options...]")); assertNotNull(apexMain1); } @Test - public void testBadParameters() throws ApexException { - String[] args = { "-p", "src/test/resources/parameters/badParams.json" }; + void testBadParameters() { + String[] args = {"-p", "src/test/resources/parameters/badParams.json"}; apexMain1 = new ApexMain(args); await().atMost(200, TimeUnit.MILLISECONDS).until(() -> outContent.toString() - .contains("item has status INVALID")); + .contains("item has status INVALID")); assertNotNull(apexMain1); } @Test - public void testCorrectParameters() throws ApexException { + void testCorrectParameters() { String[] args = {"-p", "src/test/resources/parameters/correctParams.json"}; apexMain1 = new ApexMain(args); @@ -126,7 +126,7 @@ public class ApexMainTest { } @Test - public void testJavaProperties() throws ApexException { + void testJavaProperties() { String[] args = {"-p", "src/test/resources/parameters/correctParamsJavaProperties.json"}; apexMain1 = new ApexMain(args); @@ -139,7 +139,7 @@ public class ApexMainTest { } @Test - public void testCorrectParametersWithMultiplePolicies() throws ApexException { + void testCorrectParametersWithMultiplePolicies() { String[] args1 = {"-p", "src/test/resources/parameters/correctParams.json"}; String[] args2 = {"-p", "src/test/resources/parameters/correctParams2.json"}; apexMain1 = new ApexMain(args1); @@ -156,7 +156,7 @@ public class ApexMainTest { } @Test - public void testInCorrectParametersWithMultiplePolicies() throws ApexException { + void testInCorrectParametersWithMultiplePolicies() { String[] args = {"-p", "src/test/resources/parameters/correctParams.json"}; apexMain1 = new ApexMain(args); apexMain2 = new ApexMain(args); @@ -168,7 +168,7 @@ public class ApexMainTest { } @Test - public void testInvalidArgsWithMultiplePolicies() throws ApexException { + void testInvalidArgsWithMultiplePolicies() { String[] args = {"-c", "file1", "-m", "file2"}; apexMain1 = new ApexMain(args); assertFalse(apexMain1.isAlive()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexPolicyStatisticsManagerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexPolicyStatisticsManagerTest.java index 6213cae1f..59ebfe50d 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexPolicyStatisticsManagerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/main/ApexPolicyStatisticsManagerTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,27 +21,27 @@ package org.onap.policy.apex.service.engine.main; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import io.prometheus.client.CollectorRegistry; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.resources.PrometheusUtils; -public class ApexPolicyStatisticsManagerTest { +class ApexPolicyStatisticsManagerTest { private ApexPolicyStatisticsManager statisticsManager; /** * Starts the statisticsManager object for tests. */ - @Before - public void setup() { + @BeforeEach + void setup() { statisticsManager = new ApexPolicyStatisticsManager(); } @Test - public void testUpdatePolicyDeployCounter() { + void testUpdatePolicyDeployCounter() { statisticsManager.updatePolicyDeployCounter(false); assertDeploys(1, 0, 1); @@ -52,7 +52,7 @@ public class ApexPolicyStatisticsManagerTest { } @Test - public void testUpdatePolicyExecutedCounter() { + void testUpdatePolicyExecutedCounter() { statisticsManager.updatePolicyExecutedCounter(true); assertExecuted(1, 1, 0); @@ -61,7 +61,7 @@ public class ApexPolicyStatisticsManagerTest { } @Test - public void testUpdatePolicyUndeployCounter() { + void testUpdatePolicyUndeployCounter() { statisticsManager.updatePolicyUndeployCounter(false); assertUndeploys(1, 0, 1); @@ -91,11 +91,11 @@ public class ApexPolicyStatisticsManagerTest { private void checkDeploymentsMetrics(String operation) { final var defaultRegistry = CollectorRegistry.defaultRegistry; Double totalCount = defaultRegistry.getSampleValue("pdpa_policy_deployments_total", - new String[]{"operation", "status"}, new String[]{operation, "TOTAL"}); + new String[] {"operation", "status"}, new String[] {operation, "TOTAL"}); Double successCount = defaultRegistry.getSampleValue("pdpa_policy_deployments_total", - new String[]{"operation", "status"}, new String[]{operation, "SUCCESS"}); + new String[] {"operation", "status"}, new String[] {operation, "SUCCESS"}); Double failCount = defaultRegistry.getSampleValue("pdpa_policy_deployments_total", - new String[]{"operation", "status"}, new String[]{operation, "FAIL"}); + new String[] {"operation", "status"}, new String[] {operation, "FAIL"}); if (PrometheusUtils.DEPLOY_OPERATION.equals(operation)) { assertEquals(totalCount.intValue(), statisticsManager.getPolicyDeployCount()); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ApexParametersTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ApexParametersTest.java index dd76374d8..20fea1ce7 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ApexParametersTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ApexParametersTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020,2022 Nordix Foundation. + * Modifications Copyright (C) 2020, 2022, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -25,13 +25,13 @@ package org.onap.policy.apex.service.engine.parameters; 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.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.ApexParameterHandler; import org.onap.policy.apex.service.parameters.ApexParameters; @@ -40,10 +40,10 @@ import org.onap.policy.common.parameters.ParameterException; /** * Test the ApexParameters class. */ -public class ApexParametersTest { +class ApexParametersTest { @Test - public void testJavaPropertiesOk() throws ParameterException { + void testJavaPropertiesOk() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/javaPropertiesOK.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -57,7 +57,7 @@ public class ApexParametersTest { } @Test - public void testJavaPropertiesEmpty() throws ParameterException { + void testJavaPropertiesEmpty() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/javaPropertiesEmpty.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -67,7 +67,7 @@ public class ApexParametersTest { } @Test - public void testJavaPropertiesBad() throws ParameterException { + void testJavaPropertiesBad() { final String[] args = {"-p", "src/test/resources/parameters/javaPropertiesBad.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -80,7 +80,7 @@ public class ApexParametersTest { } @Test - public void testPolicyModelFromMetadata() throws ParameterException { + void testPolicyModelFromMetadata() throws ParameterException { // Policy Models provided only in metadata. final String[] args = {"-p", "src/test/resources/parameters/policyModelFromMetadata.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -95,7 +95,7 @@ public class ApexParametersTest { } @Test - public void testPolicyModelFromProperties() throws ParameterException { + void testPolicyModelFromProperties() throws ParameterException { // Policy models provided in properties under EngineServiceParameters for backward compatibility final String[] args = {"-p", "src/test/resources/parameters/policyModelFromProperties.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -110,7 +110,7 @@ public class ApexParametersTest { } @Test - public void testPolicyModelFromPropertiesAndMetadata() throws ParameterException { + void testPolicyModelFromPropertiesAndMetadata() throws ParameterException { // Policy models provided in both properties and in metadata. policyModels in metadata takes precedence final String[] args = {"-p", "src/test/resources/parameters/policyModelMultiple.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -125,7 +125,7 @@ public class ApexParametersTest { } @Test - public void testGettersSetters() { + void testGettersSetters() { ApexParameters pars = new ApexParameters(); assertNotNull(pars); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java index a55afbed4..2c02f14ca 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ContextParameterTests.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,9 +23,10 @@ package org.onap.policy.apex.service.engine.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperDistributorParameters; import org.onap.policy.apex.service.parameters.ApexParameterHandler; @@ -37,10 +38,10 @@ import org.onap.policy.common.parameters.ParameterException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ContextParameterTests { +class ContextParameterTests { @Test - public void testNoParamsTest() { + void testNoParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextNoParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -51,18 +52,18 @@ public class ContextParameterTests { } @Test - public void testBadParamsTest() { + void testBadParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) - .hasMessage("error reading parameters from \"src/test/resources/parameters/serviceContextBadParams.json\"" - + "\n(ParameterRuntimeException):failed to deserialize the parameters for " - + "\"contextParameters\" to parameter class " + "\"hello\"\njava.lang.ClassNotFoundException: hello"); + .hasMessageContaining("error reading parameters from " + + "\"src/test/resources/parameters/serviceContextBadParams.json\"") + .hasMessageContaining("class " + "\"hello\"\njava.lang.ClassNotFoundException: hello"); } @Test - public void testBadPluginParamNameTest() { + void testBadPluginParamNameTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadPluginNameParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -74,19 +75,20 @@ public class ContextParameterTests { } @Test - public void testBadClassParamTest() { + void testBadClassParamTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); - assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)).hasMessage( - "error reading parameters from " + "\"src/test/resources/parameters/serviceContextBadClassParams.json\"" - + "\n(ParameterRuntimeException):failed to deserialize " + "the parameters for \"contextParameters\"" - + " to parameter class \"java.lang.Integer\"\ncom.google.gson.JsonSyntaxException: " - + "java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $"); + assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) + .hasMessageContaining("error reading parameters from " + + "\"src/test/resources/parameters/serviceContextBadClassParams.json\"") + .hasMessageContaining("(ParameterRuntimeException):failed to deserialize the parameters for " + + "\"contextParameters\" to parameter class \"java.lang.Integer\"\ncom.google.gson.JsonSyntaxException" + + ": java.lang.IllegalStateException: Expected NUMBER but was BEGIN_OBJECT at path $"); } @Test - public void testBadPluginClassTest() { + void testBadPluginClassTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadPluginClassParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -102,7 +104,7 @@ public class ContextParameterTests { } @Test - public void testOkFlushParamTest() throws ParameterException { + void testOkFlushParamTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/serviceContextOKFlushParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -115,7 +117,7 @@ public class ContextParameterTests { } @Test - public void testOkDefaultParamTest() throws ParameterException { + void testOkDefaultParamTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/serviceContextOKDefaultParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -128,7 +130,7 @@ public class ContextParameterTests { } @Test - public void testOkDistParamTest() throws ParameterException { + void testOkDistParamTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/serviceContextOKDistParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -142,7 +144,7 @@ public class ContextParameterTests { } @Test - public void testOkFullDefaultParamTest() throws ParameterException { + void testOkFullDefaultParamTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/goodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -164,7 +166,7 @@ public class ContextParameterTests { } @Test - public void testOkFullParamTest() throws ParameterException { + void testOkFullParamTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/serviceContextOKFullParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -186,13 +188,13 @@ public class ContextParameterTests { infinispanParameters.getClass().getName()); assertEquals("my/lovely/configFile.xml", infinispanParameters.getConfigFile()); assertEquals("holy/stone.xml", infinispanParameters.getJgroupsFile()); - assertEquals(false, infinispanParameters.isPreferIPv4Stack()); + assertFalse(infinispanParameters.isPreferIPv4Stack()); assertEquals("fatherted", infinispanParameters.getJgroupsBindAddress()); } @Test - public void testBadClassDistParamTest() { + void testBadClassDistParamTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassDistParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -207,7 +209,7 @@ public class ContextParameterTests { } @Test - public void testBadClassLockParamTest() { + void testBadClassLockParamTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassLockParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -222,7 +224,7 @@ public class ContextParameterTests { } @Test - public void testBadClassPersistParamTest() { + void testBadClassPersistParamTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassPersistParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ExecutorParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ExecutorParameterTests.java index 92a7b7d54..ad1dc442d 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ExecutorParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ExecutorParameterTests.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,10 +23,10 @@ package org.onap.policy.apex.service.engine.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.ApexParameterHandler; import org.onap.policy.apex.service.parameters.ApexParameters; @@ -37,37 +37,38 @@ import org.onap.policy.common.parameters.ParameterException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ExecutorParameterTests { - @After - public void resetRelativeFileRoot() { +class ExecutorParameterTests { + + @AfterEach + void resetRelativeFileRoot() { System.clearProperty("APEX_RELATIVE_FILE_ROOT"); } @Test - public void testNoParamsTest() throws ParameterException { + void testNoParamsTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorNoParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments); assertEquals(0, - parameters.getEngineServiceParameters().getEngineParameters().getExecutorParameterMap().size()); + parameters.getEngineServiceParameters().getEngineParameters().getExecutorParameterMap().size()); } @Test - public void testBadParamsTest() { + void testBadParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) .hasMessage("error reading parameters from " - + "\"src/test/resources/parameters/serviceExecutorBadParams.json\"\n" - + "(ParameterRuntimeException):value of \"executorParameters:ZOOBY\" entry is not " - + "a parameter JSON object"); + + "\"src/test/resources/parameters/serviceExecutorBadParams.json\"\n" + + "(ParameterRuntimeException):value of \"executorParameters:ZOOBY\" entry is not " + + "a parameter JSON object"); } @Test - public void testNoExecutorParamsTest() { + void testNoExecutorParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorNoExecutorParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -79,7 +80,7 @@ public class ExecutorParameterTests { } @Test - public void testEmptyParamsTest() { + void testEmptyParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorEmptyParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -91,7 +92,7 @@ public class ExecutorParameterTests { } @Test - public void testBadPluginParamNameTest() { + void testBadPluginParamNameTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginNameParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -103,7 +104,7 @@ public class ExecutorParameterTests { } @Test - public void testBadPluginParamObjectTest() { + void testBadPluginParamObjectTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginValueObjectParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -115,7 +116,7 @@ public class ExecutorParameterTests { } @Test - public void testBadPluginParamBlankTest() { + void testBadPluginParamBlankTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginValueBlankParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -127,20 +128,20 @@ public class ExecutorParameterTests { } @Test - public void testBadPluginParamValueTest() { + void testBadPluginParamValueTest() { final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginValueParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) - .hasMessage("error reading parameters from" - + " \"src/test/resources/parameters/serviceExecutorBadPluginValueParams.json\"\n" - + "(ParameterRuntimeException):failed to deserialize the parameters " + .hasMessageContaining("error reading parameters from" + + " \"src/test/resources/parameters/serviceExecutorBadPluginValueParams.json\"\n") + .hasMessageContaining("(ParameterRuntimeException):failed to deserialize the parameters " + "for \"executorParameters:LOOBY\" to parameter class \"helloworld\"\n" + "java.lang.ClassNotFoundException: helloworld"); } @Test - public void testGoodParametersTest() throws ParameterException { + void testGoodParametersTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/goodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -155,7 +156,7 @@ public class ExecutorParameterTests { } @Test - public void testRelativeParametersTest() throws ParameterException { + void testRelativeParametersTest() throws ParameterException { // @formatter:off final String[] args = { "-rfr", diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java index e37da3540..7257855a3 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ParameterTests.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -24,13 +24,14 @@ package org.onap.policy.apex.service.engine.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.file.NoSuchFileException; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.consumer.ApexFileEventConsumer; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.producer.ApexFileEventProducer; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; @@ -48,9 +49,9 @@ import org.onap.policy.common.parameters.ParameterException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ParameterTests { +class ParameterTests { @Test - public void testInvalidParametersNoFileTest() throws ParameterException { + void testInvalidParametersNoFileTest() { final String[] args = {"-p", "src/test/resources/parameters/invalidNoFile.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -59,7 +60,7 @@ public class ParameterTests { } @Test - public void testInvalidParametersEmptyTest() { + void testInvalidParametersEmptyTest() { final String[] args = {"-p", "src/test/resources/parameters/empty.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -68,7 +69,7 @@ public class ParameterTests { } @Test - public void testInvalidParametersNoParamsTest() { + void testInvalidParametersNoParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/noParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -81,7 +82,7 @@ public class ParameterTests { } @Test - public void testInvalidParametersBlankParamsTest() { + void testInvalidParametersBlankParamsTest() { final String[] args = {"-p", "src/test/resources/parameters/blankParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -96,7 +97,7 @@ public class ParameterTests { } @Test - public void testInvalidParametersTest() { + void testInvalidParametersTest() { final String[] args = {"-p", "src/test/resources/parameters/badParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -109,15 +110,15 @@ public class ParameterTests { .hasMessageContaining("\"instanceCount\" value \"-345\" INVALID, is below the minimum") .hasMessageContaining("\"deploymentPort\" value \"65536\" INVALID, exceeds the maximum") .hasMessageContaining("eventOutputParameters", "FirstProducer", "EventHandlerParameters", - "FileCarrierTechnologyParameters") + "FileCarrierTechnologyParameters") .hasMessageContaining("\"fileName\" value \"null\" INVALID, is blank") .hasMessageContaining("eventInputParameters", "TheFileConsumer1", "EventHandlerParameters", - "FileCarrierTechnologyParameters") + "FileCarrierTechnologyParameters") .hasMessageContaining("\"fileName\" value \"null\" INVALID, is blank"); } @Test - public void testGoodParametersTest() throws ParameterException { + void testGoodParametersTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/goodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -128,40 +129,40 @@ public class ParameterTests { assertTrue(parameters.getEventOutputParameters().containsKey("FirstProducer")); assertTrue(parameters.getEventOutputParameters().containsKey("MyOtherProducer")); assertEquals("FILE", parameters.getEventOutputParameters().get("FirstProducer") - .getCarrierTechnologyParameters().getLabel()); + .getCarrierTechnologyParameters().getLabel()); assertEquals("FILE", parameters.getEventOutputParameters().get("MyOtherProducer") - .getCarrierTechnologyParameters().getLabel()); + .getCarrierTechnologyParameters().getLabel()); assertEquals(ApexFileEventProducer.class.getName(), parameters.getEventOutputParameters() - .get("MyOtherProducer").getCarrierTechnologyParameters().getEventProducerPluginClass()); + .get("MyOtherProducer").getCarrierTechnologyParameters().getEventProducerPluginClass()); assertEquals(ApexFileEventConsumer.class.getName(), parameters.getEventOutputParameters() - .get("MyOtherProducer").getCarrierTechnologyParameters().getEventConsumerPluginClass()); + .get("MyOtherProducer").getCarrierTechnologyParameters().getEventConsumerPluginClass()); assertEquals("JSON", - parameters.getEventOutputParameters().get("FirstProducer").getEventProtocolParameters().getLabel()); + parameters.getEventOutputParameters().get("FirstProducer").getEventProtocolParameters().getLabel()); assertEquals("JSON", parameters.getEventOutputParameters().get("MyOtherProducer") - .getEventProtocolParameters().getLabel()); + .getEventProtocolParameters().getLabel()); assertTrue(parameters.getEventInputParameters().containsKey("TheFileConsumer1")); assertTrue(parameters.getEventInputParameters().containsKey("MySuperDooperConsumer1")); assertEquals("FILE", parameters.getEventInputParameters().get("TheFileConsumer1") - .getCarrierTechnologyParameters().getLabel()); + .getCarrierTechnologyParameters().getLabel()); assertEquals("SUPER_DOOPER", parameters.getEventInputParameters().get("MySuperDooperConsumer1") - .getCarrierTechnologyParameters().getLabel()); + .getCarrierTechnologyParameters().getLabel()); assertEquals("JSON", parameters.getEventInputParameters().get("TheFileConsumer1") - .getEventProtocolParameters().getLabel()); + .getEventProtocolParameters().getLabel()); assertEquals("SUPER_TOK_DEL", parameters.getEventInputParameters().get("MySuperDooperConsumer1") - .getEventProtocolParameters().getLabel()); + .getEventProtocolParameters().getLabel()); assertEquals(ApexFileEventProducer.class.getName(), parameters.getEventInputParameters() - .get("TheFileConsumer1").getCarrierTechnologyParameters().getEventProducerPluginClass()); + .get("TheFileConsumer1").getCarrierTechnologyParameters().getEventProducerPluginClass()); assertEquals(ApexFileEventConsumer.class.getName(), parameters.getEventInputParameters() - .get("TheFileConsumer1").getCarrierTechnologyParameters().getEventConsumerPluginClass()); + .get("TheFileConsumer1").getCarrierTechnologyParameters().getEventConsumerPluginClass()); assertEquals(SuperDooperEventProducer.class.getName(), parameters.getEventInputParameters() - .get("MySuperDooperConsumer1").getCarrierTechnologyParameters().getEventProducerPluginClass()); + .get("MySuperDooperConsumer1").getCarrierTechnologyParameters().getEventProducerPluginClass()); assertEquals(SuperDooperEventSubscriber.class.getName(), parameters.getEventInputParameters() - .get("MySuperDooperConsumer1").getCarrierTechnologyParameters().getEventConsumerPluginClass()); + .get("MySuperDooperConsumer1").getCarrierTechnologyParameters().getEventConsumerPluginClass()); } @Test - public void testSuperDooperParametersTest() throws ParameterException { + void testSuperDooperParametersTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/superDooperParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -174,23 +175,32 @@ public class ParameterTests { assertEquals(65522, parameters.getEngineServiceParameters().getDeploymentPort()); final CarrierTechnologyParameters prodCarrierTech = - parameters.getEventOutputParameters().get("FirstProducer").getCarrierTechnologyParameters(); + parameters.getEventOutputParameters().get("FirstProducer").getCarrierTechnologyParameters(); final EventProtocolParameters prodEventProt = - parameters.getEventOutputParameters().get("FirstProducer").getEventProtocolParameters(); + parameters.getEventOutputParameters().get("FirstProducer").getEventProtocolParameters(); final CarrierTechnologyParameters consCarrierTech = - parameters.getEventInputParameters().get("MySuperDooperConsumer1").getCarrierTechnologyParameters(); + parameters.getEventInputParameters().get("MySuperDooperConsumer1").getCarrierTechnologyParameters(); final EventProtocolParameters consEventProt = - parameters.getEventInputParameters().get("MySuperDooperConsumer1").getEventProtocolParameters(); + parameters.getEventInputParameters().get("MySuperDooperConsumer1").getEventProtocolParameters(); assertEquals("SUPER_DOOPER", prodCarrierTech.getLabel()); assertEquals("SUPER_TOK_DEL", prodEventProt.getLabel()); assertEquals("SUPER_DOOPER", consCarrierTech.getLabel()); assertEquals("JSON", consEventProt.getLabel()); - assertTrue(prodCarrierTech instanceof SuperDooperCarrierTechnologyParameters); + assertInstanceOf(SuperDooperCarrierTechnologyParameters.class, prodCarrierTech); final SuperDooperCarrierTechnologyParameters superDooperParameters = - (SuperDooperCarrierTechnologyParameters) prodCarrierTech; + (SuperDooperCarrierTechnologyParameters) prodCarrierTech; + assertFalse(superDooperParameters.isEnableAutoCommit()); + assertEqualsOnFields(superDooperParameters); + + final String[] consumerTopics = {"consumer-out-0", "consumer-out-1", "consumer-out-2"}; + assertEquals(Arrays.asList(consumerTopics), superDooperParameters.getConsumerTopicList()); + + } + + private static void assertEqualsOnFields(SuperDooperCarrierTechnologyParameters superDooperParameters) { assertEquals("somehost:12345", superDooperParameters.getBootstrapServers()); assertEquals("0", superDooperParameters.getAcks()); assertEquals(25, superDooperParameters.getRetries()); @@ -198,7 +208,6 @@ public class ParameterTests { assertEquals(21, superDooperParameters.getLingerTime()); assertEquals(50505050, superDooperParameters.getBufferMemory()); assertEquals("first-group-id", superDooperParameters.getGroupId()); - assertFalse(superDooperParameters.isEnableAutoCommit()); assertEquals(441, superDooperParameters.getAutoCommitTime()); assertEquals(987, superDooperParameters.getSessionTimeout()); assertEquals("producer-out", superDooperParameters.getProducerTopic()); @@ -207,9 +216,5 @@ public class ParameterTests { assertEquals("some.value.serailizer", superDooperParameters.getValueSerializer()); assertEquals("some.key.deserailizer", superDooperParameters.getKeyDeserializer()); assertEquals("some.value.deserailizer", superDooperParameters.getValueDeserializer()); - - final String[] consumerTopics = {"consumer-out-0", "consumer-out-1", "consumer-out-2"}; - assertEquals(Arrays.asList(consumerTopics), superDooperParameters.getConsumerTopicList()); - } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java index 0b05eac63..1f9a0d349 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/ProducerConsumerTests.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -24,10 +24,11 @@ package org.onap.policy.apex.service.engine.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.event.impl.filecarrierplugin.FileCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.parameters.ApexParameterHandler; @@ -39,9 +40,9 @@ import org.onap.policy.common.parameters.ParameterException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class ProducerConsumerTests { +class ProducerConsumerTests { @Test - public void testGoodParametersTest() throws ParameterException { + void testGoodParametersTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/goodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -71,7 +72,7 @@ public class ProducerConsumerTests { } @Test - public void testNoCarrierTechnology() { + void testNoCarrierTechnology() { final String[] args = {"-p", "src/test/resources/parameters/prodConsNoCT.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -79,12 +80,12 @@ public class ProducerConsumerTests { .hasMessageContaining("src/test/resources/parameters/prodConsNoCT.json") .hasMessageContaining("ApexParameters") .hasMessageContaining("eventInputParameters", "aConsumer", "EventHandlerParameters", - "carrierTechnologyParameters") + "carrierTechnologyParameters") .hasMessageContaining("is null"); } @Test - public void testNoEventProcol() { + void testNoEventProcol() { final String[] args = {"-p", "src/test/resources/parameters/prodConsNoEP.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -92,15 +93,15 @@ public class ProducerConsumerTests { .hasMessageContaining("src/test/resources/parameters/prodConsNoEP.json") .hasMessageContaining("ApexParameters") .hasMessageContaining("eventOutputParameters", "aProducer", "EventHandlerParameters", - "eventProtocolParameters") + "eventProtocolParameters") .hasMessageContaining("eventInputParameters", "aConsumer", "EventHandlerParameters", - "FileCarrierTechnologyParameters", "fileName") + "FileCarrierTechnologyParameters", "fileName") .hasMessageContaining("is null") .hasMessageContaining("is blank"); } @Test - public void testNoCarrierTechnologyParClass() { + void testNoCarrierTechnologyParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsNoCTParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -111,7 +112,7 @@ public class ProducerConsumerTests { } @Test - public void testMismatchCarrierTechnologyParClass() { + void testMismatchCarrierTechnologyParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsMismatchCTParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -124,14 +125,16 @@ public class ProducerConsumerTests { } @Test - public void testWrongTypeCarrierTechnologyParClass() { + void testWrongTypeCarrierTechnologyParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsWrongTypeCTParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); - assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)).hasMessage( - "error reading parameters from " + "\"src/test/resources/parameters/prodConsWrongTypeCTParClass.json\"\n" - + "(ParameterRuntimeException):could not create default parameters for carrier technology " - + "\"SUPER_DOOPER\"\n" + "class org.onap.policy.apex.service.engine.parameters.dummyclasses." + assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) + .hasMessageContaining( + "error reading parameters from " + "\"src/test/resources/parameters/prodConsWrongTypeCTParClass.json\"\n") + .hasMessageContaining("(ParameterRuntimeException):could not create default parameters for " + + "carrier technology \"SUPER_DOOPER\"\n" + + "class org.onap.policy.apex.service.engine.parameters.dummyclasses." + "SuperTokenDelimitedEventProtocolParameters cannot be cast to class " + "org.onap.policy.apex.service.parameters.carriertechnology.CarrierTechnologyParameters (org.onap." + "policy.apex.service.engine.parameters.dummyclasses.SuperTokenDelimitedEventProtocolParameters " @@ -140,7 +143,7 @@ public class ProducerConsumerTests { } @Test - public void testOkFileNameCarrierTechnology() throws ParameterException { + void testOkFileNameCarrierTechnology() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/prodConsOKFileName.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -148,14 +151,14 @@ public class ProducerConsumerTests { final FileCarrierTechnologyParameters fileParams = (FileCarrierTechnologyParameters) parameters .getEventOutputParameters().get("aProducer").getCarrierTechnologyParameters(); assertTrue(fileParams.getFileName().endsWith("target/aaa.json")); - assertEquals(false, fileParams.isStandardError()); - assertEquals(false, fileParams.isStandardIo()); - assertEquals(false, fileParams.isStreamingMode()); + assertFalse(fileParams.isStandardError()); + assertFalse(fileParams.isStandardIo()); + assertFalse(fileParams.isStreamingMode()); } @Test - public void testBadFileNameCarrierTechnology() { + void testBadFileNameCarrierTechnology() { final String[] args = {"-p", "src/test/resources/parameters/prodConsBadFileName.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -163,12 +166,12 @@ public class ProducerConsumerTests { .hasMessageContaining("src/test/resources/parameters/prodConsBadFileName.json") .hasMessageContaining("ApexParameters") .hasMessageContaining("eventOutputParameters", "aProducer", "EventHandlerParameters", - "FileCarrierTechnologyParameters", "fileName") + "FileCarrierTechnologyParameters", "fileName") .hasMessageContaining("is blank"); } @Test - public void testBadEventProtocolParClass() { + void testBadEventProtocolParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsBadEPParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -181,7 +184,7 @@ public class ProducerConsumerTests { } @Test - public void testNoEventProtocolParClass() { + void testNoEventProtocolParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsNoEPParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -192,7 +195,7 @@ public class ProducerConsumerTests { } @Test - public void testMismatchEventProtocolParClass() { + void testMismatchEventProtocolParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsMismatchEPParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -206,17 +209,19 @@ public class ProducerConsumerTests { } @Test - public void testWrongTypeEventProtocolParClass() { + void testWrongTypeEventProtocolParClass() { final String[] args = {"-p", "src/test/resources/parameters/prodConsWrongTypeEPParClass.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); - assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)).hasMessage( - "error reading parameters from " + "\"src/test/resources/parameters/prodConsWrongTypeEPParClass.json\"\n" - + "(ParameterRuntimeException):could not create default parameters for event protocol " - + "\"SUPER_TOK_DEL\"\n" + "class org.onap.policy.apex.service.engine." + assertThatThrownBy(() -> new ApexParameterHandler().getParameters(arguments)) + .hasMessageContaining("error reading parameters from " + + "\"src/test/resources/parameters/prodConsWrongTypeEPParClass.json\"\n") + .hasMessageContaining("(ParameterRuntimeException):could not create default parameters for event protocol " + + "\"SUPER_TOK_DEL\"\nclass org.onap.policy.apex.service.engine." + "parameters.dummyclasses.SuperDooperCarrierTechnologyParameters " + "cannot be cast to class org.onap.policy.apex.service." - + "parameters.eventprotocol.EventProtocolParameters (org.onap.policy.apex.service.engine.parameters" + + "parameters.eventprotocol.EventProtocolParameters ") + .hasMessageContaining("org.onap.policy.apex.service.engine.parameters" + ".dummyclasses.SuperDooperCarrierTechnologyParameters and org.onap.policy.apex.service.parameters" + ".eventprotocol.EventProtocolParameters are in unnamed module of loader 'app')"); } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java index aaa98fd47..e9e989629 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/parameters/SyncParameterTests.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. + * Modifications Copyright (C) 2019-2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -24,11 +24,12 @@ package org.onap.policy.apex.service.engine.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexCommandLineArguments; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperCarrierTechnologyParameters; import org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperTokenDelimitedEventProtocolParameters; @@ -44,9 +45,10 @@ import org.onap.policy.common.parameters.ParameterException; * * @author Liam Fallon (liam.fallon@ericsson.com) */ -public class SyncParameterTests { +class SyncParameterTests { + @Test - public void testSyncBadNoSyncWithPeer() throws ParameterException { + void testSyncBadNoSyncWithPeer() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsNoSyncWithPeer.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -58,7 +60,7 @@ public class SyncParameterTests { } @Test - public void testSyncBadNotSyncWithPeer() throws ParameterException { + void testSyncBadNotSyncWithPeer() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsNotSyncWithPeer.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -70,7 +72,7 @@ public class SyncParameterTests { } @Test - public void testSyncBadSyncBadPeers() throws ParameterException { + void testSyncBadSyncBadPeers() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsBadPeers.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -85,7 +87,7 @@ public class SyncParameterTests { } @Test - public void testSyncBadSyncInvalidTimeout() throws ParameterException { + void testSyncBadSyncInvalidTimeout() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsInvalidTimeout.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -103,7 +105,7 @@ public class SyncParameterTests { } @Test - public void testSyncBadSyncBadTimeout() throws ParameterException { + void testSyncBadSyncBadTimeout() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsBadTimeout.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -115,7 +117,7 @@ public class SyncParameterTests { } @Test - public void testSyncBadSyncUnpairedTimeout() throws ParameterException { + void testSyncBadSyncUnpairedTimeout() { final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsUnpairedTimeout.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -133,17 +135,17 @@ public class SyncParameterTests { } @Test - public void testSyncGoodSyncGoodTimeoutProducer() throws ParameterException { + void testSyncGoodSyncGoodTimeoutProducer() throws ParameterException { verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsProducerTimeout.json"); } @Test - public void testSyncGoodSyncGoodTimeoutConsumer() throws ParameterException { + void testSyncGoodSyncGoodTimeoutConsumer() throws ParameterException { verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsConsumerTimeout.json"); } @Test - public void testSyncGoodSyncGoodTimeoutBoth() throws ParameterException { + void testSyncGoodSyncGoodTimeoutBoth() throws ParameterException { verifySyncGoodSyncGoodTimeout("src/test/resources/parameters/syncGoodParamsBothTimeout.json"); } @@ -152,18 +154,18 @@ public class SyncParameterTests { final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); final ApexParameters parameters = new ApexParameterHandler().getParameters(arguments); - assertEquals(fileName, 12345, parameters.getEventInputParameters().get("SyncConsumer0") - .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); - assertEquals(fileName, 1, parameters.getEventInputParameters().get("SyncConsumer1") - .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); - assertEquals(fileName, 12345, parameters.getEventOutputParameters().get("SyncProducer0") - .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); - assertEquals(fileName, 1, parameters.getEventOutputParameters().get("SyncProducer1") - .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + assertEquals(12345, parameters.getEventInputParameters().get("SyncConsumer0") + .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + assertEquals(1, parameters.getEventInputParameters().get("SyncConsumer1") + .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + assertEquals(12345, parameters.getEventOutputParameters().get("SyncProducer0") + .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); + assertEquals(1, parameters.getEventOutputParameters().get("SyncProducer1") + .getPeerTimeout(EventHandlerPeeredMode.SYNCHRONOUS)); } @Test - public void testSyncUnusedConsumerPeers() throws ParameterException { + void testSyncUnusedConsumerPeers() { final String[] args = {"-p", "src/test/resources/parameters/syncUnusedConsumerPeers.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -177,7 +179,7 @@ public class SyncParameterTests { } @Test - public void testSyncMismatchedPeers() throws ParameterException { + void testSyncMismatchedPeers() { final String[] args = {"-p", "src/test/resources/parameters/syncMismatchedPeers.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -195,7 +197,7 @@ public class SyncParameterTests { } @Test - public void testSyncUnusedProducerPeers() throws ParameterException { + void testSyncUnusedProducerPeers() { final String[] args = {"-p", "src/test/resources/parameters/syncUnusedProducerPeers.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -209,7 +211,7 @@ public class SyncParameterTests { } @Test - public void testSyncMismatchedTimeout() throws ParameterException { + void testSyncMismatchedTimeout() { final String[] args = {"-p", "src/test/resources/parameters/syncMismatchedTimeout.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -223,7 +225,7 @@ public class SyncParameterTests { } @Test - public void testSyncGoodParametersTest() throws ParameterException { + void testSyncGoodParametersTest() throws ParameterException { final String[] args = {"-p", "src/test/resources/parameters/syncGoodParams.json"}; final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args); @@ -236,21 +238,21 @@ public class SyncParameterTests { assertEquals(65522, parameters.getEngineServiceParameters().getDeploymentPort()); final CarrierTechnologyParameters prodCT0 = - parameters.getEventOutputParameters().get("SyncProducer0").getCarrierTechnologyParameters(); + parameters.getEventOutputParameters().get("SyncProducer0").getCarrierTechnologyParameters(); final EventProtocolParameters prodEP0 = - parameters.getEventOutputParameters().get("SyncProducer0").getEventProtocolParameters(); + parameters.getEventOutputParameters().get("SyncProducer0").getEventProtocolParameters(); final CarrierTechnologyParameters consCT0 = - parameters.getEventInputParameters().get("SyncConsumer0").getCarrierTechnologyParameters(); + parameters.getEventInputParameters().get("SyncConsumer0").getCarrierTechnologyParameters(); final EventProtocolParameters consEP0 = - parameters.getEventInputParameters().get("SyncConsumer0").getEventProtocolParameters(); + parameters.getEventInputParameters().get("SyncConsumer0").getEventProtocolParameters(); final CarrierTechnologyParameters prodCT1 = - parameters.getEventOutputParameters().get("SyncProducer1").getCarrierTechnologyParameters(); + parameters.getEventOutputParameters().get("SyncProducer1").getCarrierTechnologyParameters(); final EventProtocolParameters prodEP1 = - parameters.getEventOutputParameters().get("SyncProducer1").getEventProtocolParameters(); + parameters.getEventOutputParameters().get("SyncProducer1").getEventProtocolParameters(); final CarrierTechnologyParameters consCT1 = - parameters.getEventInputParameters().get("SyncConsumer1").getCarrierTechnologyParameters(); + parameters.getEventInputParameters().get("SyncConsumer1").getCarrierTechnologyParameters(); final EventProtocolParameters consEP1 = - parameters.getEventInputParameters().get("SyncConsumer1").getEventProtocolParameters(); + parameters.getEventInputParameters().get("SyncConsumer1").getEventProtocolParameters(); assertEquals("FILE", prodCT0.getLabel()); assertEquals("JSON", prodEP0.getLabel()); @@ -261,11 +263,18 @@ public class SyncParameterTests { assertEquals("SUPER_DOOPER", consCT1.getLabel()); assertEquals("SUPER_TOK_DEL", consEP1.getLabel()); - assertTrue(consCT1 instanceof SuperDooperCarrierTechnologyParameters); - assertTrue(consEP1 instanceof SuperTokenDelimitedEventProtocolParameters); + assertInstanceOf(SuperDooperCarrierTechnologyParameters.class, consCT1); + assertInstanceOf(SuperTokenDelimitedEventProtocolParameters.class, consEP1); final SuperDooperCarrierTechnologyParameters superDooperParameters = - (SuperDooperCarrierTechnologyParameters) consCT1; + (SuperDooperCarrierTechnologyParameters) consCT1; + assertEqualsOnFields(superDooperParameters); + + final String[] consumerTopics = {"apex-in"}; + assertEquals(Arrays.asList(consumerTopics), superDooperParameters.getConsumerTopicList()); + } + + private static void assertEqualsOnFields(SuperDooperCarrierTechnologyParameters superDooperParameters) { assertEquals("localhost:9092", superDooperParameters.getBootstrapServers()); assertEquals("all", superDooperParameters.getAcks()); assertEquals(0, superDooperParameters.getRetries()); @@ -279,15 +288,12 @@ public class SyncParameterTests { assertEquals("apex-out", superDooperParameters.getProducerTopic()); assertEquals(100, superDooperParameters.getConsumerPollTime()); assertEquals("org.apache.superDooper.common.serialization.StringSerializer", - superDooperParameters.getKeySerializer()); + superDooperParameters.getKeySerializer()); assertEquals("org.apache.superDooper.common.serialization.StringSerializer", - superDooperParameters.getValueSerializer()); + superDooperParameters.getValueSerializer()); assertEquals("org.apache.superDooper.common.serialization.StringDeserializer", - superDooperParameters.getKeyDeserializer()); + superDooperParameters.getKeyDeserializer()); assertEquals("org.apache.superDooper.common.serialization.StringDeserializer", - superDooperParameters.getValueDeserializer()); - - final String[] consumerTopics = {"apex-in"}; - assertEquals(Arrays.asList(consumerTopics), superDooperParameters.getConsumerTopicList()); + superDooperParameters.getValueDeserializer()); } } diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImplTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImplTest.java index a903a885e..caba093ce 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImplTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineServiceImplTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020-2022 Nordix Foundation. + * Modifications Copyright (C) 2020-2022, 2024 Nordix Foundation. * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -24,17 +24,18 @@ package org.onap.policy.apex.service.engine.runtime.impl; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.IOException; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.ContextParameters; import org.onap.policy.apex.context.parameters.DistributorParameters; @@ -59,7 +60,7 @@ import org.onap.policy.common.utils.resources.TextFileUtils; /** * Test the engine service implementation. */ -public class EngineServiceImplTest { +class EngineServiceImplTest { private static String simpleModelString; private static String differentModelString; @@ -71,8 +72,8 @@ public class EngineServiceImplTest { * @throws IOException on model reading errors * @throws ApexModelException on model reading exceptions */ - @BeforeClass - public static void readSimpleModel() throws IOException, ApexModelException { + @BeforeAll + static void readSimpleModel() throws IOException, ApexModelException { simpleModelString = TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json"); differentModelString = @@ -85,8 +86,8 @@ public class EngineServiceImplTest { /** * Initialize default parameters. */ - @BeforeClass - public static void initializeDefaultParameters() { + @BeforeAll + static void initializeDefaultParameters() { ParameterService.clear(); final SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); @@ -110,30 +111,29 @@ public class EngineServiceImplTest { final EngineParameters engineParameters = new EngineParameters(); engineParameters.setName(EngineParameterConstants.MAIN_GROUP_NAME); + ExecutorParameters jsExecutorParameters = getExecutorParameters("JAVASCRIPT"); + engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters); + getExecutorParameters("MVEL"); + engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters); + ParameterService.register(engineParameters); + } + + private static @NotNull ExecutorParameters getExecutorParameters(String lang) { ExecutorParameters jsExecutorParameters = new ExecutorParameters(); - jsExecutorParameters.setName("JAVASCRIPT"); + jsExecutorParameters.setName(lang); jsExecutorParameters .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse"); jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe"); jsExecutorParameters .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe"); - engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters); - ExecutorParameters mvvelExecutorParameters = new ExecutorParameters(); - mvvelExecutorParameters.setName("MVEL"); - mvvelExecutorParameters - .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse"); - mvvelExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe"); - mvvelExecutorParameters - .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe"); - engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters); - ParameterService.register(engineParameters); + return jsExecutorParameters; } /** * Teardown default parameters. */ - @AfterClass - public static void teardownDefaultParameters() { + @AfterAll + static void teardownDefaultParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); @@ -154,9 +154,9 @@ public class EngineServiceImplTest { } @Test - public void testEngineServiceImplSanity() throws ApexException { + void testEngineServiceImplSanity() throws ApexException { assertThatThrownBy(() -> EngineServiceImpl.create(null)).isInstanceOf(ApexException.class) - .hasMessage("engine service configuration parameters are null"); + .hasMessage("Engine service configuration parameters are null"); EngineServiceParameters invalidConfig = new EngineServiceParameters(); invalidConfig.setInstanceCount(0); @@ -212,7 +212,7 @@ public class EngineServiceImplTest { } @Test - public void testEngineServiceExceptions() throws ApexException { + void testEngineServiceExceptions() throws ApexException { EngineServiceParameters config = makeConfig(); EngineServiceImpl esImpl = EngineServiceImpl.create(config); assertThatThrownBy(() -> esImpl.start(null)).isInstanceOf(ApexException.class) @@ -225,7 +225,7 @@ public class EngineServiceImplTest { .isInstanceOf(ApexException.class).hasMessage("start()<-Engine-0:0.0.1,STOPPED, cannot start engine, " + "engine has not been initialized, its model is not loaded"); - assertThatThrownBy(() -> esImpl.startAll()).isInstanceOf(ApexException.class) + assertThatThrownBy(esImpl::startAll).isInstanceOf(ApexException.class) .hasMessage("start()<-Engine-0:0.0.1,STOPPED, cannot start engine, " + "engine has not been initialized, its model is not loaded"); @@ -244,13 +244,13 @@ public class EngineServiceImplTest { esImpl.startPeriodicEvents(100000); assertThatThrownBy(() -> esImpl.startPeriodicEvents(100000)).isInstanceOf(ApexException.class) - .hasMessage("Periodic event geneation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator " + .hasMessage("Periodic event generation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator " + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]"); esImpl.stopPeriodicEvents(); - assertThatThrownBy(() -> esImpl.stopPeriodicEvents()).isInstanceOf(ApexException.class) - .hasMessage("Periodic event geneation not running on engine Engine:0.0.1"); + assertThatThrownBy(esImpl::stopPeriodicEvents).isInstanceOf(ApexException.class) + .hasMessage("Periodic event generation not running on engine Engine:0.0.1"); assertThatThrownBy(() -> esImpl.clear(null)).isInstanceOf(ApexException.class) .hasMessage("engine key must be specified and may not be null"); @@ -296,7 +296,7 @@ public class EngineServiceImplTest { } @Test - public void testApexImplModelWIthModel() throws ApexException { + void testApexImplModelWIthModel() throws ApexException { EngineServiceParameters config = makeConfig(); EngineServiceImpl esImpl = EngineServiceImpl.create(config); assertEquals("Engine:0.0.1", esImpl.getKey().getId()); @@ -387,6 +387,10 @@ public class EngineServiceImplTest { fail("test should not throw an exception"); } + assertPeriodicEvents(esImpl); + } + + private static void assertPeriodicEvents(EngineServiceImpl esImpl) throws ApexException { esImpl.startPeriodicEvents(100000); esImpl.stop(); esImpl.startAll(); @@ -397,7 +401,7 @@ public class EngineServiceImplTest { esImpl.startPeriodicEvents(100000); fail("test should throw an exception"); } catch (ApexException apEx) { - assertEquals("Periodic event geneation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator " + assertEquals("Periodic event generation already running on engine Engine:0.0.1, ApexPeriodicEventGenerator " + "[period=100000, firstEventTime=0, lastEventTime=0, eventCount=0]", apEx.getMessage()); } @@ -406,7 +410,7 @@ public class EngineServiceImplTest { esImpl.stopPeriodicEvents(); fail("test should throw an exception"); } catch (ApexException apEx) { - assertEquals("Periodic event geneation not running on engine Engine:0.0.1", apEx.getMessage()); + assertEquals("Periodic event generation not running on engine Engine:0.0.1", apEx.getMessage()); } try { diff --git a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorkerTest.java b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorkerTest.java index b23b3d4e6..0716e0ad3 100644 --- a/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorkerTest.java +++ b/services/services-engine/src/test/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorkerTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020,2022 Nordix Foundation. + * Modifications Copyright (C) 2020, 2022-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,21 +22,23 @@ package org.onap.policy.apex.service.engine.runtime.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.ContextParameters; import org.onap.policy.apex.context.parameters.DistributorParameters; @@ -63,7 +65,7 @@ import org.onap.policy.common.utils.services.Registry; /** * Test the engine worker class. */ -public class EngineWorkerTest { +class EngineWorkerTest { private final ApplicationThreadFactory atFactory = new ApplicationThreadFactory("apex-engine-service", 512); private static String simpleModelString; @@ -73,15 +75,15 @@ public class EngineWorkerTest { /** * Read the models into strings. * - * @throws IOException on model reading errors + * @throws IOException on model reading errors * @throws ApexModelException on model reading exceptions */ - @BeforeClass - public static void readSimpleModel() throws IOException, ApexModelException { + @BeforeAll + static void readSimpleModel() throws IOException, ApexModelException { simpleModelString = TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModel.json"); differentModelString = - TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json"); + TextFileUtils.getTextFileAsString("src/test/resources/policymodels/SmallModelDifferent.json"); final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); simpleModel = modelReader.read(new ByteArrayInputStream(simpleModelString.getBytes())); @@ -90,8 +92,8 @@ public class EngineWorkerTest { /** * Initialize default parameters. */ - @BeforeClass - public static void initializeDefaultParameters() { + @BeforeAll + static void initializeDefaultParameters() { ParameterService.clear(); final SchemaParameters schemaParameters = new SchemaParameters(); schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); @@ -115,31 +117,30 @@ public class EngineWorkerTest { final EngineParameters engineParameters = new EngineParameters(); engineParameters.setName(EngineParameterConstants.MAIN_GROUP_NAME); - ExecutorParameters jsExecutorParameters = new ExecutorParameters(); - jsExecutorParameters.setName("JAVASCRIPT"); - jsExecutorParameters - .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse"); - jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe"); - jsExecutorParameters - .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe"); + ExecutorParameters jsExecutorParameters = getExecutorParameters("JAVASCRIPT"); engineParameters.getExecutorParameterMap().put("JAVASCRIPT", jsExecutorParameters); - ExecutorParameters mvvelExecutorParameters = new ExecutorParameters(); - mvvelExecutorParameters.setName("MVEL"); - mvvelExecutorParameters - .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse"); - mvvelExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe"); - mvvelExecutorParameters - .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe"); + getExecutorParameters("MVEL"); engineParameters.getExecutorParameterMap().put("MVEL", jsExecutorParameters); ParameterService.register(engineParameters); } + private static @NotNull ExecutorParameters getExecutorParameters(String lang) { + ExecutorParameters jsExecutorParameters = new ExecutorParameters(); + jsExecutorParameters.setName(lang); + jsExecutorParameters + .setTaskSelectionExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTse"); + jsExecutorParameters.setTaskExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummyTe"); + jsExecutorParameters + .setStateFinalizerExecutorPluginClass("org.onap.policy.apex.service.engine.runtime.impl.DummySfe"); + return jsExecutorParameters; + } + /** * Teardown default parameters. */ - @AfterClass - public static void teardownDefaultParameters() { + @AfterAll + static void teardownDefaultParameters() { ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME); ParameterService.deregister(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); ParameterService.deregister(ContextParameterConstants.LOCKING_GROUP_NAME); @@ -148,192 +149,59 @@ public class EngineWorkerTest { ParameterService.deregister(EngineParameterConstants.MAIN_GROUP_NAME); } - @After - public void cleardownTest() { + @AfterEach + void clearDownTest() { ModelService.clear(); } @Test - public void testEngineWorker() { + void testEngineWorker() { BlockingQueue<ApexEvent> eventQueue = new LinkedBlockingQueue<>(); EngineWorker worker = new EngineWorker(new AxArtifactKey("Worker", "0.0.1"), eventQueue, atFactory); - try { - worker.registerActionListener(null, null); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage()); - } + assertThatThrownBy(() -> worker.registerActionListener(null, null)) + .hasMessageContaining("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null"); worker.registerActionListener("DummyListener", null); - try { - worker.registerActionListener(null, new DummyApexEventListener()); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage()); - } + assertThatThrownBy(() -> worker.registerActionListener(null, new DummyApexEventListener())) + .hasMessageContaining("addEventListener()<-Worker:0.0.1,STOPPED, listenerName is null"); worker.registerActionListener("DummyListener", new DummyApexEventListener()); - try { - worker.deregisterActionListener(null); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("removeEventListener()<-Worker:0.0.1,STOPPED, listenerName is null", apEx.getMessage()); - } + assertThatThrownBy(() -> worker.deregisterActionListener(null)) + .hasMessageContaining("removeEventListener()<-Worker:0.0.1,STOPPED, listenerName is null"); worker.deregisterActionListener("DummyListener"); - try { - worker.getEngineServiceEventInterface(); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker", - apEx.getMessage()); - } - - try { - worker.startPeriodicEvents(100000); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("startPeriodicEvents() call is not allowed on an Apex Engine Worker", apEx.getMessage()); - } - - try { - worker.stopPeriodicEvents(); - fail("test should throw an exception"); - } catch (Exception apEx) { - assertEquals("stopPeriodicEvents() call is not allowed on an Apex Engine Worker", apEx.getMessage()); - } + assertThatThrownBy(worker::getEngineServiceEventInterface) + .hasMessageContaining("getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker"); + + assertThatThrownBy(() -> worker.startPeriodicEvents(100000)) + .hasMessageContaining("startPeriodicEvents() call is not allowed on an Apex Engine Worker"); + + assertThatThrownBy(worker::stopPeriodicEvents) + .hasMessageContaining("stopPeriodicEvents() call is not allowed on an Apex Engine Worker"); assertEquals("Worker:0.0.1", worker.getEngineKeys().iterator().next().getId()); assertNull(worker.getApexModelKey()); - String runtimeInfo = worker.getRuntimeInfo(worker.getEngineKeys().iterator().next()); - assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13)); + assertEngineWorkerStartStop(worker); - assertEquals(AxEngineState.STOPPED, worker.getState()); + assertThatThrownBy(() -> worker.clear(new AxArtifactKey("DummyKey", "0.0.1"))) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); - assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13)); + assertDoesNotThrow(() -> worker.clear(worker.getEngineKeys().iterator().next())); + assertDoesNotThrow(() -> worker.clear()); - assertFalse(worker.isStarted()); - assertFalse(worker.isStarted(null)); - assertFalse(worker.isStarted(new AxArtifactKey("DummyKey", "0.0.1"))); - assertFalse(worker.isStarted(worker.getEngineKeys().iterator().next())); - assertTrue(worker.isStopped()); - assertTrue(worker.isStopped(null)); - assertTrue(worker.isStopped(new AxArtifactKey("DummyKey", "0.0.1"))); - assertTrue(worker.isStopped(worker.getEngineKeys().iterator().next())); - - try { - worker.start(new AxArtifactKey("DummyKey", "0.0.1")); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } - - try { - worker.start(worker.getEngineKeys().iterator().next()); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("start()<-Worker:0.0.1,STOPPED, cannot start engine, engine has not been initialized, " - + "its model is not loaded", apEx.getMessage()); - } - - try { - worker.startAll(); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("start()<-Worker:0.0.1,STOPPED, cannot start engine, " - + "engine has not been initialized, its model is not loaded", apEx.getMessage()); - } - - try { - worker.stop(new AxArtifactKey("DummyKey", "0.0.1")); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } - - try { - worker.stop(worker.getEngineKeys().iterator().next()); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.stop(); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.clear(new AxArtifactKey("DummyKey", "0.0.1")); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } - - try { - worker.clear(worker.getEngineKeys().iterator().next()); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.clear(); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "", true); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("failed to unmarshal the apex model on engine DummyKey:0.0.1", apEx.getMessage()); - } - - try { - worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "I am not an Apex model", true); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("failed to unmarshal the apex model on engine DummyKey:0.0.1", apEx.getMessage()); - } - - try { - worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModelString, true); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } - - try { - worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), (AxPolicyModel) null, true); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } - - try { - worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModel, true); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine", - apEx.getMessage()); - } + assertUpdateEngineModel(worker); } @Test - public void testApexImplModelWIthModel() throws ApexException { + void testApexImplModelWIthModel() throws ApexException { Registry.newRegistry(); Registry.register(ApexPolicyStatisticsManager.REG_APEX_PDP_POLICY_COUNTER, new ApexPolicyStatisticsManager()); BlockingQueue<ApexEvent> eventQueue = new LinkedBlockingQueue<>(); @@ -341,34 +209,18 @@ public class EngineWorkerTest { EngineWorker worker = new EngineWorker(new AxArtifactKey("Worker", "0.0.1"), eventQueue, atFactory); assertEquals("Worker:0.0.1", worker.getKey().getId()); - try { - worker.updateModel(worker.getKey(), simpleModelString, false); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } + assertDoesNotThrow(() -> worker.updateModel(worker.getKey(), simpleModelString, false)); eventQueue.add(new ApexEvent("SomeEvent", "0.0.1", "the.event.namespace", "EventSource", "EventTarget", "")); - try { - worker.updateModel(worker.getKey(), differentModelString, false); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("apex model update failed, supplied model with key \"SmallModelDifferent:0.0.1\" is not a " - + "compatible model update " + "from the existing engine model with key \"SmallModel:0.0.1\"", - apEx.getMessage()); - } - - try { - worker.updateModel(worker.getKey(), differentModelString, true); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.updateModel(worker.getKey(), simpleModelString, true); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> worker.updateModel(worker.getKey(), differentModelString, false)) + .hasMessageContaining("apex model update failed, supplied model with key " + + "\"SmallModelDifferent:0.0.1\" is not a compatible model update " + + "from the existing engine model with key \"SmallModel:0.0.1\""); + + assertDoesNotThrow(() -> worker.updateModel(worker.getKey(), differentModelString, true)); + + assertDoesNotThrow(() -> worker.updateModel(worker.getKey(), simpleModelString, true)); String runtimeInfo = worker.getRuntimeInfo(worker.getEngineKeys().iterator().next()); assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13)); @@ -379,6 +231,7 @@ public class EngineWorkerTest { assertEquals(AxEngineState.READY, worker.getState()); String status = worker.getStatus(worker.getEngineKeys().iterator().next()); + assertNotNull(status); assertEquals("{\"timestamp\":", status.replaceAll("\\s+", "").substring(0, 13)); assertTrue(worker.isStarted()); @@ -386,74 +239,92 @@ public class EngineWorkerTest { assertFalse(worker.isStopped()); assertFalse(worker.isStopped(worker.getEngineKeys().iterator().next())); - try { - worker.start(worker.getEngineKeys().iterator().next()); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY", - apEx.getMessage()); - } - - try { - worker.startAll(); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("apex engine for engine key Worker:0.0.1 is already running with state READY", - apEx.getMessage()); - } - - try { - worker.stop(worker.getEngineKeys().iterator().next()); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.start(worker.getEngineKeys().iterator().next()); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.stop(); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.startAll(); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } + assertWorkerStartStopWithModel(worker); + } + + private static void assertUpdateEngineModel(EngineWorker worker) { + assertThatThrownBy(() -> worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "", true)) + .hasMessageContaining("failed to unmarshal the apex model on engine DummyKey:0.0.1"); + + assertThatThrownBy( + () -> worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), "I am not an Apex model", true)) + .hasMessageContaining("failed to unmarshal the apex model on engine DummyKey:0.0.1"); + + assertThatThrownBy(() -> worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModelString, true)) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); + + assertThatThrownBy( + () -> worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), (AxPolicyModel) null, true)) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); + + assertThatThrownBy(() -> worker.updateModel(new AxArtifactKey("DummyKey", "0.0.1"), simpleModel, true)) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); + } + + private static void assertEngineWorkerStartStop(EngineWorker worker) { + String runtimeInfo = worker.getRuntimeInfo(worker.getEngineKeys().iterator().next()); + assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13)); + + assertEquals(AxEngineState.STOPPED, worker.getState()); + + assertEquals("{\"TimeStamp\":", runtimeInfo.replaceAll("\\s+", "").substring(0, 13)); + + assertFalse(worker.isStarted()); + assertFalse(worker.isStarted(null)); + assertFalse(worker.isStarted(new AxArtifactKey("DummyKey", "0.0.1"))); + assertFalse(worker.isStarted(worker.getEngineKeys().iterator().next())); + assertTrue(worker.isStopped()); + assertTrue(worker.isStopped(null)); + assertTrue(worker.isStopped(new AxArtifactKey("DummyKey", "0.0.1"))); + assertTrue(worker.isStopped(worker.getEngineKeys().iterator().next())); + + assertThatThrownBy(() -> worker.start(new AxArtifactKey("DummyKey", "0.0.1"))) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); + + assertThatThrownBy(() -> worker.start(worker.getEngineKeys().iterator().next())) + .hasMessageContaining( + "start()<-Worker:0.0.1,STOPPED, cannot start engine, engine has not been initialized, " + + "its model is not loaded"); + + assertThatThrownBy(worker::startAll).hasMessageContaining( + "start()<-Worker:0.0.1,STOPPED, cannot start engine, engine has not been initialized, its " + + "model is not loaded"); + + assertThatThrownBy(() -> worker.stop(new AxArtifactKey("DummyKey", "0.0.1"))) + .hasMessageContaining("engine key DummyKey:0.0.1 does not match the keyWorker:0.0.1 of this engine"); + + assertDoesNotThrow(() -> worker.stop(worker.getEngineKeys().iterator().next())); + + assertDoesNotThrow(() -> worker.stop()); + } + + private static void assertWorkerStartStopWithModel(EngineWorker worker) throws ApexException { + assertThatThrownBy(() -> worker.start(worker.getEngineKeys().iterator().next())) + .hasMessageContaining("apex engine for engine key Worker:0.0.1 is already running with state READY"); + + assertThatThrownBy(worker::startAll) + .hasMessageContaining("apex engine for engine key Worker:0.0.1 is already running with state READY"); + + assertDoesNotThrow(() -> worker.stop(worker.getEngineKeys().iterator().next())); + assertDoesNotThrow(() -> worker.start(worker.getEngineKeys().iterator().next())); + assertDoesNotThrow(() -> worker.stop()); + assertDoesNotThrow(worker::startAll); worker.stop(); worker.startAll(); - try { - worker.clear(worker.getEngineKeys().iterator().next()); - fail("test should throw an exception"); - } catch (ApexException apEx) { - assertEquals("clear()<-Worker:0.0.1,READY, cannot clear engine, engine is not stopped", apEx.getMessage()); - } - - try { - worker.stop(worker.getEngineKeys().iterator().next()); - worker.clear(worker.getEngineKeys().iterator().next()); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } - - try { - worker.clear(); - } catch (ApexException apEx) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> worker.clear(worker.getEngineKeys().iterator().next())) + .hasMessageContaining("clear()<-Worker:0.0.1,READY, cannot clear engine, engine is not stopped"); + + assertDoesNotThrow(() -> worker.stop(worker.getEngineKeys().iterator().next())); + assertDoesNotThrow(() -> worker.clear(worker.getEngineKeys().iterator().next())); + assertDoesNotThrow(() -> worker.clear()); assertNotNull(worker.getApexModelKey()); final ApexPolicyStatisticsManager policyCounter = ApexPolicyStatisticsManager.getInstanceFromRegistry(); assertNotNull(policyCounter); assertEquals(policyCounter.getPolicyExecutedCount(), - policyCounter.getPolicyExecutedFailCount() + policyCounter.getPolicyExecutedSuccessCount()); + policyCounter.getPolicyExecutedFailCount() + policyCounter.getPolicyExecutedSuccessCount()); } } diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java index 2030b3b65..49bde831f 100644 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -74,7 +74,7 @@ public class ApexEngineHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class); - private Map<ToscaConceptIdentifier, ApexMain> apexMainMap = new LinkedHashMap<>(); + private final Map<ToscaConceptIdentifier, ApexMain> apexMainMap = new LinkedHashMap<>(); /** * Constructs the object. Extracts the config and model files from each policy and instantiates the apex engine. @@ -95,12 +95,13 @@ public class ApexEngineHandler { * @param polsToUndeploy list of policies to undeploy which will be modified to remove policies not running * @throws ApexStarterException if the apex engine instantiation failed using the policies passed */ - public void updateApexEngine(List<ToscaPolicy> polsToDeploy, List<ToscaConceptIdentifier> polsToUndeploy) + public void updateApexEngine(final List<ToscaPolicy> polsToDeploy, + final List<ToscaConceptIdentifier> polsToUndeploy) throws ApexStarterException { Set<ToscaConceptIdentifier> runningPolicies = new HashSet<>(getRunningPolicies()); - List<ToscaPolicy> policiesToDeploy = polsToDeploy; + List<ToscaPolicy> policiesToDeploy = new ArrayList<>(polsToDeploy); policiesToDeploy.removeIf(p -> runningPolicies.contains(p.getIdentifier())); - List<ToscaConceptIdentifier> policiesToUnDeploy = polsToUndeploy; + List<ToscaConceptIdentifier> policiesToUnDeploy = new ArrayList<>(polsToUndeploy); policiesToUnDeploy.removeIf(p -> !runningPolicies.contains(p)); Map<ToscaConceptIdentifier, ApexMain> undeployedPoliciesMainMap = new LinkedHashMap<>(); policiesToUnDeploy.forEach(policyId -> { @@ -179,19 +180,19 @@ public class ApexEngineHandler { List<String> schemaParamKeysToRetain, ApexMain main) { ApexParameters existingParameters = ParameterService.get(ApexParameterConstants.MAIN_GROUP_NAME); List<String> eventInputParamKeysToRemove = main.getApexParameters().getEventInputParameters().keySet().stream() - .filter(key -> !inputParamKeysToRetain.contains(key)).collect(Collectors.toList()); + .filter(key -> !inputParamKeysToRetain.contains(key)).toList(); List<String> eventOutputParamKeysToRemove = main.getApexParameters().getEventOutputParameters().keySet() - .stream().filter(key -> !outputParamKeysToRetain.contains(key)).collect(Collectors.toList()); + .stream().filter(key -> !outputParamKeysToRetain.contains(key)).toList(); eventInputParamKeysToRemove.forEach(existingParameters.getEventInputParameters()::remove); eventOutputParamKeysToRemove.forEach(existingParameters.getEventOutputParameters()::remove); var engineParameters = main.getApexParameters().getEngineServiceParameters().getEngineParameters(); final List<TaskParameters> taskParametersToRemove = engineParameters.getTaskParameters().stream() - .filter(taskParameter -> !taskParametersToRetain.contains(taskParameter)).collect(Collectors.toList()); + .filter(taskParameter -> !taskParametersToRetain.contains(taskParameter)).toList(); final List<String> executorParamKeysToRemove = engineParameters.getExecutorParameterMap().keySet().stream() - .filter(key -> !executorParamKeysToRetain.contains(key)).collect(Collectors.toList()); + .filter(key -> !executorParamKeysToRetain.contains(key)).toList(); final List<String> schemaParamKeysToRemove = engineParameters.getContextParameters().getSchemaParameters().getSchemaHelperParameterMap().keySet() - .stream().filter(key -> !schemaParamKeysToRetain.contains(key)).collect(Collectors.toList()); + .stream().filter(key -> !schemaParamKeysToRetain.contains(key)).toList(); var aggregatedEngineParameters = existingParameters.getEngineServiceParameters().getEngineParameters(); aggregatedEngineParameters.getTaskParameters().removeAll(taskParametersToRemove); executorParamKeysToRemove.forEach(aggregatedEngineParameters.getExecutorParameterMap()::remove); @@ -205,17 +206,17 @@ public class ApexEngineHandler { Map<AxArtifactKey, AxPolicy> policyMapToRetain, ApexMain main) { final AxPolicyModel policyModel = main.getActivator().getPolicyModel(); final List<AxArtifactKey> keyInfoKeystoRemove = policyModel.getKeyInformation().getKeyInfoMap().keySet() - .stream().filter(key -> !keyInfoMapToRetain.containsKey(key)).collect(Collectors.toList()); + .stream().filter(key -> !keyInfoMapToRetain.containsKey(key)).toList(); final List<AxArtifactKey> schemaKeystoRemove = policyModel.getSchemas().getSchemasMap().keySet().stream() - .filter(key -> !schemaMapToRetain.containsKey(key)).collect(Collectors.toList()); + .filter(key -> !schemaMapToRetain.containsKey(key)).toList(); final List<AxArtifactKey> eventKeystoRemove = policyModel.getEvents().getEventMap().keySet().stream() - .filter(key -> !eventMapToRetain.containsKey(key)).collect(Collectors.toList()); + .filter(key -> !eventMapToRetain.containsKey(key)).toList(); final List<AxArtifactKey> albumKeystoRemove = policyModel.getAlbums().getAlbumsMap().keySet().stream() - .filter(key -> !albumMapToRetain.containsKey(key)).collect(Collectors.toList()); + .filter(key -> !albumMapToRetain.containsKey(key)).toList(); final List<AxArtifactKey> taskKeystoRemove = policyModel.getTasks().getTaskMap().keySet().stream() - .filter(key -> !taskMapToRetain.containsKey(key)).collect(Collectors.toList()); + .filter(key -> !taskMapToRetain.containsKey(key)).toList(); final List<AxArtifactKey> policyKeystoRemove = policyModel.getPolicies().getPolicyMap().keySet().stream() - .filter(key -> !policyMapToRetain.containsKey(key)).collect(Collectors.toList()); + .filter(key -> !policyMapToRetain.containsKey(key)).toList(); final Map<AxArtifactKey, AxKeyInfo> keyInfoMap = ModelService.getModel(AxKeyInformation.class).getKeyInfoMap(); final Map<AxArtifactKey, AxContextSchema> schemasMap = @@ -274,7 +275,7 @@ public class ApexEngineHandler { ModelService.clear(); ParameterService.clear(); throw new ApexStarterException("Apex Engine failed to start."); - } else if (failedPoliciesMainMap.size() > 0) { + } else if (!failedPoliciesMainMap.isEmpty()) { updateModelAndParameterServices(failedPoliciesMainMap); if (failedPoliciesMainMap.size() == policies.size()) { throw new ApexStarterException("Updating the APEX engine with new policies failed."); diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java index 328bb3003..d3f428174 100644 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2023 Bell Canada. All rights reserved. * ================================================================================ @@ -122,8 +122,8 @@ public class PdpMessageHandler { * * @return PdpResponseDetails */ - public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status, - final String responseMessage) { + public PdpResponseDetails createPdpResponseDetails(final String requestId, final PdpResponseStatus status, + final String responseMessage) { final var pdpResponseDetails = new PdpResponseDetails(); pdpResponseDetails.setResponseTo(requestId); pdpResponseDetails.setResponseStatus(status); diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java index af3e93b6a..4d3de3293 100644 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ @@ -93,13 +93,13 @@ public class PdpStateChangeMessageHandler { final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { PdpResponseDetails pdpResponseDetails = null; if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Pdp already in active state"); } else { final List<ToscaPolicy> policies = Registry.get(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST); if (policies.isEmpty()) { pdpStatusContext.setState(PdpState.ACTIVE); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, "State changed to active. No policies found."); } else { pdpResponseDetails = startApexEngine(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler, policies); @@ -130,7 +130,7 @@ public class PdpStateChangeMessageHandler { if (new HashSet<>(runningPolicies) .equals(new HashSet<>(pdpMessageHandler.getToscaPolicyIdentifiers(policies)))) { pdpResponseDetails = - pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Apex engine started. State changed to active."); } else { var message = new StringBuilder( @@ -139,18 +139,18 @@ public class PdpStateChangeMessageHandler { message.append(policy.getName()).append(":").append(policy.getVersion()).append(" "); } message.append(". Other policies failed execution. Please see the logs for more details."); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails( + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails( pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, message.toString()); } pdpStatusContext.setState(PdpState.ACTIVE); updateDeploymentCounts(runningPolicies, policies); } else { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.FAIL, "Apex engine failed to start. State cannot be changed to active."); } } catch (final ApexStarterException e) { LOGGER.error("Pdp State Change failed.", e); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); } return pdpResponseDetails; @@ -168,7 +168,7 @@ public class PdpStateChangeMessageHandler { final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { PdpResponseDetails pdpResponseDetails = null; if (pdpStatusContext.getState().equals(PdpState.PASSIVE)) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Pdp already in passive state"); } else { ApexEngineHandler apexEngineHandler = null; @@ -181,12 +181,12 @@ public class PdpStateChangeMessageHandler { if (null != apexEngineHandler && apexEngineHandler.isApexEngineRunning()) { apexEngineHandler.shutdown(); } - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Apex pdp state changed from Active to Passive."); pdpStatusContext.setState(PdpState.PASSIVE); } catch (final Exception e) { LOGGER.error("Stopping apex engine failed. State cannot be changed to Passive.", e); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpStateChangeMsg.getRequestId(), PdpResponseStatus.FAIL, "Stopping apex engine failed. State cannot be changed to Passive." + e.getMessage()); } @@ -206,7 +206,7 @@ public class PdpStateChangeMessageHandler { return; } var policiesToDeploy = policies.stream() - .map(ToscaWithTypeAndObjectProperties::getIdentifier).collect(Collectors.toList()); + .map(ToscaWithTypeAndObjectProperties::getIdentifier).toList(); var policiesSuccessfullyDeployed = new ArrayList<>(policiesToDeploy); policiesSuccessfullyDeployed.retainAll(runningPolicies); diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java index b8e361e1e..f6567f06e 100644 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -66,7 +66,7 @@ public class PdpUpdateMessageHandler { if (pdpUpdateMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), pdpStatusContext.getPdpSubgroup())) { if (checkIfAlreadyHandled(pdpUpdateMsg, pdpStatusContext)) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Pdp already updated"); } else { pdpResponseDetails = handlePdpUpdate(pdpUpdateMsg, pdpMessageHandler, pdpStatusContext); @@ -128,7 +128,7 @@ public class PdpUpdateMessageHandler { } } if (null == pdpResponseDetails) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Pdp update successful."); } return pdpResponseDetails; @@ -170,11 +170,11 @@ public class PdpUpdateMessageHandler { try { apexEngineHandler.shutdown(); runningPolicies = apexEngineHandler.getRunningPolicies(); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.SUCCESS, "Pdp update successful. No policies are running."); } catch (final ApexStarterException e) { LOGGER.error("Pdp update failed as the policies couldn't be undeployed.", e); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.FAIL, "Pdp update failed as the policies couldn't be undeployed."); } updateDeploymentCounts(runningPolicies, pdpUpdateMsg); @@ -200,12 +200,12 @@ public class PdpUpdateMessageHandler { populateResponseForEngineInitiation(pdpUpdateMsg, pdpMessageHandler, apexEngineHandler); runningPolicies = apexEngineHandler.getRunningPolicies(); } else { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.FAIL, "Apex engine failed to start."); } } catch (final ApexStarterException e) { LOGGER.error("Apex engine service running failed. ", e); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); } updateDeploymentCounts(runningPolicies, pdpUpdateMsg); @@ -234,7 +234,7 @@ public class PdpUpdateMessageHandler { message.append(policy.getName()).append(":").append(policy.getVersion()).append(" "); } } - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.SUCCESS, message.toString()); } else { var message = @@ -243,7 +243,7 @@ public class PdpUpdateMessageHandler { message.append(policy.getName()).append(":").append(policy.getVersion()).append(" "); } message.append(". Other policies failed execution. Please see the logs for more details."); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(), PdpResponseStatus.SUCCESS, message.toString()); } return pdpResponseDetails; diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java index 77ffa5317..793549b14 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java @@ -1,8 +1,7 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +22,15 @@ package org.onap.policy.apex.services.onappf; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.services.onappf.exception.ApexStarterException; import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; @@ -44,7 +43,7 @@ import org.onap.policy.models.pdp.concepts.PdpStatus; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestApexStarterActivator { +class TestApexStarterActivator { private ApexStarterActivator activator; @@ -53,12 +52,12 @@ public class TestApexStarterActivator { * * @throws Exception if an error occurs */ - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Registry.newRegistry(); - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParametersNoop.json"}; + final String[] apexStarterConfigParameters = {"-c", "src/test/resources/ApexStarterConfigParametersNoop.json"}; final ApexStarterCommandLineArguments arguments = - new ApexStarterCommandLineArguments(apexStarterConfigParameters); + new ApexStarterCommandLineArguments(apexStarterConfigParameters); final ApexStarterParameterGroup parGroup = new ApexStarterParameterHandler().getParameters(arguments); activator = new ApexStarterActivator(parGroup); } @@ -68,15 +67,15 @@ public class TestApexStarterActivator { * * @throws Exception if an error occurs */ - @After - public void teardown() throws Exception { + @AfterEach + void teardown() throws Exception { if (activator != null && activator.isAlive()) { activator.terminate(); } } @Test - public void testApexStarterActivator() throws ApexStarterException { + void testApexStarterActivator() throws ApexStarterException { assertFalse(activator.isAlive()); activator.initialize(); assertTrue(activator.isAlive()); @@ -93,7 +92,7 @@ public class TestApexStarterActivator { } @Test - public void testTerminate() throws Exception { + void testTerminate() throws Exception { activator.initialize(); activator.terminate(); assertFalse(activator.isAlive()); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterCommandLineArguments.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterCommandLineArguments.java index e564d38e4..c5ebd50ea 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterCommandLineArguments.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterCommandLineArguments.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. + * Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,11 @@ package org.onap.policy.apex.services.onappf; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TestApexStarterCommandLineArguments { +class TestApexStarterCommandLineArguments { /** * Test method for {@link org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments @@ -33,7 +33,7 @@ public class TestApexStarterCommandLineArguments { * Assert custom option was added to options object from super. */ @Test - public void testCommandLineHasPropertyFileOption() { + void testCommandLineHasPropertyFileOption() { String[] args = {"-p", "someFile.json"}; ApexStarterCommandLineArguments sut = new ApexStarterCommandLineArguments(args); assertEquals("someFile.json", sut.getPropertyFilePath()); @@ -44,7 +44,7 @@ public class TestApexStarterCommandLineArguments { * Assert method consults version.txt from Apex module. */ @Test - public void testVersion() { + void testVersion() { String[] args = {"-v"}; ApexStarterCommandLineArguments sut = new ApexStarterCommandLineArguments(args); assertThat(sut.version()).startsWith("ONAP Policy Framework Apex Starter Service"); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java index f1a2a089c..4c13b5709 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019,2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2020 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,16 +24,17 @@ package org.onap.policy.apex.services.onappf; import static org.assertj.core.api.Assertions.assertThatCode; import java.lang.reflect.Constructor; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Class to perform unit test of {@link ApexStarterConstants}}. * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestApexStarterConstants { +class TestApexStarterConstants { + @Test - public void test() throws Exception { + void test() { // verify that constructor does not throw an exception assertThatCode(() -> { Constructor<ApexStarterConstants> c = ApexStarterConstants.class.getDeclaredConstructor(); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java index f24329c29..e34a1cd04 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2020 Nordix Foundation. + * Copyright (C) 2019-2020, 2024 Nordix Foundation. * Modifications Copyright (C) 2020 Nordix Foundation * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. * ================================================================================ @@ -24,13 +24,13 @@ package org.onap.policy.apex.services.onappf; import static org.assertj.core.api.Assertions.assertThatCode; 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.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager; import org.onap.policy.apex.services.onappf.exception.ApexStarterException; import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException; @@ -39,18 +39,17 @@ import org.onap.policy.common.utils.resources.MessageConstants; import org.onap.policy.common.utils.services.Registry; /** - * Class to perform unit test of {@link ApexStarterMain}}. + * Class to perform unit test of {@link ApexStarterMain}. * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestApexStarterMain { - private ApexStarterMain apexStarter; +class TestApexStarterMain { /** * Set up. */ - @Before - public void setUp() { + @BeforeEach + void setUp() { Registry.newRegistry(); } @@ -59,8 +58,8 @@ public class TestApexStarterMain { * * @throws Exception if an error occurs */ - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { // shut down activator final ApexStarterActivator activator = Registry.getOrDefault(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class, null); @@ -70,9 +69,9 @@ public class TestApexStarterMain { } @Test - public void testApexStarter() throws ApexStarterException { + void testApexStarter() throws ApexStarterException { final String[] apexStarterConfigParameters = {"-c", "src/test/resources/ApexStarterConfigParametersNoop.json"}; - apexStarter = new ApexStarterMain(apexStarterConfigParameters); + ApexStarterMain apexStarter = new ApexStarterMain(apexStarterConfigParameters); assertTrue(apexStarter.getParameters().isValid()); assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarter.getParameters().getName()); @@ -84,7 +83,7 @@ public class TestApexStarterMain { } @Test - public void testApexStarter_NoArguments() { + void testApexStarter_NoArguments() { final String[] apexStarterConfigParameters = {}; assertThatThrownBy(() -> new ApexStarterMain(apexStarterConfigParameters)) .isInstanceOf(ApexStarterRunTimeException.class) @@ -92,7 +91,7 @@ public class TestApexStarterMain { } @Test - public void testApexStarter_InvalidArguments() { + void testApexStarter_InvalidArguments() { final String[] apexStarterConfigParameters = {"src/test/resources/ApexStarterConfigParameters.json"}; assertThatThrownBy(() -> new ApexStarterMain(apexStarterConfigParameters)) .isInstanceOf(ApexStarterRunTimeException.class) @@ -100,13 +99,13 @@ public class TestApexStarterMain { } @Test - public void testApexStarter_Help() { + void testApexStarter_Help() { final String[] apexStarterConfigParameters = {"-h"}; assertThatCode(() -> ApexStarterMain.main(apexStarterConfigParameters)).doesNotThrowAnyException(); } @Test - public void testApexStarter_InvalidParameters() { + void testApexStarter_InvalidParameters() { final String[] apexStarterConfigParameters = {"-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json"}; assertThatThrownBy(() -> new ApexStarterMain(apexStarterConfigParameters)) diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java index dda98db94..7bff64652 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * ================================================================================ @@ -23,20 +23,19 @@ package org.onap.policy.apex.services.onappf.comm; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager; import org.onap.policy.apex.services.onappf.ApexStarterActivator; import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; @@ -60,25 +59,23 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestPdpStateChangeListener { +class TestPdpStateChangeListener { private PdpUpdateListener pdpUpdateMessageListener; private PdpStateChangeListener pdpStateChangeListener; private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; private static final String TOPIC = "my-topic"; private ApexStarterActivator activator; private ApexEngineHandler apexEngineHandler; - private PrintStream stdout = System.out; + private final PrintStream stdout = System.out; /** * Method for setup before each test. * * @throws ApexStarterException if some error occurs while starting up the apex starter - * @throws FileNotFoundException if the file is missing - * @throws IOException if IO exception occurs * @throws CommandLineException if any parsing of args has errors */ - @Before - public void setUp() throws ApexStarterException, FileNotFoundException, IOException, CommandLineException { + @BeforeEach + void setUp() throws ApexStarterException, CommandLineException { pdpUpdateMessageListener = new PdpUpdateListener(); pdpStateChangeListener = new PdpStateChangeListener(); Registry.newRegistry(); @@ -108,8 +105,8 @@ public class TestPdpStateChangeListener { * * @throws Exception if an error occurs */ - @After - public void teardown() throws Exception { + @AfterEach + void teardown() throws Exception { System.setOut(stdout); apexEngineHandler = Registry.getOrDefault(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, ApexEngineHandler.class, null); @@ -123,7 +120,7 @@ public class TestPdpStateChangeListener { } @Test - public void testPdpStateChangeMessageListener_passivetopassive() { + void testPdpStateChangeMessageListener_passiveToPassive() { final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, TestListenerUtils.createPdpUpdateMsg(pdpStatus, new ArrayList<>(), @@ -136,7 +133,7 @@ public class TestPdpStateChangeListener { } @Test - public void testPdpStateChangeMessageListener_activetoactive() { + void testPdpStateChangeMessageListener_activeToActive() { final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, TestListenerUtils.createPdpUpdateMsg(pdpStatus, new ArrayList<>(), @@ -150,7 +147,7 @@ public class TestPdpStateChangeListener { } @Test - public void testPdpStateChangeMessageListener() throws InterruptedException, CoderException { + void testPdpStateChangeMessageListener() throws CoderException { OutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); @@ -180,11 +177,11 @@ public class TestPdpStateChangeListener { apexEngineHandler = Registry.getOrDefault(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, ApexEngineHandler.class, null); assertNotNull(apexEngineHandler); - assertTrue(apexEngineHandler.getEngineStats().size() > 0); + assertFalse(apexEngineHandler.getEngineStats().isEmpty()); } @Test - public void testPdpStateChangeMessageListener_activetopassive() throws InterruptedException, CoderException { + void testPdpStateChangeMessageListener_activeToPassive() throws CoderException { final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); final ToscaPolicy toscaPolicy = TestListenerUtils.createToscaPolicy("apex_policy_name", "1.0", "src/test/resources/dummyProperties.json"); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java index 3716e043f..56889cf72 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. * ================================================================================ @@ -23,21 +23,19 @@ package org.onap.policy.apex.services.onappf.comm; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.service.engine.main.ApexPolicyStatisticsManager; import org.onap.policy.apex.services.onappf.ApexStarterActivator; import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; @@ -62,25 +60,23 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestPdpUpdateListener { +class TestPdpUpdateListener { private PdpUpdateListener pdpUpdateMessageListener; private PdpStateChangeListener pdpStateChangeListener; private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; private static final String TOPIC = "my-topic"; private ApexStarterActivator activator; private ApexEngineHandler apexEngineHandler; - private PrintStream stdout = System.out; + private final PrintStream stdout = System.out; /** * Method for setup before each test. * * @throws ApexStarterException if some error occurs while starting up the apex starter - * @throws FileNotFoundException if the file is missing - * @throws IOException if IO exception occurs * @throws CommandLineException if any parsing of args has errors */ - @Before - public void setUp() throws ApexStarterException, FileNotFoundException, IOException, CommandLineException { + @BeforeEach + void setUp() throws ApexStarterException, CommandLineException { Registry.newRegistry(); final String[] apexStarterConfigParameters = {"-c", "src/test/resources/ApexStarterConfigParametersNoop.json"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); @@ -103,7 +99,7 @@ public class TestPdpUpdateListener { pdpUpdateMessageListener = new PdpUpdateListener(); pdpStateChangeListener = new PdpStateChangeListener(); Registry.register(ApexPolicyStatisticsManager.REG_APEX_PDP_POLICY_COUNTER, - new ApexPolicyStatisticsManager()); + new ApexPolicyStatisticsManager()); } /** @@ -111,8 +107,8 @@ public class TestPdpUpdateListener { * * @throws Exception if an error occurs */ - @After - public void teardown() throws Exception { + @AfterEach + void teardown() throws Exception { System.setOut(stdout); apexEngineHandler = Registry.getOrDefault(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, ApexEngineHandler.class, null); @@ -126,29 +122,29 @@ public class TestPdpUpdateListener { } @Test - public void testPdpUpdateMssageListener() throws CoderException { + void testPdpUpdateMessageListener() throws CoderException { final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); final ToscaPolicy toscaPolicy = TestListenerUtils.createToscaPolicy("apex policy name", "1.0", "src/test/resources/dummyProperties.json"); final List<ToscaPolicy> toscaPolicies = new ArrayList<ToscaPolicy>(); toscaPolicies.add(toscaPolicy); final PdpUpdate pdpUpdateMsg = TestListenerUtils.createPdpUpdateMsg(pdpStatus, toscaPolicies, - new LinkedList<>()); + new LinkedList<>()); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); assertEquals(pdpStatus.getPdpGroup(), pdpUpdateMsg.getPdpGroup()); assertEquals(pdpStatus.getPdpSubgroup(), pdpUpdateMsg.getPdpSubgroup()); assertEquals(pdpStatus.getPolicies(), - new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPoliciesToBeDeployed())); + new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPoliciesToBeDeployed())); } @Test - public void testPdpUpdateMssageListener_success() throws InterruptedException, CoderException { + void testPdpUpdateMessageListener_success() throws CoderException { OutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, TestListenerUtils.createPdpUpdateMsg(pdpStatus, new ArrayList<>(), - new ArrayList<>())); + new ArrayList<>())); PdpStateChange pdpStateChangeMsg = TestListenerUtils.createPdpStateChangeMsg(PdpState.ACTIVE, "pdpGroup", "pdpSubgroup", pdpStatus.getName()); pdpStateChangeListener.onTopicEvent(INFRA, TOPIC, null, pdpStateChangeMsg); @@ -157,22 +153,22 @@ public class TestPdpUpdateListener { final List<ToscaPolicy> toscaPolicies = new ArrayList<ToscaPolicy>(); toscaPolicies.add(toscaPolicy); final PdpUpdate pdpUpdateMsg = TestListenerUtils.createPdpUpdateMsg(pdpStatus, toscaPolicies, - new LinkedList<>()); + new LinkedList<>()); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); final String outString = outContent.toString(); assertEquals(pdpStatus.getPdpGroup(), pdpUpdateMsg.getPdpGroup()); assertEquals(pdpStatus.getPdpSubgroup(), pdpUpdateMsg.getPdpSubgroup()); assertEquals(pdpStatus.getPolicies(), - new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPoliciesToBeDeployed())); + new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPoliciesToBeDeployed())); assertThat(outString).contains("Apex engine started. Deployed policies are: apex_policy_name:1.0"); } @Test - public void testPdpUpdateMssageListener_undeploy() throws InterruptedException, CoderException { + void testPdpUpdateMessageListener_undeploy() throws CoderException { final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, TestListenerUtils.createPdpUpdateMsg(pdpStatus, new ArrayList<>(), - new ArrayList<>())); + new ArrayList<>())); PdpStateChange pdpStateChangeMsg = TestListenerUtils.createPdpStateChangeMsg(PdpState.ACTIVE, "pdpGroup", "pdpSubgroup", pdpStatus.getName()); pdpStateChangeListener.onTopicEvent(INFRA, TOPIC, null, pdpStateChangeMsg); @@ -181,21 +177,20 @@ public class TestPdpUpdateListener { final List<ToscaPolicy> toscaPolicies = new ArrayList<ToscaPolicy>(); toscaPolicies.add(toscaPolicy); final PdpUpdate pdpUpdateMsg = TestListenerUtils.createPdpUpdateMsg(pdpStatus, toscaPolicies, - new ArrayList<>()); + new ArrayList<>()); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); OutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, TestListenerUtils.createPdpUpdateMsg(pdpStatus, new ArrayList<>(), - toscaPolicies.stream().map(ToscaPolicy::getIdentifier) + toscaPolicies.stream().map(ToscaPolicy::getIdentifier) .collect(Collectors.toList()))); final String outString = outContent.toString(); assertThat(outString).contains("Pdp update successful. No policies are running."); } @Test - public void testPdpUpdateMssageListener_multi_policy_duplicate() - throws InterruptedException, ApexStarterException, CoderException { + void testPdpUpdateMessageListener_multi_policy_duplicate() throws CoderException { OutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT); @@ -207,7 +202,7 @@ public class TestPdpUpdateListener { toscaPolicies.add(toscaPolicy); toscaPolicies.add(toscaPolicy2); final PdpUpdate pdpUpdateMsg = TestListenerUtils.createPdpUpdateMsg(pdpStatus, toscaPolicies, - new LinkedList<>()); + new LinkedList<>()); pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); PdpStateChange pdpStateChangeMsg = TestListenerUtils.createPdpStateChangeMsg(PdpState.ACTIVE, "pdpGroup", "pdpSubgroup", pdpStatus.getName()); @@ -215,6 +210,6 @@ public class TestPdpUpdateListener { final String outString = outContent.toString(); assertTrue(outString.contains( "Apex engine started. But, only the following polices are running - apex_policy_name:1.0 . " - + "Other policies failed execution. Please see the logs for more details.")); + + "Other policies failed execution. Please see the logs for more details.")); } } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java index 7ccb850b1..da1568d33 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ package org.onap.policy.apex.services.onappf.exception; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.utils.test.ExceptionsTester; /** @@ -28,10 +28,10 @@ import org.onap.policy.common.utils.test.ExceptionsTester; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestExceptions { +class TestExceptions { @Test - public void test() { + void test() { new ExceptionsTester().test(ApexStarterException.class); new ExceptionsTester().test(ApexStarterRunTimeException.class); } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java index f227acc6c..099663af9 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java @@ -86,7 +86,7 @@ public class CommonTestData { * Converts the contents of a map to a parameter class. * * @param source property map - * @param clazz class of object to be created from the map + * @param clazz class of object to be created from the map * @return a new object represented by the map */ public <T extends ParameterGroup> T toObject(final Map<String, Object> source, final Class<T> clazz) { @@ -102,7 +102,6 @@ public class CommonTestData { * Returns a property map for a ApexStarterParameterGroup map for test cases. * * @param name name of the parameters - * * @return a property map suitable for constructing an object */ public Map<String, Object> getApexStarterParameterGroupMap(final String name) { diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java index c44964921..bd063d06a 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,12 +22,13 @@ package org.onap.policy.apex.services.onappf.parameters; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.parameters.RestServerParameters; import org.onap.policy.common.endpoints.parameters.TopicParameterGroup; import org.onap.policy.common.parameters.ValidationResult; @@ -37,23 +38,23 @@ import org.onap.policy.common.parameters.ValidationResult; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestApexStarterParameterGroup { +class TestApexStarterParameterGroup { CommonTestData commonTestData = new CommonTestData(); @Test - public void testApexStarterParameterGroup_Named() { + void testApexStarterParameterGroup_Named() { final ApexStarterParameterGroup apexStarterParameters = new ApexStarterParameterGroup("my-name"); assertEquals("my-name", apexStarterParameters.getName()); } @Test - public void testApexStarterParameterGroup() { + void testApexStarterParameterGroup() { final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), - ApexStarterParameterGroup.class); + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), + ApexStarterParameterGroup.class); final RestServerParameters restServerParameters = apexStarterParameters.getRestServerParameters(); final PdpStatusParameters pdpStatusParameters = apexStarterParameters.getPdpStatusParameters(); - final TopicParameterGroup topicParameterGroup = apexStarterParameters.getTopicParameterGroup(); + final TopicParameterGroup topicParameterGroup = apexStarterParameters.getTopicParameterGroup(); final ValidationResult validationResult = apexStarterParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarterParameters.getName()); @@ -72,19 +73,19 @@ public class TestApexStarterParameterGroup { } @Test - public void testApexStarterParameterGroup_NullName() { + void testApexStarterParameterGroup_NullName() { final ApexStarterParameterGroup apexStarterParameters = commonTestData - .toObject(commonTestData.getApexStarterParameterGroupMap(null), ApexStarterParameterGroup.class); + .toObject(commonTestData.getApexStarterParameterGroupMap(null), ApexStarterParameterGroup.class); final ValidationResult validationResult = apexStarterParameters.validate(); assertFalse(validationResult.isValid()); - assertEquals(null, apexStarterParameters.getName()); + assertNull(apexStarterParameters.getName()); assertTrue(validationResult.getResult().contains("is null")); } @Test - public void testApexStarterParameterGroup_EmptyName() { + void testApexStarterParameterGroup_EmptyName() { final ApexStarterParameterGroup apexStarterParameters = commonTestData - .toObject(commonTestData.getApexStarterParameterGroupMap(""), ApexStarterParameterGroup.class); + .toObject(commonTestData.getApexStarterParameterGroupMap(""), ApexStarterParameterGroup.class); final ValidationResult validationResult = apexStarterParameters.validate(); assertThat(validationResult.getResult()).contains("\"name\" value \"\" INVALID, is blank"); assertFalse(validationResult.isValid()); @@ -92,10 +93,10 @@ public class TestApexStarterParameterGroup { } @Test - public void testApexStarterParameterGroup_SetName() { + void testApexStarterParameterGroup_SetName() { final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), - ApexStarterParameterGroup.class); + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), + ApexStarterParameterGroup.class); apexStarterParameters.setName("ApexStarterNewGroup"); final ValidationResult validationResult = apexStarterParameters.validate(); assertTrue(validationResult.isValid()); @@ -103,26 +104,26 @@ public class TestApexStarterParameterGroup { } @Test - public void testApexStarterParameterGroup_EmptyPdpStatusParameters() { + void testApexStarterParameterGroup_EmptyPdpStatusParameters() { final Map<String, Object> map = - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); map.put("pdpStatusParameters", commonTestData.getPdpStatusParametersMap(true)); final ApexStarterParameterGroup apexStarterParameters = - commonTestData.toObject(map, ApexStarterParameterGroup.class); + commonTestData.toObject(map, ApexStarterParameterGroup.class); final ValidationResult validationResult = apexStarterParameters.validate(); assertThat(validationResult.getResult()) - .contains("\"ApexStarterParameterGroup\" INVALID, item has status INVALID"); + .contains("\"ApexStarterParameterGroup\" INVALID, item has status INVALID"); assertFalse(validationResult.isValid()); } @Test - public void testApexStarterParameterGroupp_EmptyRestServerParameters() { + void testApexStarterParameterGroupp_EmptyRestServerParameters() { final Map<String, Object> map = - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); map.put("restServerParameters", commonTestData.getRestServerParametersMap(true)); final ApexStarterParameterGroup apexStarterParameters = - commonTestData.toObject(map, ApexStarterParameterGroup.class); + commonTestData.toObject(map, ApexStarterParameterGroup.class); final ValidationResult validationResult = apexStarterParameters.validate(); assertThat(validationResult.getResult()).contains("\"RestServerParameters\" INVALID, item has status INVALID"); assertFalse(validationResult.isValid()); @@ -130,13 +131,13 @@ public class TestApexStarterParameterGroup { @Test - public void testApexStarterParameterGroupp_EmptyTopicParameters() { + void testApexStarterParameterGroup_EmptyTopicParameters() { final Map<String, Object> map = - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); map.put("topicParameterGroup", commonTestData.getTopicParametersMap(true)); final ApexStarterParameterGroup apexStarterParameters = - commonTestData.toObject(map, ApexStarterParameterGroup.class); + commonTestData.toObject(map, ApexStarterParameterGroup.class); final ValidationResult validationResult = apexStarterParameters.validate(); assertThat(validationResult.getResult()).contains("\"TopicParameterGroup\" INVALID, item has status INVALID"); assertFalse(validationResult.isValid()); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java index 90c2ef743..0f97203b4 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021 Nordix Foundation. + * Copyright (C) 2019-2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,11 +22,11 @@ package org.onap.policy.apex.services.onappf.parameters; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.FileNotFoundException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; import org.onap.policy.apex.services.onappf.exception.ApexStarterException; import org.onap.policy.common.utils.cmd.CommandLineException; @@ -37,11 +37,11 @@ import org.onap.policy.common.utils.coder.CoderException; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestApexStarterParameterHandler { +class TestApexStarterParameterHandler { @Test - public void testParameterHandlerNoParameterFile() throws ApexStarterException, CommandLineException { - final String[] emptyArgumentString = { "-c", "src/test/resources/NoParametersFile.json" }; + void testParameterHandlerNoParameterFile() throws CommandLineException { + final String[] emptyArgumentString = {"-c", "src/test/resources/NoParametersFile.json"}; final ApexStarterCommandLineArguments emptyArguments = new ApexStarterCommandLineArguments(); emptyArguments.parse(emptyArgumentString); @@ -52,8 +52,8 @@ public class TestApexStarterParameterHandler { } @Test - public void testParameterHandlerEmptyParameters() throws ApexStarterException, CommandLineException { - final String[] noArgumentString = { "-c", "src/test/resources/NoParameters.json" }; + void testParameterHandlerEmptyParameters() throws CommandLineException { + final String[] noArgumentString = {"-c", "src/test/resources/NoParameters.json"}; final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); noArguments.parse(noArgumentString); @@ -63,8 +63,8 @@ public class TestApexStarterParameterHandler { } @Test - public void testParameterHandlerInvalidParameters() throws ApexStarterException, CommandLineException { - final String[] invalidArgumentString = { "-c", "src/test/resources/InvalidParameters.json" }; + void testParameterHandlerInvalidParameters() throws CommandLineException { + final String[] invalidArgumentString = {"-c", "src/test/resources/InvalidParameters.json"}; final ApexStarterCommandLineArguments invalidArguments = new ApexStarterCommandLineArguments(); invalidArguments.parse(invalidArgumentString); @@ -75,8 +75,8 @@ public class TestApexStarterParameterHandler { } @Test - public void testParameterHandlerNoParameters() throws ApexStarterException, CommandLineException { - final String[] noArgumentString = { "-c", "src/test/resources/EmptyConfigParameters.json" }; + void testParameterHandlerNoParameters() throws CommandLineException { + final String[] noArgumentString = {"-c", "src/test/resources/EmptyConfigParameters.json"}; final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); noArguments.parse(noArgumentString); @@ -86,8 +86,8 @@ public class TestApexStarterParameterHandler { } @Test - public void testApexStarterParameterGroup() throws ApexStarterException, CommandLineException { - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json" }; + void testApexStarterParameterGroup() throws ApexStarterException, CommandLineException { + final String[] apexStarterConfigParameters = {"-c", "src/test/resources/ApexStarterConfigParameters.json"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); arguments.parse(apexStarterConfigParameters); @@ -98,9 +98,9 @@ public class TestApexStarterParameterHandler { } @Test - public void testApexStarterParameterGroup_InvalidName() throws ApexStarterException, CommandLineException { + void testApexStarterParameterGroup_InvalidName() throws CommandLineException { final String[] apexStarterConfigParameters = - { "-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json" }; + {"-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); arguments.parse(apexStarterConfigParameters); @@ -110,24 +110,24 @@ public class TestApexStarterParameterHandler { } @Test - public void testApexStarterVersion() throws ApexStarterException, CommandLineException { - final String[] apexStarterConfigParameters = { "-v" }; + void testApexStarterVersion() throws CommandLineException { + final String[] apexStarterConfigParameters = {"-v"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); final String version = arguments.parse(apexStarterConfigParameters); assertTrue(version.startsWith("ONAP Policy Framework Apex Starter Service")); } @Test - public void testApexStarterHelp() throws ApexStarterException, CommandLineException { - final String[] apexStarterConfigParameters = { "-h" }; + void testApexStarterHelp() throws CommandLineException { + final String[] apexStarterConfigParameters = {"-h"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); final String help = arguments.parse(apexStarterConfigParameters); assertTrue(help.startsWith("usage:")); } @Test - public void testApexStarterInvalidOption() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-d" }; + void testApexStarterInvalidOption() { + final String[] apexStarterConfigParameters = {"-d"}; final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); assertThatThrownBy(() -> arguments.parse(apexStarterConfigParameters)) .hasMessageStartingWith("invalid command line arguments specified"); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java index 765bb70a9..7b65ac71e 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,13 +22,13 @@ package org.onap.policy.apex.services.onappf.parameters; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.policy.common.parameters.ValidationResult; /** @@ -36,13 +36,13 @@ import org.onap.policy.common.parameters.ValidationResult; * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestPdpStatusParameters { - private static CommonTestData testData = new CommonTestData(); +class TestPdpStatusParameters { + private static final CommonTestData testData = new CommonTestData(); @Test - public void test() throws Exception { + void test() { final PdpStatusParameters pdpStatusParameters = - testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); + testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); final ValidationResult validationResult = pdpStatusParameters.validate(); assertTrue(validationResult.isValid()); assertEquals(CommonTestData.TIME_INTERVAL, pdpStatusParameters.getTimeIntervalMs()); @@ -53,31 +53,31 @@ public class TestPdpStatusParameters { } @Test - public void testValidate() throws Exception { + void testValidate() { final PdpStatusParameters pdpStatusParameters = - testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); + testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); final ValidationResult result = pdpStatusParameters.validate(); assertNull(result.getResult()); assertTrue(result.isValid()); } @Test - public void testPdpStatusParameters_nullPdpGroup() throws Exception { + void testPdpStatusParameters_nullPdpGroup() { Map<String, Object> pdpStatusParametersMap = testData.getPdpStatusParametersMap(false); pdpStatusParametersMap.remove("pdpGroup"); final PdpStatusParameters pdpStatusParameters = - testData.toObject(pdpStatusParametersMap, PdpStatusParameters.class); + testData.toObject(pdpStatusParametersMap, PdpStatusParameters.class); final ValidationResult validationResult = pdpStatusParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"pdpGroup\" value \"null\" INVALID"); } @Test - public void testPdpStatusParameters_emptyPdpGroup() throws Exception { + void testPdpStatusParameters_emptyPdpGroup() { Map<String, Object> pdpStatusParametersMap = testData.getPdpStatusParametersMap(false); pdpStatusParametersMap.put("pdpGroup", ""); final PdpStatusParameters pdpStatusParameters = - testData.toObject(pdpStatusParametersMap, PdpStatusParameters.class); + testData.toObject(pdpStatusParametersMap, PdpStatusParameters.class); final ValidationResult validationResult = pdpStatusParameters.validate(); assertFalse(validationResult.isValid()); assertThat(validationResult.getResult()).contains("\"pdpGroup\" value \"\" INVALID"); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyStateFinalizerExecutor.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyStateFinalizerExecutor.java index 2342542e4..b89333668 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyStateFinalizerExecutor.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyStateFinalizerExecutor.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,9 +24,7 @@ package org.onap.policy.apex.services.onappf.parameters.dummyclasses; import java.util.Map; import java.util.Properties; -import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.core.engine.executor.StateFinalizerExecutor; -import org.onap.policy.apex.core.engine.executor.exception.StateMachineException; /** * Dummy state finalizer executor for testing. @@ -35,7 +33,7 @@ public class DummyStateFinalizerExecutor extends StateFinalizerExecutor { @Override public String execute(final long executionId, final Properties executorProperties, - final Map<String, Object> newIncomingFields) throws StateMachineException, ContextException { + final Map<String, Object> newIncomingFields) { return "stateOutput0"; } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskExecutor.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskExecutor.java index eac2ec3ba..85999d74c 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskExecutor.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskExecutor.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -25,10 +25,8 @@ package org.onap.policy.apex.services.onappf.parameters.dummyclasses; import java.util.Map; import java.util.Properties; -import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.core.engine.event.EnEvent; import org.onap.policy.apex.core.engine.executor.TaskExecutor; -import org.onap.policy.apex.core.engine.executor.exception.StateMachineException; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; import org.onap.policy.apex.model.policymodel.concepts.AxTask; @@ -38,13 +36,13 @@ import org.onap.policy.apex.model.policymodel.concepts.AxTask; public class DummyTaskExecutor extends TaskExecutor { @Override - public void prepare() throws StateMachineException { + public void prepare() { // Not used } @Override public Map<String, Map<String, Object>> execute(final long executionId, final Properties executorProperties, - final Map<String, Object> newIncomingFields) throws StateMachineException, ContextException { + final Map<String, Object> newIncomingFields) { AxArtifactKey event0Key = new AxArtifactKey("Event0:0.0.1"); return Map.of(event0Key.getName(), new EnEvent(event0Key)); @@ -57,7 +55,7 @@ public class DummyTaskExecutor extends TaskExecutor { } @Override - public void cleanUp() throws StateMachineException { + public void cleanUp() { // Not used } } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskSelectExecutor.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskSelectExecutor.java index 5a6a98f4e..d51f2c4b0 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskSelectExecutor.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/dummyclasses/DummyTaskSelectExecutor.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,10 +23,8 @@ package org.onap.policy.apex.services.onappf.parameters.dummyclasses; import java.util.Properties; -import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.core.engine.event.EnEvent; import org.onap.policy.apex.core.engine.executor.TaskSelectExecutor; -import org.onap.policy.apex.core.engine.executor.exception.StateMachineException; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; /** @@ -35,19 +33,19 @@ import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; public class DummyTaskSelectExecutor extends TaskSelectExecutor { @Override - public void prepare() throws StateMachineException { + public void prepare() { // Not used } @Override public AxArtifactKey execute(final long executionId, final Properties executorProperties, - final EnEvent newIncomingEvent) throws StateMachineException, ContextException { + final EnEvent newIncomingEvent) { return new AxArtifactKey("task:0.0.1"); } @Override - public void cleanUp() throws StateMachineException { + public void cleanUp() { // Not used } } diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java index 24835d70c..3279c27ab 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/CommonApexStarterRestServer.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019,2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,8 +21,9 @@ package org.onap.policy.apex.services.onappf.rest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; @@ -39,10 +40,10 @@ import java.util.function.Function; import javax.net.ssl.SSLContext; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.onap.policy.apex.services.onappf.ApexStarterActivator; import org.onap.policy.apex.services.onappf.ApexStarterConstants; import org.onap.policy.apex.services.onappf.ApexStarterMain; @@ -59,7 +60,7 @@ import org.slf4j.LoggerFactory; import org.springframework.test.util.ReflectionTestUtils; /** - * Class to perform unit test of {@link ApexStarterRestServer}. + * Class to perform unit test to check REST endpoints. * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ @@ -67,9 +68,8 @@ public class CommonApexStarterRestServer { private static final Logger LOGGER = LoggerFactory.getLogger(CommonApexStarterRestServer.class); - private static Coder coder = new StandardCoder(); + private static final Coder coder = new StandardCoder(); - public static final String NOT_ALIVE = "not alive"; public static final String ALIVE = "alive"; public static final String SELF = "self"; public static final String ENDPOINT_PREFIX = "policy/apex-pdp/v1/"; @@ -86,7 +86,7 @@ public class CommonApexStarterRestServer { * * @throws Exception if an error occurs */ - @BeforeClass + @BeforeAll public static void setUpBeforeClass() throws Exception { port = NetworkUtil.allocPort(); @@ -100,7 +100,7 @@ public class CommonApexStarterRestServer { /** * Stops Main. */ - @AfterClass + @AfterAll public static void teardownAfterClass() { try { stopMain(); @@ -115,7 +115,7 @@ public class CommonApexStarterRestServer { * * @throws Exception if an error occurs */ - @Before + @BeforeEach public void setUp() throws Exception { // restart, if not currently running if (main == null) { @@ -123,13 +123,13 @@ public class CommonApexStarterRestServer { } activatorWasAlive = - Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class).isAlive(); + Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class).isAlive(); } /** * Restores the activator's "alive" state. */ - @After + @AfterEach public void tearDown() { markActivator(activatorWasAlive); } @@ -154,10 +154,10 @@ public class CommonApexStarterRestServer { */ private static void makeConfigFile() throws Exception { final Map<String, Object> config = - new CommonTestData().getApexStarterParameterGroupMap("ApexStarterParameterGroup"); + new CommonTestData().getApexStarterParameterGroupMap("ApexStarterParameterGroup"); - @SuppressWarnings("unchecked") - final Map<String, Object> restParams = (Map<String, Object>) config.get("restServerParameters"); + @SuppressWarnings("unchecked") final Map<String, Object> restParams = + (Map<String, Object>) config.get("restServerParameters"); restParams.put("port", port); final File file = new File("src/test/resources/TestConfigParams.json"); @@ -184,7 +184,7 @@ public class CommonApexStarterRestServer { systemProps.put("javax.net.ssl.keyStorePassword", SelfSignedKeyStore.KEYSTORE_PASSWORD); System.setProperties(systemProps); - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/TestConfigParams.json" }; + final String[] apexStarterConfigParameters = {"-c", "src/test/resources/TestConfigParams.json"}; main = new ApexStarterMain(apexStarterConfigParameters); @@ -196,7 +196,7 @@ public class CommonApexStarterRestServer { /** * Stops the "Main". * - * @throws Exception if an error occurs + * @throws ApexStarterException if an error occurs */ private static void stopMain() throws ApexStarterException { if (main != null) { @@ -209,8 +209,10 @@ public class CommonApexStarterRestServer { private void markActivator(final boolean wasAlive) { final Object manager = ReflectionTestUtils.getField( - Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class), "manager"); + Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class), "manager"); + assertNotNull(manager); AtomicBoolean running = (AtomicBoolean) ReflectionTestUtils.getField(manager, "running"); + assertNotNull(running); running.set(wasAlive); } @@ -218,13 +220,13 @@ public class CommonApexStarterRestServer { * Verifies that unauthorized requests fail. * * @param endpoint the target end point - * @param sender function that sends the requests to the target + * @param sender function that sends the requests to the target * @throws Exception if an error occurs */ - protected void checkUnauthRequest(final String endpoint, final Function<Invocation.Builder, Response> sender) - throws Exception { + protected void checkUnauthorizedRequest(final String endpoint, final Function<Invocation.Builder, Response> sender) + throws Exception { assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), - sender.apply(sendNoAuthRequest(endpoint)).getStatus()); + sender.apply(sendNoAuthRequest(endpoint)).getStatus()); } /** @@ -253,16 +255,16 @@ public class CommonApexStarterRestServer { * Sends a request to a fully qualified endpoint. * * @param fullyQualifiedEndpoint the fully qualified target endpoint - * @param includeAuth if authorization header should be included + * @param includeAuth if authorization header should be included * @return a request builder * @throws Exception if an error occurs */ protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, final boolean includeAuth) - throws Exception { + throws Exception { final SSLContext sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom()); final ClientBuilder clientBuilder = - ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); + ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); final Client client = clientBuilder.build(); client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java index a49fb5070..a63824a0e 100644 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/rest/TestHealthCheckRestControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,44 +22,39 @@ package org.onap.policy.apex.services.onappf.rest; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import jakarta.ws.rs.client.Invocation; -import org.junit.Ignore; -import org.junit.Test; +import jakarta.ws.rs.client.SyncInvoker; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.onap.policy.common.endpoints.report.HealthCheckReport; /** - * Class to perform unit test of {@link ApexStarterRestServer}. + * Class to perform unit test of {@link HealthCheckRestControllerV1}. * * @author Ajith Sreekumar (ajith.sreekumar@est.tech) */ -public class TestHealthCheckRestControllerV1 extends CommonApexStarterRestServer { +class TestHealthCheckRestControllerV1 extends CommonApexStarterRestServer { private static final String HEALTHCHECK_ENDPOINT = "healthcheck"; - @Ignore @Test - public void testSwagger() throws Exception { - super.testSwagger(HEALTHCHECK_ENDPOINT); - } - - @Test - public void testHealthCheckSuccess() throws Exception { + void testHealthCheckSuccess() throws Exception { final Invocation.Builder invocationBuilder = sendRequest(HEALTHCHECK_ENDPOINT); final HealthCheckReport report = invocationBuilder.get(HealthCheckReport.class); - validateHealthCheckReport(SELF, true, 200, ALIVE, report); + validateHealthCheckReport(report); // verify it fails when no authorization info is included - checkUnauthRequest(HEALTHCHECK_ENDPOINT, req -> req.get()); + checkUnauthorizedRequest(HEALTHCHECK_ENDPOINT, SyncInvoker::get); } - private void validateHealthCheckReport(final String url, final boolean healthy, final int code, - final String message, final HealthCheckReport report) { + private void validateHealthCheckReport(final HealthCheckReport report) { assertThat(report.getName()).isNotBlank(); - assertEquals(url, report.getUrl()); - assertEquals(healthy, report.isHealthy()); - assertEquals(code, report.getCode()); - assertEquals(message, report.getMessage()); + assertEquals(CommonApexStarterRestServer.SELF, report.getUrl()); + assertTrue(report.isHealthy()); + assertEquals(200, report.getCode()); + assertEquals(CommonApexStarterRestServer.ALIVE, report.getMessage()); } } |