@Getter
private ApexParameters apexParameters;
- private ApexParameterHandler apexParameterHandler = new ApexParameterHandler();
+ private final ApexParameterHandler apexParameterHandler = new ApexParameterHandler();
@Getter
@Setter(lombok.AccessLevel.PRIVATE)
/*-
* ============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");
// 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.
* 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;
// 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());
}
*/
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();
*/
@Override
public AxArtifactKey getApexModelKey() {
- if (engineWorkerMap.size() == 0) {
+ if (engineWorkerMap.isEmpty()) {
return null;
}
}
/**
- * 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()));
*/
@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
*/
@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
* 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);
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
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() + "\"");
}
}
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
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
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
@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();
@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();
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
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
@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);
/**
* {@inheritDoc}.
- *
*/
@Override
public List<AxEngineModel> getEngineStats() {
@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
@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;
}
// 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);
+ }
}
/*
* ============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");
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;
*
* @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();
}
@Test
- public void setExecutionProperties() {
+ void setExecutionProperties() {
final Properties properties = new Properties();
apexEvent.setExecutionProperties(properties);
final Properties actual = apexEvent.getExecutionProperties();
}
@Test
- public void setExceptionMessage() {
+ void setExceptionMessage() {
final String message = RandomStringUtils.randomAlphabetic(25);
apexEvent.setExceptionMessage(message);
final String actual = apexEvent.getExceptionMessage();
}
@Test
- public void put() {
+ void put() {
final String key = RandomStringUtils.randomAlphabetic(5);
final Object event = new Object();
apexEvent.put(key, event);
}
@Test
- public void put2() {
+ void put2() {
final String key = "_#+@" + RandomStringUtils.randomAlphabetic(5);
final Object event = new Object();
apexEvent.put(key, event);
}
@Test
- public void putAll() {
+ void putAll() {
final String key1 = RandomStringUtils.randomAlphabetic(5);
final String key2 = RandomStringUtils.randomAlphabetic(6);
final Object event1 = new Object();
}
@Test
- public void putAllOneInvalidKey() {
+ void putAllOneInvalidKey() {
final String key1 = RandomStringUtils.randomAlphabetic(5);
final String key2 = "_#+@" + RandomStringUtils.randomAlphabetic(6);
final String key3 = RandomStringUtils.randomAlphabetic(7);
/*
* ============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");
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
/*-
* ============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");
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;
* 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))
.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");
/*-
* ============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.
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;
*
* @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()));
/**
* 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);
/**
* Teardown default schema parameters.
*/
- @AfterClass
- public static void teardownDefaultSchemaParameters() {
+ @AfterAll
+ static void teardownDefaultSchemaParameters() {
ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
ModelService.clear();
}
* 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);
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);
* 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);
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);
* 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);
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);
/*-
* ============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");
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;
*
* @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()));
/**
* 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);
/**
* Teardown default schema parameters.
*/
- @AfterClass
- public static void teardownDefaultSchemaParameters() {
+ @AfterAll
+ static void teardownDefaultSchemaParameters() {
ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
ModelService.clear();
}
* @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());
*/
@SuppressWarnings("deprecation")
@Test
- public void testJsontoApexBadEvent() throws ApexException {
+ void testJsontoApexBadEvent() throws ApexException {
final Apex2JsonEventConverter jsonEventConverter = new Apex2JsonEventConverter();
assertNotNull(jsonEventConverter);
jsonEventConverter.init(new JsonEventProtocolParameters());
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"));
* @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);
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);
/*-
* ============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");
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());
}
* ============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.
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;
* 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());
}
}
/*
* ============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.
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;
}
@Test
- public void getPeeredProducer() {
+ void getPeeredProducer() {
final ApexEventConsumer eventConsumer = new ApexFileEventConsumer();
final ApexEventProducer eventProducer = new ApexFileEventProducer();
final EventHandlerPeeredMode peeredMode = EventHandlerPeeredMode.SYNCHRONOUS;
* ============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.
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;
/**
* 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);
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);
}
}
/*
* ============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");
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 =
}
@Test
- public void removeCachedFromApex() {
+ void removeCachedFromApex() {
int timeout = random.nextInt(100);
int executionId = random.nextInt();
final SynchronousEventCache cache =
}
@Test
- public void removedCachedToApexNotExists() {
+ void removedCachedToApexNotExists() {
int timeout = random.nextInt(100);
int executionId = random.nextInt();
final SynchronousEventCache cache =
}
@Test
- public void removeCachedToApex() {
+ void removeCachedToApex() {
int timeout = random.nextInt(100);
int executionId = random.nextInt();
final SynchronousEventCache cache =
}
@Test
- public void apexExistsFromApexNo() {
+ void apexExistsFromApexNo() {
int executionId = random.nextInt();
final SynchronousEventCache cache =
new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0);
}
@Test
- public void apexExistsFromApexYes() {
+ void apexExistsFromApexYes() {
int executionId = random.nextInt();
final SynchronousEventCache cache =
new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0);
}
@Test
- public void apexExistsToApexNo() {
+ void apexExistsToApexNo() {
int executionId = random.nextInt();
final SynchronousEventCache cache =
new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0);
}
@Test
- public void apexExistsToApexYes() {
+ void apexExistsToApexYes() {
int executionId = random.nextInt();
final SynchronousEventCache cache =
new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 0);
}
@Test
- public void addEventsFromApexDuplicatedExecutionId() {
+ void addEventsFromApexDuplicatedExecutionId() {
int timeout = random.nextInt(100);
int executionId = random.nextInt();
final SynchronousEventCache cache =
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);
}
@Test
- public void stopNotEmpty() {
+ void stopNotEmpty() {
final SynchronousEventCache cache =
new SynchronousEventCache(EventHandlerPeeredMode.SYNCHRONOUS, consumer, producer, 2000);
assertThatCode(() -> {
/*
* ============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.
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();
}
@Test
- public void createConsumerNoConsumerPlugin() {
+ void createConsumerNoConsumerPlugin() {
final String name = RandomStringUtils.randomAlphabetic(6);
final EventHandlerParameters parameters = new EventHandlerParameters();
parameters.setCarrierTechnologyParameters(new RestPluginCarrierTechnologyParameters());
}
@Test
- public void createConsumerWrongPluginClassName() {
+ void createConsumerWrongPluginClassName() {
final String name = RandomStringUtils.randomAlphabetic(6);
final EventHandlerParameters parameters = new EventHandlerParameters();
final RestPluginCarrierTechnologyParameters technologyParameters =
}
@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());
/*
* ============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.
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);
}
@Test
- public void createConsumerNoConsumerPlugin() {
+ void createConsumerNoConsumerPlugin() {
final EventHandlerParameters parameters = new EventHandlerParameters();
final String name = RandomStringUtils.randomAlphabetic(4);
parameters.setCarrierTechnologyParameters(new RestPluginCarrierTechnologyParameters());
}
@Test
- public void createConsumerWrongProducerPluginName() {
+ void createConsumerWrongProducerPluginName() {
final EventHandlerParameters parameters = new EventHandlerParameters();
final RestPluginCarrierTechnologyParameters technologyParameters =
new RestPluginCarrierTechnologyParameters();
}
@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);
/*
* ============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.
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);
}
@Test
- public void createConsumer2() {
+ void createConsumer2() {
final EventProtocolParameters parameters = new ApexEventProtocolParameters();
final String name = RandomStringUtils.randomAlphabetic(9);
parameters.setEventProtocolPluginClass("java.lang.Object");
}
@Test
- public void createConsumer() {
+ void createConsumer() {
final EventProtocolParameters parameters = new JsonEventProtocolParameters();
final String name = RandomStringUtils.randomAlphabetic(9);
/*
* ============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");
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);
}
@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);
}
@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);
}
@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);
}
@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);
/*
* ============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.
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();
}
@Test
- public void testConstructor() {
+ void testConstructor() {
final String expected = RandomStringUtils.randomAlphabetic(6);
final ApexEventProtocolParameters apexEventProtocolParameters = new ApexEventProtocolParameters(expected);
final String actual = apexEventProtocolParameters.getLabel();
/*
* ============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");
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;
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);
}
@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);
/*
* ============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");
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);
/*
* ============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.
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;
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();
}
@Test
- public void initNoPeered() {
+ void initNoPeered() {
final String consumerName = RandomStringUtils.randomAlphabetic(6);
final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters();
eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters());
}
@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());
}
@Test
- public void getSetPeeeredReference() {
+ void getSetPeeeredReference() {
final PeeredReference peeredReference =
new PeeredReference(EventHandlerPeeredMode.REQUESTOR, new ApexFileEventConsumer(),
new ApexFileEventProducer());
/*
* ============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");
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;
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;
@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();
}
@Test
- public void initNotPeered() {
+ void initNotPeered() {
final String producerName = RandomStringUtils.random(4);
final EventHandlerParameters eventHandlerParameters = new EventHandlerParameters();
eventHandlerParameters.setCarrierTechnologyParameters(new EventRequestorCarrierTechnologyParameters());
}
@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());
}
@Test
- public void getSetPeeredReference() {
+ void getSetPeeredReference() {
final PeeredReference peeredReference = new PeeredReference(EventHandlerPeeredMode.SYNCHRONOUS, apexConsumer,
apexProducer);
producer.setPeeredReference(EventHandlerPeeredMode.SYNCHRONOUS, peeredReference);
}
@Test
- public void sendEventNoRequestor() {
+ void sendEventNoRequestor() {
final int id = random.nextInt(1000);
assertThatThrownBy(() -> producer.sendEvent(id, null, null, null))
}
@Test
- public void sendEventNoEventRequestorConsumer() {
+ void sendEventNoEventRequestorConsumer() {
final int id = random.nextInt(1000);
final ApexFileEventConsumer fileEventConsumer = Mockito.mock(ApexFileEventConsumer.class);
}
@Test
- public void sendEvent() {
+ void sendEvent() {
final int id = random.nextInt(1000);
final PeeredReference reference =
}
@Test
- public void sendEventCached() {
+ void sendEventCached() {
final int id = random.nextInt(1000);
// Set event cache
/*
* ============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.
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);
}
@Test
- public void getSetFileName() {
+ void getSetFileName() {
final String fileName = RandomStringUtils.random(10);
parameters.setFileName(fileName);
assertThat(parameters.getFileName())
}
@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();
}
@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();
}
@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()));
}
@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();
}
@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();
/*
* ============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.
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;
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;
*
* @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");
}
@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);
}
@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);
}
}
/*
* ============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.
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();
}
@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;
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();
}
@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();
}
@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;
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();
/*
* ============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.
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();
}
@Test
- public void getTaggedReaderTextTokenDelimitedParams() throws ApexEventException {
+ void getTaggedReaderTextTokenDelimitedParams() throws ApexEventException {
final String text = RandomStringUtils.randomAlphanumeric(22);
final InputStream inputStream = prepareInputStream(text);
new ApexEventProtocolParameters();
}
@Test
- public void getTaggedReaderNotSupportedParams() {
+ void getTaggedReaderNotSupportedParams() {
final String text = RandomStringUtils.randomAlphanumeric(22);
final InputStream inputStream = prepareInputStream(text);
final EventProtocolParameters parameters = new ApexEventProtocolParameters();
/*
* ============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.
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);
}
@Test
- public void getText() {
+ void getText() {
final boolean endOfText = random.nextBoolean();
final String text = RandomStringUtils.randomAlphanumeric(8);
final TextBlock textBlock = new TextBlock(endOfText, text);
}
@Test
- public void setText() {
+ void setText() {
final boolean endOfText = random.nextBoolean();
final String text = RandomStringUtils.randomAlphanumeric(8);
final TextBlock textBlock = new TextBlock(endOfText, null);
/*
* ============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.
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;
/**
* 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))
}
@Test
- public void initParamsWithStandardError() {
+ void initParamsWithStandardError() {
final String name = RandomStringUtils.randomAlphabetic(5);
technologyParameters.setStandardError(true);
}
@Test
- public void initParamsWithStandardIo() {
+ void initParamsWithStandardIo() {
final String name = RandomStringUtils.randomAlphabetic(5);
technologyParameters.setStandardIo(true);
}
@Test
- public void initParamsWithFileIsDirectory() {
+ void initParamsWithFileIsDirectory() {
final String name = RandomStringUtils.randomAlphabetic(5);
final String fileName = System.getProperty("user.dir");
}
@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();
}
@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));
// 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);
/*-
* ============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");
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;
/**
*
* @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"};
}
@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();
}
}
/*-
* ============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.
* ================================================================================
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;
*
* @throws Exception if an error occurs
*/
- @Before
- public void setUp() throws Exception {
+ @BeforeEach
+ void setUp() throws Exception {
System.setOut(new PrintStream(outContent));
}
*
* @throws Exception if an error occurs
*/
- @After
- public void teardown() throws Exception {
+ @AfterEach
+ void teardown() throws Exception {
if (null != apexMain1) {
apexMain1.shutdown();
}
}
@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);
}
@Test
- public void testJavaProperties() throws ApexException {
+ void testJavaProperties() {
String[] args = {"-p", "src/test/resources/parameters/correctParamsJavaProperties.json"};
apexMain1 = new ApexMain(args);
}
@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);
}
@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);
}
@Test
- public void testInvalidArgsWithMultiplePolicies() throws ApexException {
+ void testInvalidArgsWithMultiplePolicies() {
String[] args = {"-c", "file1", "-m", "file2"};
apexMain1 = new ApexMain(args);
assertFalse(apexMain1.isAlive());
/*-
* ============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");
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);
}
@Test
- public void testUpdatePolicyExecutedCounter() {
+ void testUpdatePolicyExecutedCounter() {
statisticsManager.updatePolicyExecutedCounter(true);
assertExecuted(1, 1, 0);
}
@Test
- public void testUpdatePolicyUndeployCounter() {
+ void testUpdatePolicyUndeployCounter() {
statisticsManager.updatePolicyUndeployCounter(false);
assertUndeploys(1, 0, 1);
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());
/*-
* ============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.
* ================================================================================
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;
/**
* 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);
}
@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);
}
@Test
- public void testJavaPropertiesBad() throws ParameterException {
+ void testJavaPropertiesBad() {
final String[] args = {"-p", "src/test/resources/parameters/javaPropertiesBad.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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);
}
@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);
}
@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);
}
@Test
- public void testGettersSetters() {
+ void testGettersSetters() {
ApexParameters pars = new ApexParameters();
assertNotNull(pars);
/*-
* ============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");
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;
*
* @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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
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);
}
@Test
- public void testBadClassLockParamTest() {
+ void testBadClassLockParamTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassLockParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testBadClassPersistParamTest() {
+ void testBadClassPersistParamTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceContextBadClassPersistParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
/*-
* ============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");
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;
*
* @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);
}
@Test
- public void testEmptyParamsTest() {
+ void testEmptyParamsTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorEmptyParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testBadPluginParamNameTest() {
+ void testBadPluginParamNameTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginNameParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testBadPluginParamObjectTest() {
+ void testBadPluginParamObjectTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginValueObjectParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testBadPluginParamBlankTest() {
+ void testBadPluginParamBlankTest() {
final String[] args = {"-p", "src/test/resources/parameters/serviceExecutorBadPluginValueBlankParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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);
}
@Test
- public void testRelativeParametersTest() throws ParameterException {
+ void testRelativeParametersTest() throws ParameterException {
// @formatter:off
final String[] args = {
"-rfr",
/*-
* ============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.
* ================================================================================
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;
*
* @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);
}
@Test
- public void testInvalidParametersEmptyTest() {
+ void testInvalidParametersEmptyTest() {
final String[] args = {"-p", "src/test/resources/parameters/empty.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testInvalidParametersNoParamsTest() {
+ void testInvalidParametersNoParamsTest() {
final String[] args = {"-p", "src/test/resources/parameters/noParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testInvalidParametersBlankParamsTest() {
+ void testInvalidParametersBlankParamsTest() {
final String[] args = {"-p", "src/test/resources/parameters/blankParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testInvalidParametersTest() {
+ void testInvalidParametersTest() {
final String[] args = {"-p", "src/test/resources/parameters/badParams.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
.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);
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);
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());
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());
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());
-
}
}
/*-
* ============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.
* ================================================================================
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;
*
* @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);
}
@Test
- public void testNoCarrierTechnology() {
+ void testNoCarrierTechnology() {
final String[] args = {"-p", "src/test/resources/parameters/prodConsNoCT.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
.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);
.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);
}
@Test
- public void testMismatchCarrierTechnologyParClass() {
+ void testMismatchCarrierTechnologyParClass() {
final String[] args = {"-p", "src/test/resources/parameters/prodConsMismatchCTParClass.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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 "
}
@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);
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);
.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);
}
@Test
- public void testNoEventProtocolParClass() {
+ void testNoEventProtocolParClass() {
final String[] args = {"-p", "src/test/resources/parameters/prodConsNoEPParClass.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testMismatchEventProtocolParClass() {
+ void testMismatchEventProtocolParClass() {
final String[] args = {"-p", "src/test/resources/parameters/prodConsMismatchEPParClass.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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')");
}
/*-
* ============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.
* ================================================================================
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;
*
* @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);
}
@Test
- public void testSyncBadNotSyncWithPeer() throws ParameterException {
+ void testSyncBadNotSyncWithPeer() {
final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsNotSyncWithPeer.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncBadSyncBadPeers() throws ParameterException {
+ void testSyncBadSyncBadPeers() {
final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsBadPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncBadSyncInvalidTimeout() throws ParameterException {
+ void testSyncBadSyncInvalidTimeout() {
final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsInvalidTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncBadSyncBadTimeout() throws ParameterException {
+ void testSyncBadSyncBadTimeout() {
final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsBadTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncBadSyncUnpairedTimeout() throws ParameterException {
+ void testSyncBadSyncUnpairedTimeout() {
final String[] args = {"-p", "src/test/resources/parameters/syncBadParamsUnpairedTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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");
}
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);
}
@Test
- public void testSyncMismatchedPeers() throws ParameterException {
+ void testSyncMismatchedPeers() {
final String[] args = {"-p", "src/test/resources/parameters/syncMismatchedPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncUnusedProducerPeers() throws ParameterException {
+ void testSyncUnusedProducerPeers() {
final String[] args = {"-p", "src/test/resources/parameters/syncUnusedProducerPeers.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@Test
- public void testSyncMismatchedTimeout() throws ParameterException {
+ void testSyncMismatchedTimeout() {
final String[] args = {"-p", "src/test/resources/parameters/syncMismatchedTimeout.json"};
final ApexCommandLineArguments arguments = new ApexCommandLineArguments(args);
}
@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);
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());
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());
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());
}
}
/*-
* ============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.
* ================================================================================
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;
/**
* Test the engine service implementation.
*/
-public class EngineServiceImplTest {
+class EngineServiceImplTest {
private static String simpleModelString;
private static String differentModelString;
* @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 =
/**
* 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);
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);
}
@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);
}
@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)
.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");
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");
}
@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());
fail("test should not throw an exception");
}
+ assertPeriodicEvents(esImpl);
+ }
+
+ private static void assertPeriodicEvents(EngineServiceImpl esImpl) throws ApexException {
esImpl.startPeriodicEvents(100000);
esImpl.stop();
esImpl.startAll();
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());
}
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 {
/*-
* ============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");
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;
/**
* Test the engine worker class.
*/
-public class EngineWorkerTest {
+class EngineWorkerTest {
private final ApplicationThreadFactory atFactory = new ApplicationThreadFactory("apex-engine-service", 512);
private static String simpleModelString;
/**
* 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()));
/**
* 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);
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);
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<>();
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));
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());
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());
}
}
/*-
* ============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.
* ================================================================================
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.
* @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 -> {
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);
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 =
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.");
/*-
* ============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.
* ================================================================================
*
* @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);
/*-
* ============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.
* ================================================================================
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);
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(
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;
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;
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());
}
return;
}
var policiesToDeploy = policies.stream()
- .map(ToscaWithTypeAndObjectProperties::getIdentifier).collect(Collectors.toList());
+ .map(ToscaWithTypeAndObjectProperties::getIdentifier).toList();
var policiesSuccessfullyDeployed = new ArrayList<>(policiesToDeploy);
policiesSuccessfullyDeployed.retainAll(runningPolicies);
/*-
* ============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.
* ================================================================================
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);
}
}
if (null == pdpResponseDetails) {
- pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(),
+ pdpResponseDetails = pdpMessageHandler.createPdpResponseDetails(pdpUpdateMsg.getRequestId(),
PdpResponseStatus.SUCCESS, "Pdp update successful.");
}
return pdpResponseDetails;
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);
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);
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 =
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;
/*-
* ============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.
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;
*
* @author Ajith Sreekumar (ajith.sreekumar@est.tech)
*/
-public class TestApexStarterActivator {
+class TestApexStarterActivator {
private ApexStarterActivator activator;
*
* @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);
}
*
* @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());
}
@Test
- public void testTerminate() throws Exception {
+ void testTerminate() throws Exception {
activator.initialize();
activator.terminate();
assertFalse(activator.isAlive());
/*-
* ============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.
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
* 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());
* 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");
/*-
* ============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");
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();
/*-
* ============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.
* ================================================================================
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;
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();
}
*
* @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);
}
@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());
}
@Test
- public void testApexStarter_NoArguments() {
+ void testApexStarter_NoArguments() {
final String[] apexStarterConfigParameters = {};
assertThatThrownBy(() -> new ApexStarterMain(apexStarterConfigParameters))
.isInstanceOf(ApexStarterRunTimeException.class)
}
@Test
- public void testApexStarter_InvalidArguments() {
+ void testApexStarter_InvalidArguments() {
final String[] apexStarterConfigParameters = {"src/test/resources/ApexStarterConfigParameters.json"};
assertThatThrownBy(() -> new ApexStarterMain(apexStarterConfigParameters))
.isInstanceOf(ApexStarterRunTimeException.class)
}
@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))
/*-
* ============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.
* ================================================================================
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;
*
* @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();
*
* @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);
}
@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<>(),
}
@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<>(),
}
@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);
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");
/*-
* ============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.
* ================================================================================
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;
*
* @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();
pdpUpdateMessageListener = new PdpUpdateListener();
pdpStateChangeListener = new PdpStateChangeListener();
Registry.register(ApexPolicyStatisticsManager.REG_APEX_PDP_POLICY_COUNTER,
- new ApexPolicyStatisticsManager());
+ new ApexPolicyStatisticsManager());
}
/**
*
* @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);
}
@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);
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);
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);
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());
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."));
}
}
/*-
* ============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.
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;
/**
*
* @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);
}
* 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) {
* 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) {
/*-
* ============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");
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;
*
* @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());
}
@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());
}
@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());
}
@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());
@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());
/*-
* ============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");
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;
*
* @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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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);
}
@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");
/*-
* ============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");
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;
/**
*
* @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());
}
@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");
/*-
* ============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");
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.
@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";
}
/*-
* ============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.
* ================================================================================
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;
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));
}
@Override
- public void cleanUp() throws StateMachineException {
+ public void cleanUp() {
// Not used
}
}
/*-
* ============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");
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;
/**
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
}
}
/*-
* ============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");
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;
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;
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)
*/
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/";
*
* @throws Exception if an error occurs
*/
- @BeforeClass
+ @BeforeAll
public static void setUpBeforeClass() throws Exception {
port = NetworkUtil.allocPort();
/**
* Stops Main.
*/
- @AfterClass
+ @AfterAll
public static void teardownAfterClass() {
try {
stopMain();
*
* @throws Exception if an error occurs
*/
- @Before
+ @BeforeEach
public void setUp() throws Exception {
// restart, if not currently running
if (main == null) {
}
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);
}
*/
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");
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);
/**
* Stops the "Main".
*
- * @throws Exception if an error occurs
+ * @throws ApexStarterException if an error occurs
*/
private static void stopMain() throws ApexStarterException {
if (main != null) {
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);
}
* 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());
}
/**
* 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");
/*-
* ============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");
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());
}
}