diff options
Diffstat (limited to 'core')
16 files changed, 392 insertions, 1009 deletions
diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java index 000acab75..ab44f900d 100644 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java +++ b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/BatchDeployerTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,7 @@ package org.onap.policy.apex.core.deployment; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayOutputStream; import java.io.File; @@ -43,39 +42,27 @@ import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; public class BatchDeployerTest { @Test public void testBatchDeployerBad() { - try { - final String[] eventArgs = { "-h" }; - - BatchDeployer.main(eventArgs); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("invalid arguments: [-h]", exc.getMessage().substring(0, 23)); - } + final String[] eventArgs = { "-h" }; + + assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) + .hasMessageContaining("invalid arguments: [-h]"); } @Test public void testBatchDeployerBadPort() { - try { - final String[] eventArgs = { "localhost", "aport", "afile" }; - - BatchDeployer.main(eventArgs); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("argument port is invalid", exc.getMessage().substring(0, 24)); - } + final String[] eventArgs = { "localhost", "aport", "afile" }; + + assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) + .hasMessage("argument port is invalid"); } @Test public void testBatchDeployerOk() { - try { - final String[] eventArgs = { "Host", "43443", - "src/test/resources/models/SamplePolicyModelJAVASCRIPT.json" }; - - BatchDeployer.main(eventArgs); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("model deployment failed on parameters Host 43443", exc.getMessage()); - } + final String[] eventArgs = { "Host", "43443", + "src/test/resources/models/SamplePolicyModelJAVASCRIPT.json" }; + + assertThatThrownBy(() -> BatchDeployer.main(eventArgs)) + .hasMessage("model deployment failed on parameters Host 43443"); } @Test @@ -88,13 +75,7 @@ public class BatchDeployerTest { // We are testing towards a dummy client, make it return a failed initiation dummyDeploymentClient.setInitSuccessful(false); - try { - deployer.init(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("model deployment failed on parameters localhost 12345", ade.getMessage()); - } - + assertThatThrownBy(deployer::init).hasMessage("model deployment failed on parameters localhost 12345"); // Wait until the connection to the server closes following the bad connection // attempt Awaitility.await().atLeast(Duration.ofMillis(100)); @@ -103,14 +84,8 @@ public class BatchDeployerTest { dummyDeploymentClient.setInitSuccessful(true); deployer.init(); - try { - deployer.deployModel("src/test/resources/models/SmallModel.json", false, false); - fail("test should throw an exception"); - } catch (ApexException ade) { - assertEquals("could not deploy apex model from src/test/resources/models/SmallModel.json", - ade.getMessage()); - } - + assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SmallModel.json", false, false)) + .hasMessage("could not deploy apex model from src/test/resources/models/SmallModel.json"); deployer.deployModel("src/test/resources/models/SmallModel.json", false, false); deployer.close(); @@ -126,18 +101,14 @@ public class BatchDeployerTest { deployer.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); dummyDeploymentClient.setInitSuccessful(false); - try { - deployer.init(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("model deployment failed on parameters localhost 12345", ade.getMessage()); - } - + assertThatThrownBy(deployer::init) + .hasMessage("model deployment failed on parameters localhost 12345"); // Wait until the connection to the server closes following the bad connection // attempt Awaitility.await().atLeast(Duration.ofMillis(100)); dummyDeploymentClient.setInitSuccessful(true); + deployer.init(); final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class); @@ -145,12 +116,8 @@ public class BatchDeployerTest { final AxPolicyModel apexPolicyModel = modelReader .read(new FileInputStream(new File("src/test/resources/models/SmallModel.json"))); - try { - deployer.deployModel(apexPolicyModel, false, false); - fail("test should throw an exception"); - } catch (ApexException ade) { - assertEquals("failed response Operation failed received from serverlocalhost:12345", ade.getMessage()); - } + assertThatThrownBy(() -> deployer.deployModel(apexPolicyModel, false, false)) + .hasMessage("failed response Operation failed received from serverlocalhost:12345"); deployer.deployModel(apexPolicyModel, false, false); @@ -164,19 +131,12 @@ public class BatchDeployerTest { BatchDeployer deployer = new BatchDeployer("localhost", 12345, new PrintStream(baosOut, true)); deployer.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - try { - deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", false, false); - fail("test should throw an exception"); - } catch (ApexException ade) { - assertEquals("could not deploy apex model, deployer is not initialized", ade.getMessage()); - } - - try { - deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", false, false); - fail("test should throw an exception"); - } catch (ApexException ade) { - assertEquals("could not deploy apex model, deployer is not initialized", ade.getMessage()); - } + assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", + false, false)) + .hasMessage("could not deploy apex model, deployer is not initialized"); + assertThatThrownBy(() -> deployer.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", + false, false)) + .hasMessage("could not deploy apex model, deployer is not initialized"); deployer.close(); } @@ -193,13 +153,8 @@ public class BatchDeployerTest { final AxPolicyModel apexPolicyModel = modelReader .read(new FileInputStream(new File("src/test/resources/models/SmallModel.json"))); - try { - deployer.deployModel(apexPolicyModel, false, false); - fail("test should throw an exception"); - } catch (ApexException ade) { - assertEquals("failed response Operation failed received from serverlocalhost:12345", ade.getMessage()); - } - + assertThatThrownBy(() -> deployer.deployModel(apexPolicyModel, false, false)) + .hasMessage("failed response Operation failed received from serverlocalhost:12345"); deployer.close(); } } diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java index ddbcf2176..96b553a30 100644 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java +++ b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/DeploymentClientTest.java @@ -6,26 +6,26 @@ * 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.core.deployment; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Matchers.anyObject; import java.lang.reflect.Field; @@ -76,9 +76,9 @@ public class DeploymentClientTest { Mockito.doNothing().when(mockService).addMessageListener(messageListener.capture()); Mockito.doNothing().when(mockService).startConnection(); - + Mockito.doNothing().when(mockService).send((MessageHolder<Message>) anyObject()); - + Thread clientThread = new Thread(deploymentClient); clientThread.start(); @@ -86,7 +86,7 @@ public class DeploymentClientTest { assertTrue(deploymentClient.isStarted()); assertTrue(clientThread.isAlive()); - + AxArtifactKey engineKey = new AxArtifactKey("MyEngine", "0.0.1"); GetEngineStatus getEngineStatus = new GetEngineStatus(engineKey); deploymentClient.sendMessage(new GetEngineStatus(engineKey)); @@ -94,20 +94,16 @@ public class DeploymentClientTest { Response response = new Response(engineKey, true, getEngineStatus); List<Message> messageList = new ArrayList<>(); messageList.add(response); - + MessageBlock<Message> responseBlock = new MessageBlock<>(messageList, null); messageListener.getValue().onMessage(responseBlock); - - try { - messageListener.getValue().onMessage("StringMessage"); - fail("test should throw an exception here"); - } catch (UnsupportedOperationException use) { - assertEquals("String mesages are not supported on the EngDep protocol", use.getMessage()); - } + + assertThatThrownBy(() -> messageListener.getValue().onMessage("StringMessage")) + .hasMessage("String mesages are not supported on the EngDep protocol"); await().atMost(300, TimeUnit.MILLISECONDS).until(() -> deploymentClient.getMessagesReceived() == 2); assertEquals(2, deploymentClient.getMessagesReceived()); - + deploymentClient.stopClient(); } diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java index fb2ef4459..6e0826c3f 100644 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java +++ b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/EngineServiceFacadeTest.java @@ -21,9 +21,9 @@ package org.onap.policy.apex.core.deployment; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -43,23 +43,15 @@ public class EngineServiceFacadeTest { // First init should fail due to our dummy client dummyDeploymentClient.setInitSuccessful(false); - try { - facade.init(); - fail("could not handshake with server localhost:51273"); - } catch (final Exception ade) { - assertEquals("could not handshake with server localhost:51273", ade.getMessage()); - } - + assertThatThrownBy(facade::init) + .hasMessage("could not handshake with server localhost:51273"); assertNull(facade.getKey()); assertNull(facade.getApexModelKey()); assertNull(facade.getEngineKeyArray()); - try { - facade.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("could not deploy apex model, deployer is not initialized", ade.getMessage()); - } + assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/SamplePolicyModelJAVASCRIPT.json", + false, false)) + .hasMessage("could not deploy apex model, deployer is not initialized"); // Second init should work dummyDeploymentClient.setInitSuccessful(true); @@ -69,126 +61,78 @@ public class EngineServiceFacadeTest { assertEquals("Model:0.0.1", facade.getApexModelKey().getId()); assertEquals("Engine:0.0.1", facade.getEngineKeyArray()[0].getId()); - try { - facade.deployModel("src/test/resources/models/NonExistantModel.json", false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("could not create apex model, could not read from file " - + "src/test/resources/models/NonExistantModel.json", ade.getMessage()); - } - - try { - facade.deployModel("src/test/resources/models/JunkModel.json", false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("could not deploy apex model from src/test/resources/models/JunkModel.json", ade.getMessage()); - } + assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/NonExistantModel.json", + false, false)) + .hasMessage("could not create apex model, could not read from file " + + "src/test/resources/models/NonExistantModel.json"); + assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/JunkModel.json", + false, false)) + .hasMessage("could not deploy apex model from src/test/resources/models/JunkModel.json"); InputStream badStream = new ByteArrayInputStream("".getBytes()); - try { - facade.deployModel("MyModel", badStream, false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("format of input for Apex concept is neither JSON nor XML", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.deployModel("MyModel", badStream, false, false)) + .hasMessage("format of input for Apex concept is neither JSON nor XML"); InputStream closedStream = new ByteArrayInputStream("".getBytes()); closedStream.close(); - try { - facade.deployModel("MyModel", closedStream, false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("format of input for Apex concept is neither JSON nor XML", ade.getMessage()); - } - - try { - facade.deployModel("src/test/resources/models/SmallModel.json", false, false); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("could not deploy apex model from src/test/resources/models/SmallModel.json", - ade.getMessage()); - } + assertThatThrownBy(() -> facade.deployModel("MyModel", closedStream, false, false)) + .hasMessage("format of input for Apex concept is neither JSON nor XML"); + assertThatThrownBy(() -> facade.deployModel("src/test/resources/models/SmallModel.json", false, false)) + .hasMessage("could not deploy apex model from src/test/resources/models/SmallModel.json"); facade.deployModel("src/test/resources/models/SmallModel.json", false, false); - try { - facade.startEngine(facade.getEngineKeyArray()[0]); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.startEngine(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.startEngine(facade.getEngineKeyArray()[0]); - try { - facade.stopEngine(facade.getEngineKeyArray()[0]); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.stopEngine(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.stopEngine(facade.getEngineKeyArray()[0]); - try { - facade.startPerioidicEvents(facade.getEngineKeyArray()[0], 1000); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.startPerioidicEvents(facade.getEngineKeyArray()[0], 1000)) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.startPerioidicEvents(facade.getEngineKeyArray()[0], 1000); - try { - facade.stopPerioidicEvents(facade.getEngineKeyArray()[0]); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.stopPerioidicEvents(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.stopPerioidicEvents(facade.getEngineKeyArray()[0]); - try { - facade.getEngineStatus(facade.getEngineKeyArray()[0]); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.getEngineStatus(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.getEngineStatus(facade.getEngineKeyArray()[0]); - try { - facade.getEngineInfo(facade.getEngineKeyArray()[0]); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("failed response Operation failed received from serverlocalhost:51273", ade.getMessage()); - } - + assertThatThrownBy(() -> facade.getEngineInfo(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); facade.getEngineInfo(facade.getEngineKeyArray()[0]); - try { - facade.getEngineStatus(new AxArtifactKey("ReturnBadMessage", "0.0.1")); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("response received from server is of incorrect type " + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadMessage", "0.0.1"))) + .hasMessage("response received from server is of incorrect type " + "org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus, should be of type " - + "org.onap.policy.apex.core.protocols.engdep.messages.Response", ade.getMessage()); - } - - try { - facade.getEngineStatus(new AxArtifactKey("ReturnBadResponse", "0.0.1")); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("response received is not correct response to sent message GET_ENGINE_STATUS", - ade.getMessage()); - } - - try { - facade.getEngineStatus(new AxArtifactKey("DoNotRespond", "0.0.1")); - fail("test should throw an exception here"); - } catch (final Exception ade) { - assertEquals("no response received to sent message GET_ENGINE_STATUS", ade.getMessage()); - } + + "org.onap.policy.apex.core.protocols.engdep.messages.Response"); + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadResponse", "0.0.1"))) + .hasMessage("response received is not correct response to sent message GET_ENGINE_STATUS"); + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("DoNotRespond", "0.0.1"))) + .hasMessage("no response received to sent message GET_ENGINE_STATUS"); + assertThatThrownBy(() -> facade.stopPerioidicEvents(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); + + facade.stopPerioidicEvents(facade.getEngineKeyArray()[0]); + + facade.getEngineStatus(facade.getEngineKeyArray()[0]); + + assertThatThrownBy(() -> facade.getEngineInfo(facade.getEngineKeyArray()[0])) + .hasMessage("failed response Operation failed received from serverlocalhost:51273"); + + facade.getEngineInfo(facade.getEngineKeyArray()[0]); + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadMessage", "0.0.1"))) + .hasMessage("response received from server is of incorrect type " + + "org.onap.policy.apex.core.protocols.engdep.messages.GetEngineStatus, should be of type " + + "org.onap.policy.apex.core.protocols.engdep.messages.Response"); + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("ReturnBadResponse", "0.0.1"))) + .hasMessage("response received is not correct response to sent message GET_ENGINE_STATUS"); + assertThatThrownBy(() -> facade.getEngineStatus(new AxArtifactKey("DoNotRespond", "0.0.1"))) + .hasMessage("no response received to sent message GET_ENGINE_STATUS"); facade.close(); } } diff --git a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java index 3444eb7fd..99c95465f 100644 --- a/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java +++ b/core/core-deployment/src/test/java/org/onap/policy/apex/core/deployment/PeriodicEventManagerTest.java @@ -21,9 +21,8 @@ package org.onap.policy.apex.core.deployment; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -37,26 +36,18 @@ import org.junit.Test; public class PeriodicEventManagerTest { @Test public void testPeroidicEventManagerBad() { - try { - final String[] eventArgs = { "-h" }; + final String[] eventArgs = { "-h" }; - PeriodicEventManager.main(eventArgs); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("invalid arguments: [-h]", exc.getMessage().substring(0, 23)); - } + assertThatThrownBy(() -> PeriodicEventManager.main(eventArgs)) + .hasMessageContaining("invalid arguments: [-h]"); } @Test public void testPeroidicEventManagerOk() { - try { - final String[] eventArgs = { "Host", "43443", "start", "1000" }; + final String[] eventArgs = { "Host", "43443", "start", "1000" }; - PeriodicEventManager.main(eventArgs); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("periodic event setting failed on parameters Host 43443 true", exc.getMessage()); - } + assertThatThrownBy(() -> PeriodicEventManager.main(eventArgs)) + .hasMessage("periodic event setting failed on parameters Host 43443 true"); } @Test @@ -107,54 +98,31 @@ public class PeriodicEventManagerTest { } @Test - public void testPeroidicEventManagerStart() { + public void testPeroidicEventManagerStart() throws ApexDeploymentException { final String[] eventArgs = { "localhost", "12345", "start", "1000" }; final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); PeriodicEventManager peManager = null; final DummyDeploymentClient dummyDeploymentClient = new DummyDeploymentClient("aHost", 54553); - try { - peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); - peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); - } catch (ApexDeploymentException ade) { - fail("test should not throw an exception"); - } + peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); + peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); dummyDeploymentClient.setInitSuccessful(false); - try { - peManager.init(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("periodic event setting failed on parameters localhost 12345 true", ade.getMessage()); - } - + assertThatThrownBy(peManager::init) + .hasMessage("periodic event setting failed on parameters localhost 12345 true"); dummyDeploymentClient.setInitSuccessful(true); - try { - peManager.init(); - } catch (ApexDeploymentException ade) { - ade.printStackTrace(); - fail("test should not throw an exception"); - } - - try { - peManager.runCommand(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("failed response Operation failed received from serverlocalhost:12345", ade.getMessage()); - } + peManager.init(); - try { - peManager.runCommand(); - } catch (ApexDeploymentException ade) { - fail("test should not throw an exception"); - } + assertThatThrownBy(peManager::runCommand) + .hasMessage("failed response Operation failed received from serverlocalhost:12345"); peManager.close(); } @Test public void testPeroidicEventManagerStop() throws ApexDeploymentException { + final String[] eventArgs = { "localhost", "12345", "stop", "1000" }; final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); @@ -165,23 +133,13 @@ public class PeriodicEventManagerTest { peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); dummyDeploymentClient.setInitSuccessful(false); - try { - peManager.init(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("periodic event setting failed on parameters localhost 12345 false", ade.getMessage()); - } - + assertThatThrownBy(peManager::init) + .hasMessage("periodic event setting failed on parameters localhost 12345 false"); dummyDeploymentClient.setInitSuccessful(true); peManager.init(); - try { - peManager.runCommand(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("failed response Operation failed received from serverlocalhost:12345", ade.getMessage()); - } - + assertThatThrownBy(peManager::runCommand) + .hasMessage("failed response Operation failed received from serverlocalhost:12345"); peManager.runCommand(); peManager.close(); @@ -189,6 +147,7 @@ public class PeriodicEventManagerTest { @Test public void testPeroidicEventManagerStartUninitialized() throws ApexDeploymentException { + final String[] eventArgs = { "localhost", "12345", "start", "1000" }; final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); @@ -199,26 +158,18 @@ public class PeriodicEventManagerTest { peManager.getEngineServiceFacade().setDeploymentClient(dummyDeploymentClient); dummyDeploymentClient.setInitSuccessful(false); - try { - peManager.runCommand(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("connection to apex is not initialized", ade.getMessage()); - } - + assertThatThrownBy(peManager::runCommand) + .hasMessage("connection to apex is not initialized"); dummyDeploymentClient.setInitSuccessful(true); - try { - peManager.runCommand(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("connection to apex is not initialized", ade.getMessage()); - } + assertThatThrownBy(peManager::runCommand) + .hasMessage("connection to apex is not initialized"); peManager.close(); } @Test public void testPeroidicEventManagerStopUninitialized() throws ApexDeploymentException { + final String[] eventArgs = { "localhost", "12345", "stop", "1000" }; final ByteArrayOutputStream baosOut = new ByteArrayOutputStream(); @@ -227,13 +178,8 @@ public class PeriodicEventManagerTest { peManager = new PeriodicEventManager(eventArgs, new PrintStream(baosOut, true)); peManager.getEngineServiceFacade().setDeploymentClient(new DummyDeploymentClient("aHost", 54553)); - try { - peManager.runCommand(); - fail("test should throw an exception"); - } catch (ApexDeploymentException ade) { - assertEquals("connection to apex is not initialized", ade.getMessage()); - } - + assertThatThrownBy(peManager::runCommand) + .hasMessage("connection to apex is not initialized"); peManager.close(); } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/context/ApexInternalContextTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/context/ApexInternalContextTest.java index 3d0d377bf..19828f6e2 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/context/ApexInternalContextTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/context/ApexInternalContextTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ package org.onap.policy.apex.core.engine.context; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.junit.After; import org.junit.Before; @@ -128,13 +127,8 @@ public class ApexInternalContextTest { @Test public void testAlbumInit() throws ContextException { - try { - new ApexInternalContext(null); - fail("test should throw an exception"); - } catch (ContextException ce) { - assertEquals("internal context update failed, supplied model is null", ce.getMessage()); - } - + assertThatThrownBy(() -> new ApexInternalContext(null)) + .hasMessage("internal context update failed, supplied model is null"); ApexInternalContext context = new ApexInternalContext(policyModel); assertEquals(policyModel.getKey(), context.getKey()); diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java index b066e45c1..e539750e6 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/engine/impl/ApexEngineImplTest.java @@ -28,7 +28,6 @@ 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 java.io.IOException; import java.lang.reflect.Field; @@ -175,10 +174,10 @@ public class ApexEngineImplTest { assertNotNull(engine); assertEquals(engineKey, engine.getKey()); - assertThatThrownBy(() -> engine.start()).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, " + assertThatThrownBy(engine::start).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, " + "engine has not been initialized, its model is not loaded"); - assertThatThrownBy(() -> engine.stop()) + assertThatThrownBy(engine::stop) .hasMessage("stop()<-Engine:0.0.1,STOPPED, cannot stop engine, " + "engine is already stopped"); assertEquals(AxEngineState.STOPPED, engine.getState()); @@ -222,10 +221,10 @@ public class ApexEngineImplTest { engine.start(); assertEquals(AxEngineState.READY, engine.getState()); - assertThatThrownBy(() -> engine.start()) + assertThatThrownBy(engine::start) .hasMessage("start()<-Engine:0.0.1,READY, cannot start engine, engine not in state STOPPED"); - assertThatThrownBy(() -> engine.clear()) + assertThatThrownBy(engine::clear) .hasMessage("clear()<-Engine:0.0.1,READY, cannot clear engine, engine is not stopped"); engine.stop(); @@ -234,7 +233,7 @@ public class ApexEngineImplTest { engine.clear(); assertEquals(AxEngineState.STOPPED, engine.getState()); - assertThatThrownBy(() -> engine.start()).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, " + assertThatThrownBy(engine::start).hasMessage("start()<-Engine:0.0.1,STOPPED, cannot start engine, " + "engine has not been initialized, its model is not loaded"); engine.updateModel(policyModel, false); @@ -320,19 +319,11 @@ public class ApexEngineImplTest { assertFalse(engine.handleEvent(event)); assertNotNull(engine.createEvent(eventKey)); - try { - engine.stop(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } + engine.stop(); + assertEquals(AxEngineState.STOPPED, engine.getState()); - try { - engine.start(); - assertEquals(AxEngineState.READY, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } + engine.start(); + assertEquals(AxEngineState.READY, engine.getState()); // 4 seconds is more than the 3 second wait on engine stopping slowListener.setWaitTime(4000); @@ -346,20 +337,11 @@ public class ApexEngineImplTest { await().atLeast(50, TimeUnit.MILLISECONDS).until(() -> engine.getState().equals(AxEngineState.EXECUTING)); assertEquals(AxEngineState.EXECUTING, engine.getState()); - try { - engine.stop(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - fail("test should throw an exception"); - } catch (ApexException ae) { - assertEquals("stop()<-Engine:0.0.1,STOPPED, error stopping engine, engine stop timed out", ae.getMessage()); - } - - try { - engine.clear(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException e) { - fail("test should not throw an exception"); - } + assertThatThrownBy(engine::stop) + .hasMessage("stop()<-Engine:0.0.1,STOPPED, error stopping engine, engine stop timed out"); + assertEquals(AxEngineState.STOPPED, engine.getState()); + engine.clear(); + assertEquals(AxEngineState.STOPPED, engine.getState()); } @Test @@ -390,32 +372,16 @@ public class ApexEngineImplTest { assertFalse(engine.handleEvent(event)); assertEquals(AxEngineState.READY, engine.getState()); - try { - engine.stop(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } - - try { - Mockito.doThrow(new StateMachineException("mocked state machine exception", - new IOException("nexted exception"))).when(smHandlerMock).start(); - - engine.start(); - fail("test should throw an exception"); - } catch (ApexException ae) { - assertEquals("updateModel()<-Engine:0.0.1, error starting the engine state machines \"Engine:0.0.1\"", - ae.getMessage()); - } - + engine.stop(); + assertEquals(AxEngineState.STOPPED, engine.getState()); + Mockito.doThrow(new StateMachineException("mocked state machine exception", + new IOException("nexted exception"))).when(smHandlerMock).start(); + assertThatThrownBy(engine::start).hasMessage("updateModel()<-Engine:0.0.1, error starting the engine state " + + "machines \"Engine:0.0.1\""); assertEquals(AxEngineState.STOPPED, engine.getState()); - try { - engine.clear(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException e) { - fail("test should not throw an exception"); - } + engine.clear(); + assertEquals(AxEngineState.STOPPED, engine.getState()); } @Test @@ -463,54 +429,28 @@ public class ApexEngineImplTest { assertEquals(1, smExMap.size()); DummySmExecutor dummyExecutor = new DummySmExecutor(null, event.getKey()); smExMap.put(event.getAxEvent(), dummyExecutor); - - try { - ApexInternalContext internalContext = new ApexInternalContext(policyModelWithStates); - dummyExecutor.setContext(null, null, internalContext); - } catch (Exception e) { - // Ignore this exception, we just need to set the internal context - } - - try { - engine.stop(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } - - try { - engine.start(); - fail("test should throw an exception"); - } catch (ApexException ae) { - assertEquals("updateModel()<-Engine:0.0.1, error starting the engine state machines \"Engine:0.0.1\"", - ae.getMessage()); - } + ApexInternalContext internalContext = new ApexInternalContext(policyModelWithStates); + assertThatThrownBy(() -> dummyExecutor.setContext(null, null, internalContext)) + .isInstanceOf(NullPointerException.class); + + engine.stop(); + assertEquals(AxEngineState.STOPPED, engine.getState()); + assertThatThrownBy(engine::start).hasMessageContaining("updateModel()<-Engine:0.0.1, error starting the " + + "engine state machines \"Engine:0.0.1\""); assertEquals(AxEngineState.STOPPED, engine.getState()); - try { - engine.start(); - assertEquals(AxEngineState.READY, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } + engine.start(); + assertEquals(AxEngineState.READY, engine.getState()); // Works, Dummy executor fakes event execution assertTrue(engine.handleEvent(event)); assertEquals(AxEngineState.READY, engine.getState()); - try { - engine.stop(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException ae) { - fail("test should not throw an exception"); - } - - try { - engine.clear(); - assertEquals(AxEngineState.STOPPED, engine.getState()); - } catch (ApexException e) { - fail("test should not throw an exception"); - } + engine.stop(); + assertEquals(AxEngineState.STOPPED, engine.getState()); + + engine.clear(); + assertEquals(AxEngineState.STOPPED, engine.getState()); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnEventTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnEventTest.java index 225e1853f..6ac0d2e33 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnEventTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnEventTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. - * Modifications Copyright (C) 2020 Nordix Foundation. + * Modifications Copyright (C) 2020 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,12 @@ package org.onap.policy.apex.core.engine.event; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; 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 java.util.HashMap; import java.util.LinkedHashMap; @@ -34,7 +34,6 @@ import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.onap.policy.apex.context.ContextRuntimeException; import org.onap.policy.apex.context.parameters.ContextParameterConstants; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; @@ -75,20 +74,10 @@ public class EnEventTest { @Test public void testEnEvent() { AxArtifactKey eventKey = new AxArtifactKey("Event:0.0.1"); - try { - new EnEvent(eventKey); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("event definition is null or was not found in model service", ee.getMessage()); - } - - try { - new EnEvent((AxEvent) null); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("event definition is null or was not found in model service", ee.getMessage()); - } - + assertThatThrownBy(() -> new EnEvent(eventKey)) + .hasMessage("event definition is null or was not found in model service"); + assertThatThrownBy(() -> new EnEvent((AxEvent) null)) + .hasMessage("event definition is null or was not found in model service"); AxEvent axEvent = new AxEvent(eventKey, "a.name.space", "some source", "some target"); ModelService.getModel(AxEvents.class).getEventMap().put(eventKey, axEvent); @@ -108,20 +97,10 @@ public class EnEventTest { assertEquals("EnEvent [axEvent=AxEvent:(key=AxArtifactKey:(name=Event,version=0.0.1),nameSpace=a.name.space," + "source=some source,target=some target,parameter={}), " + "userArtifactStack=[AxArtifactKey:(name=Event,version=0.0.1)], map={}]", event.toString()); - try { - event.put(null, null); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("null keys are illegal on method parameter \"key\"", ee.getMessage()); - } - - try { - event.put("NonField", null); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("parameter with key \"NonField\" not defined on event \"Event\"", ee.getMessage()); - } - + assertThatThrownBy(() -> event.put(null, null)) + .hasMessage("null keys are illegal on method parameter \"key\""); + assertThatThrownBy(() -> event.put("NonField", null)) + .hasMessage("parameter with key \"NonField\" not defined on event \"Event\""); AxReferenceKey fieldKey = new AxReferenceKey("Parent", "0.0.1", "MyParent", "MyField"); AxArtifactKey fieldSchemaKey = new AxArtifactKey("FieldSchema:0.0.1"); AxField axField = new AxField(fieldKey, fieldSchemaKey); @@ -137,21 +116,12 @@ public class EnEventTest { parameterMap.put("MyField", axField); ModelService.getModel(AxEvents.class).get(eventKey).setParameterMap(parameterMap); - try { - event.put("MyField", null); - } catch (ContextRuntimeException cre) { - fail("test should throw an exception here"); - } + event.put("MyField", null); assertNull(event.get("MyField")); - try { - event.put("MyField", "Hello"); - fail("test should throw an exception here"); - } catch (ContextRuntimeException cre) { - assertEquals("Parent:0.0.1:MyParent:MyField: object \"Hello\" of class \"java.lang.String\" " - + "not compatible with class \"java.lang.Integer\"", cre.getMessage()); - } - + assertThatThrownBy(() -> event.put("MyField", "Hello")) + .hasMessage("Parent:0.0.1:MyParent:MyField: object \"Hello\" of class \"java.lang.String\" " + + "not compatible with class \"java.lang.Integer\""); event.put("MyField", 123); assertEquals(123, event.get("MyField")); @@ -161,34 +131,14 @@ public class EnEventTest { event.putAll(event); - try { - event.get(null); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("null values are illegal on method parameter \"key\"", ee.getMessage()); - } - - try { - event.get("NonField"); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("parameter with key NonField not defined on this event", ee.getMessage()); - } - - try { - event.remove(null); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("null keys are illegal on method parameter \"key\"", ee.getMessage()); - } - - try { - event.remove("NonField"); - fail("test should throw an exception here"); - } catch (EnException ee) { - assertEquals("parameter with key NonField not defined on this event", ee.getMessage()); - } - + assertThatThrownBy(() -> event.get(null)) + .hasMessage("null values are illegal on method parameter \"key\""); + assertThatThrownBy(() -> event.get("NonField")) + .hasMessage("parameter with key NonField not defined on this event"); + assertThatThrownBy(() -> event.remove(null)) + .hasMessage("null keys are illegal on method parameter \"key\""); + assertThatThrownBy(() -> event.remove("NonField")) + .hasMessage("parameter with key NonField not defined on this event"); event.remove("MyField"); assertNull(event.get("MyField")); diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnFieldTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnFieldTest.java index 9fd26f191..168ab1d78 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnFieldTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/event/EnFieldTest.java @@ -1,25 +1,27 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 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.core.engine.event; +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; @@ -67,14 +69,9 @@ public class EnFieldTest { AxArtifactKey fieldSchemaKey = new AxArtifactKey("FieldSchema:0.0.1"); AxField axField = new AxField(fieldKey, fieldSchemaKey); - try { - new EnField(axField, null); - fail("test should throw an exception"); - } catch (EnException ee) { - assertEquals("schema helper cannot be created for parameter with key \"Parent:0.0.1:MyParent:MyField\" " - + "with schema \"AxArtifactKey:(name=FieldSchema,version=0.0.1)\"", ee.getMessage()); - } - + assertThatThrownBy(() -> new EnField(axField, null)) + .hasMessage("schema helper cannot be created for parameter with key \"Parent:0.0.1:MyParent:My" + + "Field\" with schema \"AxArtifactKey:(name=FieldSchema,version=0.0.1)\""); AxContextSchema schema = new AxContextSchema(fieldSchemaKey, "Java", "java.lang.Integer"); ModelService.getModel(AxContextSchemas.class).getSchemasMap().put(fieldSchemaKey, schema); EnField field = new EnField(axField, 123); diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateExecutorTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateExecutorTest.java index ed5f9135c..f3e12cc1f 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateExecutorTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateExecutorTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +21,8 @@ package org.onap.policy.apex.core.engine.executor; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; @@ -79,18 +80,9 @@ public class StateExecutorTest { executor.setNext(null); assertEquals(null, executor.getNext()); - try { - executor.executePre(0, null, null); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execution pre work not implemented on class", ex.getMessage()); - } - - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execution post work not implemented on class", ex.getMessage()); - } + assertThatThrownBy(() -> executor.executePre(0, null, null)) + .hasMessage("execution pre work not implemented on class"); + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessage("execution post work not implemented on class"); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutorTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutorTest.java index 30c7403ce..8f6544497 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutorTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateFinalizerExecutorTest.java @@ -23,7 +23,6 @@ package org.onap.policy.apex.core.engine.executor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.util.Map; import java.util.Properties; @@ -32,6 +31,7 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.core.engine.ExecutorParameters; import org.onap.policy.apex.core.engine.context.ApexInternalContext; import org.onap.policy.apex.core.engine.event.EnEvent; @@ -75,7 +75,7 @@ public class StateFinalizerExecutorTest { } @Test - public void testStateFinalizerExecutor() { + public void testStateFinalizerExecutor() throws StateMachineException, ContextException { DummyStateFinalizerExecutor executor = new DummyStateFinalizerExecutor(); executor.setContext(parentMock, stateFinalizerLogicMock, internalContextMock); @@ -94,112 +94,46 @@ public class StateFinalizerExecutorTest { executor.setNext(null); assertEquals(null, executor.getNext()); - try { - executor.cleanUp(); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("cleanUp() not implemented on class", ex.getMessage()); - } - + assertThatThrownBy(executor::cleanUp) + .hasMessage("cleanUp() not implemented on class"); Mockito.doReturn(null).when(stateFinalizerLogicMock).getLogic(); - try { - executor.prepare(); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("state finalizer logic cannot be null.", ex.getMessage()); - } - + assertThatThrownBy(executor::prepare) + .hasMessage("state finalizer logic cannot be null."); Mockito.doReturn("some task logic").when(stateFinalizerLogicMock).getLogic(); - try { - executor.prepare(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception ex) { - assertEquals("task input fields \"[InField0]\" are missing for task \"Task0:0.0.1\"", ex.getMessage()); - } + executor.prepare(); + executor.executePre(0, new Properties(), incomingEvent); assertThatThrownBy(() -> executor.executePre(0, null, incomingEvent)) .hasMessageMatching("^executionProperties is marked .*on.*ull but is null$"); - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - try { - executor.execute(0, new Properties(), incomingEvent); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute() not implemented on abstract StateFinalizerExecutionContext class, " - + "only on its subclasses", ex.getMessage()); - } - - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute-post: state finalizer logic execution failure on state \"NULL:0.0.0:NULL:NULL\" " - + "on finalizer logic null", ex.getMessage()); - } + executor.executePre(0, new Properties(), incomingEvent); + assertThatThrownBy(() -> executor.execute(0, new Properties(), incomingEvent)) + .hasMessage("execute() not implemented on abstract StateFinalizerExecutionContext class, " + + "only on its subclasses"); + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessage("execute-post: state finalizer logic execution failure on state \"NULL:0.0.0:" + + "NULL:NULL\" on finalizer logic null"); executor.getExecutionContext().setMessage("Execution message"); - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute-post: state finalizer logic execution failure on state \"NULL:0.0.0:NULL:NULL\" " - + "on finalizer logic null, user message: Execution message", ex.getMessage()); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception ex) { - fail("test should not throw an exception"); - } - - try { - executor.executePost(true); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute-post: state finalizer logic \"null\" did not select an output state", - ex.getMessage()); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessage("execute-post: state finalizer logic execution failure on state \"NULL:0.0.0:" + + "NULL:NULL\" on finalizer logic null, user message: Execution message"); + executor.executePre(0, new Properties(), incomingEvent); + + assertThatThrownBy(() -> executor.executePost(true)) + .hasMessage("execute-post: state finalizer logic \"null\" did not select an output state"); + executor.executePre(0, new Properties(), incomingEvent); executor.getExecutionContext().setSelectedStateOutputName("ThisOutputDoesNotExist"); - try { - executor.executePost(true); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals( - "execute-post: state finalizer logic \"null\" selected output state " - + "\"ThisOutputDoesNotExist\" that does not exsist on state \"NULL:0.0.0:NULL:NULL\"", - ex.getMessage()); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> executor.executePost(true)) + .hasMessage("execute-post: state finalizer logic \"null\" selected output state " + + "\"ThisOutputDoesNotExist\" that does not exsist on state \"NULL:0.0.0:NULL:NULL\""); + executor.executePre(0, new Properties(), incomingEvent); executor.getExecutionContext().setSelectedStateOutputName("ValidOutput"); - try { - executor.executePost(true); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.executePost(true); + } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutorTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutorTest.java index d968691f6..2acb57681 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutorTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/StateMachineExecutorTest.java @@ -21,10 +21,9 @@ package org.onap.policy.apex.core.engine.executor; +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.Assert.fail; import java.util.LinkedHashMap; import java.util.Map; @@ -34,10 +33,12 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.policy.apex.context.ContextException; import org.onap.policy.apex.context.parameters.SchemaParameters; import org.onap.policy.apex.core.engine.ExecutorParameters; import org.onap.policy.apex.core.engine.context.ApexInternalContext; import org.onap.policy.apex.core.engine.event.EnEvent; +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.basicmodel.concepts.AxReferenceKey; import org.onap.policy.apex.model.basicmodel.service.ModelService; @@ -182,17 +183,12 @@ public class StateMachineExecutorTest { } @Test - public void testStateMachineExecutor() { + public void testStateMachineExecutor() throws StateMachineException, ContextException { StateMachineExecutor executor = new StateMachineExecutor(executorFactoryMock, new AxArtifactKey("OwnerKey:0.0.1")); - try { - executor.execute(0, null, incomingEventMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("no states defined on state machine", ex.getMessage()); - } - + assertThatThrownBy(() -> executor.execute(0, null, incomingEventMock)) + .hasMessage("no states defined on state machine"); executor.setContext(null, axPolicy, internalContextMock); assertEquals("Policy:0.0.1", executor.getKey().getId()); assertEquals(null, executor.getParent()); @@ -208,213 +204,109 @@ public class StateMachineExecutorTest { executor.setNext(null); assertEquals(null, executor.getNext()); - try { - executor.executePre(0, null, null); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execution pre work not implemented on class", ex.getMessage()); - } - - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execution post work not implemented on class", ex.getMessage()); - } - - try { - executor.prepare(); - fail("test should throw an exception"); - } catch (Exception e) { - assertTrue(e instanceof NullPointerException); - } - + assertThatThrownBy(() -> executor.executePre(0, null, null)) + .hasMessage("execution pre work not implemented on class"); + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessage("execution post work not implemented on class"); + assertThatThrownBy(executor::prepare) + .isInstanceOf(NullPointerException.class); axPolicy.setFirstState("BadState"); executor.setContext(null, axPolicy, internalContextMock); - try { - executor.execute(0, null, incomingEventMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("first state not defined on state machine", ex.getMessage()); - } - + assertThatThrownBy(() -> executor.execute(0, null, incomingEventMock)) + .hasMessage("first state not defined on state machine"); axPolicy.setFirstState("state0"); executor.setContext(null, axPolicy, internalContextMock); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); AxReferenceKey badStateKey = new AxReferenceKey("Policy:0.0.1:PName:BadState"); axPolicy.getStateMap().get("State1").getStateOutputs().get("stateOutput1").setNextState(badStateKey); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("state execution failed, next state \"Policy:0.0.1:PName:BadState\" not found", - ex.getMessage()); - } - + assertThatThrownBy(() -> executor.execute(0, null, incomingEventMock)) + .hasMessage("state execution failed, next state \"Policy:0.0.1:PName:BadState\" not found"); axPolicy.getStateMap().get("State1").getStateOutputs().get("stateOutput1") .setNextState(AxReferenceKey.getNullKey()); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); axPolicy.getStateMap().get("State1").setTrigger(new AxArtifactKey("BadTrigger:0.0.1")); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("incoming event \"Event1:0.0.1\" does not match trigger \"BadTrigger:0.0.1\" " - + "of state \"Policy:0.0.1:NULL:state1\"", ex.getMessage()); - } - + assertThatThrownBy(() -> executor.execute(0, null, incomingEventMock)) + .hasMessage("incoming event \"Event1:0.0.1\" does not match trigger \"BadTrigger:0.0.1\" " + + "of state \"Policy:0.0.1:NULL:state1\""); axPolicy.getStateMap().get("State1").setTrigger(new AxArtifactKey("Event1:0.0.1")); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); AxStateFinalizerLogic savedSfl = axPolicy.getStateMap().get("State1").getStateFinalizerLogicMap().get("sfl"); axPolicy.getStateMap().get("State1").getStateFinalizerLogicMap().put("sfl", null); - try { - executor.setContext(null, axPolicy, internalContextMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("state finalizer logic on task reference " + assertThatThrownBy(() -> executor.setContext(null, axPolicy, internalContextMock)) + .hasMessage("state finalizer logic on task reference " + "\"AxStateTaskReference:(stateKey=AxReferenceKey:(parentKeyName=Policy," + "parentKeyVersion=0.0.1,parentLocalName=state1,localName=str1)," + "outputType=LOGIC,output=AxReferenceKey:(parentKeyName=Policy,parentKeyVersion=0.0.1," - + "parentLocalName=state1,localName=sfl))\" on state \"Policy:0.0.1:NULL:state1\" " + "does not exist", - ex.getMessage()); - } - + + "parentLocalName=state1,localName=sfl))\" on state \"Policy:0.0.1:NULL:state1\" " + "does not exist"); axPolicy.getStateMap().get("State1").getStateFinalizerLogicMap().put("sfl", savedSfl); executor.setContext(null, axPolicy, internalContextMock); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); AxArtifactKey task1Key = new AxArtifactKey("task1:0.0.1"); - try { - axPolicy.getStateMap().get("State1").getTaskReferences().get(task1Key) - .setStateTaskOutputType(AxStateTaskOutputType.UNDEFINED); - executor.setContext(null, axPolicy, internalContextMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("invalid state output type on task reference \"AxStateTaskReference:(stateKey=AxReferenceKey:" - + "(parentKeyName=Policy,parentKeyVersion=0.0.1,parentLocalName=state1,localName=str1)," + axPolicy.getStateMap().get("State1").getTaskReferences().get(task1Key) + .setStateTaskOutputType(AxStateTaskOutputType.UNDEFINED); + assertThatThrownBy(() -> executor.setContext(null, axPolicy, internalContextMock)) + .hasMessage("invalid state output type on task reference \"AxStateTaskReference:(stateKey" + + "=AxReferenceKey:(parentKeyName=Policy,parentKeyVersion=0.0.1,parentLocalName=state1,localName=str1)," + "outputType=UNDEFINED,output=AxReferenceKey:(parentKeyName=Policy," + "parentKeyVersion=0.0.1,parentLocalName=state1,localName=sfl))\" " - + "on state \"Policy:0.0.1:NULL:state1\"", ex.getMessage()); - } - + + "on state \"Policy:0.0.1:NULL:state1\""); axPolicy.getStateMap().get("State1").getTaskReferences().get(task1Key) .setStateTaskOutputType(AxStateTaskOutputType.LOGIC); executor.setContext(null, axPolicy, internalContextMock); dummyTsle.setTaskNo(0); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + executor.execute(0, null, incomingEventMock); dummyTsle.setTaskNo(0); dummySfle.setReturnBad(true); - try { - executor.execute(0, null, incomingEventMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("State execution of state \"Policy:0.0.1:NULL:state1\" on task \"task1:0.0.1\" failed: " - + "state output definition for state output \"stateOutputBad\" not found for " - + "state \"Policy:0.0.1:NULL:state1\"", ex.getMessage()); - } - + assertThatThrownBy(() -> executor.execute(0, null, incomingEventMock)) + .hasMessage("State execution of state \"Policy:0.0.1:NULL:state1\" on task \"task1:0.0.1\"" + + " failed: state output definition for state output \"stateOutputBad\" not found for " + + "state \"Policy:0.0.1:NULL:state1\""); dummyTsle.setTaskNo(0); dummySfle.setReturnBad(false); - try { - executor.execute(0, null, incomingEventMock); - } catch (Exception ex) { - fail("test should not throw an exception"); - } - - try { - executor.cleanUp(); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("cleanUp() not implemented on class", ex.getMessage()); - } + executor.execute(0, null, incomingEventMock); + + assertThatThrownBy(executor::cleanUp) + .hasMessage("cleanUp() not implemented on class"); } @Test - public void testStateOutput() { - StateOutput output = + public void testStateOutput() throws StateMachineException { + final StateOutput output = new StateOutput(axPolicy.getStateMap().get("State0").getStateOutputs().get("stateOutput0")); assertNotNull(output); assertEquals("stateOutput0", output.getStateOutputDefinition().getKey().getLocalName()); - try { - output.setEventFields(null, null); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("incomingFieldDefinitionMap may not be null", ex.getMessage()); - } - + assertThatThrownBy(() -> output.setEventFields(null, null)) + .hasMessage("incomingFieldDefinitionMap may not be null"); Map<String, AxField> incomingFieldDefinitionMap = new LinkedHashMap<>(); - try { - output.setEventFields(incomingFieldDefinitionMap, null); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("eventFieldMap may not be null", ex.getMessage()); - } - + assertThatThrownBy(() -> output.setEventFields(incomingFieldDefinitionMap, null)) + .hasMessage("eventFieldMap may not be null"); Map<String, Object> eventFieldMap = new LinkedHashMap<>(); - try { - output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); eventFieldMap.put("key", "Value"); - try { - output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("field definitions and values do not match for event Event1:0.0.1\n[]\n[key]", - ex.getMessage()); - } - + assertThatThrownBy(() -> output.setEventFields(incomingFieldDefinitionMap, eventFieldMap)) + .hasMessage("field definitions and values do not match for event Event1:0.0.1\n[]\n[key]"); AxField axBadFieldDefinition = new AxField(); incomingFieldDefinitionMap.put("key", axBadFieldDefinition); - try { - output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("field \"key\" does not exist on event \"Event1:0.0.1\"", ex.getMessage()); - } - + assertThatThrownBy(() -> output.setEventFields(incomingFieldDefinitionMap, eventFieldMap)) + .hasMessage("field \"key\" does not exist on event \"Event1:0.0.1\""); incomingFieldDefinitionMap.clear(); eventFieldMap.clear(); AxArtifactKey stringSchemaKey = new AxArtifactKey("StringSchema:0.0.1"); @@ -422,18 +314,15 @@ public class StateMachineExecutorTest { AxField event1Field0Definition = new AxField(fieldKey, stringSchemaKey); incomingFieldDefinitionMap.put("Event1Field0", event1Field0Definition); eventFieldMap.put("Event1Field0", "Value"); - try { - output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); - } catch (Exception ex) { - fail("test should not throw an exception"); - } + output.setEventFields(incomingFieldDefinitionMap, eventFieldMap); - output = new StateOutput(axPolicy.getStateMap().get("State0").getStateOutputs().get("stateOutput0")); + StateOutput outputCopy = new StateOutput(axPolicy.getStateMap().get("State0") + .getStateOutputs().get("stateOutput0")); EnEvent incomingEvent = new EnEvent(new AxArtifactKey("Event0:0.0.1")); - output.copyUnsetFields(incomingEvent); + outputCopy.copyUnsetFields(incomingEvent); incomingEvent.put("Event1Field0", "Hello"); - output.copyUnsetFields(incomingEvent); + outputCopy.copyUnsetFields(incomingEvent); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutorTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutorTest.java index edfbcf20f..613d1ae01 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutorTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/TaskSelectExecutorTest.java @@ -23,7 +23,6 @@ package org.onap.policy.apex.core.engine.executor; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import java.util.LinkedHashMap; import java.util.Map; @@ -85,7 +84,7 @@ public class TaskSelectExecutorTest { } @Test - public void testTaskSelectionExecutor() { + public void testTaskSelectionExecutor() throws StateMachineException { DummyTaskSelectExecutor executor = new DummyTaskSelectExecutor(); executor.setContext(null, axStateMock, internalContextMock); @@ -104,102 +103,44 @@ public class TaskSelectExecutorTest { executor.setNext(null); assertEquals(null, executor.getNext()); - try { - executor.cleanUp(); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("cleanUp() not implemented on class", ex.getMessage()); - } - + assertThatThrownBy(executor::cleanUp) + .hasMessage("cleanUp() not implemented on class"); Mockito.doReturn(null).when(taskSelectionLogicMock).getLogic(); - try { - executor.prepare(); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("task selection logic cannot be null.", ex.getMessage()); - } - + assertThatThrownBy(executor::prepare) + .hasMessage("task selection logic cannot be null."); Mockito.doReturn("some task logic").when(taskSelectionLogicMock).getLogic(); - try { - executor.prepare(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - try { - executor.execute(0, new Properties(), incomingEvent); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute() not implemented on class", ex.getMessage()); - } - - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute-post: task selection logic failed on state \"State0Parent:0.0.1:Parent:State0\"", - ex.getMessage()); - } + executor.prepare(); + + executor.executePre(0, new Properties(), incomingEvent); + + assertThatThrownBy(() -> executor.execute(0, new Properties(), incomingEvent)) + .hasMessage("execute() not implemented on class"); + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessage("execute-post: task selection logic failed on state \"State0Parent:0.0.1:Parent:State0\""); executor.getExecutionContext().setMessage("Execution message"); - try { - executor.executePost(false); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("execute-post: task selection logic failed on state \"State0Parent:0.0.1:Parent:State0\", " - + "user message: Execution message", ex.getMessage()); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - try { - executor.executePost(true); - assertEquals("Task1", executor.getOutgoing().getName()); - } catch (Exception e) { - fail("test should not throw an exception"); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception e) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> executor.executePost(false)) + .hasMessageContaining("execute-post: task selection logic failed on state \"" + + "State0Parent:0.0.1:Parent:State0\", user message: Execution message"); + executor.executePre(0, new Properties(), incomingEvent); + + executor.executePost(true); + assertEquals("Task1", executor.getOutgoing().getName()); + + executor.executePre(0, new Properties(), incomingEvent); executor.getOutgoing().setName("IDontExist"); - try { - executor.executePost(true); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("task \"IDontExist:0.0.0\" returned by task selection logic not defined " - + "on state \"State0Parent:0.0.1:Parent:State0\"", ex.getMessage()); - } - - try { - executor.executePre(0, new Properties(), incomingEvent); - } catch (Exception e) { - fail("test should not throw an exception"); - } + assertThatThrownBy(() -> executor.executePost(true)) + .hasMessageContaining("task \"IDontExist:0.0.0\" returned by task selection logic not defined " + + "on state \"State0Parent:0.0.1:Parent:State0\""); + executor.executePre(0, new Properties(), incomingEvent); executor.getOutgoing().setName("Task0"); - try { - executor.executePost(true); - assertEquals("Task0", executor.getOutgoing().getName()); - } catch (Exception e) { - fail("test should not throw an exception"); - } + executor.executePost(true); + assertEquals("Task0", executor.getOutgoing().getName()); assertThatThrownBy(() -> executor.executePre(0, null, incomingEvent)) .hasMessageMatching("^executionProperties is marked .*on.*ull but is null$"); diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacadeTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacadeTest.java index cfa43ecf6..8ef78efe9 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacadeTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/AxTaskFacadeTest.java @@ -1,28 +1,29 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 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.core.engine.executor.context; +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.fail; import java.util.LinkedHashMap; import java.util.Map; @@ -115,40 +116,20 @@ public class AxTaskFacadeTest { assertEquals("Task0", taskFacade.getTaskName()); assertEquals("Task0:0.0.1", taskFacade.getId()); - try { - taskFacade.getInFieldSchemaHelper("InFieldDoesntExist"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("no incoming field with name \"InFieldDoesntExist\" " + "defined on task \"Task0:0.0.1\"", - exc.getMessage()); - } - - try { - taskFacade.getOutFieldSchemaHelper("OutFieldDoesntExist"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("no outgoing field with name \"OutFieldDoesntExist\" " + "defined on task \"Task0:0.0.1\"", - exc.getMessage()); - } - + assertThatThrownBy(() -> taskFacade.getInFieldSchemaHelper("InFieldDoesntExist")) + .hasMessage("no incoming field with name \"InFieldDoesntExist\" " + "defined on task " + + "\"Task0:0.0.1\""); + assertThatThrownBy(() -> taskFacade.getOutFieldSchemaHelper("OutFieldDoesntExist")) + .hasMessage("no outgoing field with name \"OutFieldDoesntExist\" " + "defined on task " + + "\"Task0:0.0.1\""); assertNotNull(taskFacade.getInFieldSchemaHelper("InField0")); assertNotNull(taskFacade.getOutFieldSchemaHelper("OutField0")); - try { - taskFacade.getInFieldSchemaHelper("InFieldBad"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("schema helper cannot be created for task field \"InFieldBad\" " - + "with key \"null\" with schema \"null\"", exc.getMessage()); - } - - try { - taskFacade.getOutFieldSchemaHelper("OutFieldBad"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("schema helper cannot be created for task field \"OutFieldBad\" " - + "with key \"null\" with schema \"null\"", exc.getMessage()); - } - + assertThatThrownBy(() -> taskFacade.getInFieldSchemaHelper("InFieldBad")) + .hasMessage("schema helper cannot be created for task field \"InFieldBad\" " + + "with key \"null\" with schema \"null\""); + assertThatThrownBy(() -> taskFacade.getOutFieldSchemaHelper("OutFieldBad")) + .hasMessage("schema helper cannot be created for task field \"OutFieldBad\" " + + "with key \"null\" with schema \"null\""); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContextTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContextTest.java index bbd86ed54..c540f51ad 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContextTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/StateFinalizerExecutionContextTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +21,9 @@ package org.onap.policy.apex.core.engine.executor.context; +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.fail; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -101,12 +102,8 @@ public class StateFinalizerExecutionContextTest { ContextAlbum contextAlbum = sfec.getContextAlbum("AlbumKey0"); assertEquals("AlbumKey0:0.0.1", contextAlbum.getKey().getId()); - try { - sfec.getContextAlbum("AlbumKeyNonExistant"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("cannot find definition of context album \"AlbumKeyNonExistant\" " - + "on state \"Parent:0.0.1:ParentName:StateName\"", exc.getMessage()); - } + assertThatThrownBy(() -> sfec.getContextAlbum("AlbumKeyNonExistant")) + .hasMessage("cannot find definition of context album \"AlbumKeyNonExistant\" " + + "on state \"Parent:0.0.1:ParentName:StateName\""); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContextTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContextTest.java index 2f8b91ecc..5857e0513 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContextTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/context/TaskSelectionExecutionContextTest.java @@ -1,28 +1,29 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 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.core.engine.executor.context; +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.fail; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -101,12 +102,8 @@ public class TaskSelectionExecutionContextTest { ContextAlbum contextAlbum = tsec.getContextAlbum("AlbumKey0"); assertEquals("AlbumKey0:0.0.1", contextAlbum.getKey().getId()); - try { - tsec.getContextAlbum("AlbumKeyNonExistant"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("cannot find definition of context album \"AlbumKeyNonExistant\" " - + "on state \"Parent:0.0.1:ParentName:StateName\"", exc.getMessage()); - } + assertThatThrownBy(() -> tsec.getContextAlbum("AlbumKeyNonExistant")) + .hasMessage("cannot find definition of context album \"AlbumKeyNonExistant\" " + + "on state \"Parent:0.0.1:ParentName:StateName\""); } } diff --git a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/impl/ExceutorFactoryImplTest.java b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/impl/ExceutorFactoryImplTest.java index 7fe394758..5957ff347 100644 --- a/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/impl/ExceutorFactoryImplTest.java +++ b/core/core-engine/src/test/java/org/onap/policy/apex/core/engine/executor/impl/ExceutorFactoryImplTest.java @@ -1,29 +1,29 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2018 Ericsson. All rights reserved. + * Modifications Copyright (C) 2020 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.core.engine.executor.impl; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; import org.junit.After; import org.junit.Before; @@ -93,16 +93,12 @@ public class ExceutorFactoryImplTest { } @Test - public void testExecutorFactoryImplGood() { + public void testExecutorFactoryImplGood() throws StateMachineException { setGoodPars(); ExecutorFactoryImpl factory = null; - try { - factory = new ExecutorFactoryImpl(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } + factory = new ExecutorFactoryImpl(); Mockito.doReturn(true).when(stateMock).checkSetTaskSelectionLogic(); assertNotNull(factory.getTaskSelectionExecutor(null, stateMock, internalContextMock)); @@ -118,142 +114,76 @@ public class ExceutorFactoryImplTest { public void testExecutorFactoryImplNonExistant() { setNonExistantPars(); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - - } catch (StateMachineException ex) { - assertEquals("Apex executor class not found for executor plugin " - + "\"org.onap.policy.apex.core.engine.executor.BadTaskExecutor\"", ex.getMessage()); - } - + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Apex executor class not found for executor plugin " + + "\"org.onap.policy.apex.core.engine.executor.BadTaskExecutor\""); executorPars.setTaskExecutorPluginClass(null); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - } catch (StateMachineException ex) { - assertEquals("Apex executor class not found for executor plugin " - + "\"org.onap.policy.apex.core.engine.executor.BadTaskSelectExecutor\"", ex.getMessage()); - } - + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Apex executor class not found for executor plugin " + + "\"org.onap.policy.apex.core.engine.executor.BadTaskSelectExecutor\""); executorPars.setTaskExecutorPluginClass("org.onap.policy.apex.core.engine.executor.DummyTaskExecutor"); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - } catch (StateMachineException ex) { - assertEquals("Apex executor class not found for executor plugin " - + "\"org.onap.policy.apex.core.engine.executor.BadTaskSelectExecutor\"", ex.getMessage()); - } - + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Apex executor class not found for executor plugin " + + "\"org.onap.policy.apex.core.engine.executor.BadTaskSelectExecutor\""); executorPars.setTaskSelectionExecutorPluginClass( "org.onap.policy.apex.core.engine.executor.DummyTaskSelectExecutor"); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - } catch (StateMachineException ex) { - assertEquals("Apex executor class not found for executor plugin " - + "\"org.onap.policy.apex.core.engine.executor.BadStateFinalizerExecutor\"", - ex.getMessage()); - } + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Apex executor class not found for executor plugin " + + "\"org.onap.policy.apex.core.engine.executor.BadStateFinalizerExecutor\""); } @Test public void testExecutorFactoryImplBad() { setBadPars(); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - - } catch (StateMachineException ex) { - assertEquals("Specified Apex executor plugin class \"java.lang.String\" " - + "does not implment the Executor interface", ex.getMessage()); - } - + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Specified Apex executor plugin class \"java.lang.String\" " + + "does not implment the Executor interface"); executorPars.setTaskExecutorPluginClass("org.onap.policy.apex.core.engine.executor.DummyTaskExecutor"); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - } catch (StateMachineException ex) { - assertEquals("Specified Apex executor plugin class \"java.lang.String\" " - + "does not implment the Executor interface", ex.getMessage()); - } - + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Specified Apex executor plugin class \"java.lang.String\" " + + "does not implment the Executor interface"); executorPars.setTaskSelectionExecutorPluginClass( "org.onap.policy.apex.core.engine.executor.DummyTaskSelectExecutor"); - try { - new ExecutorFactoryImpl(); - fail("test should throw an exception"); - } catch (StateMachineException ex) { - assertEquals("Specified Apex executor plugin class \"java.lang.String\" " - + "does not implment the Executor interface", ex.getMessage()); - } + assertThatThrownBy(() -> new ExecutorFactoryImpl()) + .hasMessage("Specified Apex executor plugin class \"java.lang.String\" " + + "does not implment the Executor interface"); } @Test - public void testExecutorFactoryCreateErrors() { + public void testExecutorFactoryCreateErrors() throws StateMachineException { setGoodPars(); executorPars.setTaskExecutorPluginClass(null); - ExecutorFactoryImpl factory = null; - - try { - factory = new ExecutorFactoryImpl(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } + final ExecutorFactoryImpl factory = new ExecutorFactoryImpl(); Mockito.doReturn(true).when(stateMock).checkSetTaskSelectionLogic(); - try { - factory.getTaskExecutor(null, taskMock, internalContextMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("Executor plugin class not defined for \"Dummy\" executor of type " - + "\"org.onap.policy.apex.core.engine.executor.TaskExecutor\"", ex.getMessage()); - } - + assertThatThrownBy(() -> factory.getTaskExecutor(null, taskMock, internalContextMock)) + .hasMessage("Executor plugin class not defined for \"Dummy\" executor of type " + + "\"org.onap.policy.apex.core.engine.executor.TaskExecutor\""); executorPars.setTaskExecutorPluginClass("org.onap.policy.apex.core.engine.executor.DummyFailingTaskExecutor"); - try { - factory = new ExecutorFactoryImpl(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } - - try { - factory.getTaskExecutor(null, taskMock, internalContextMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("Instantiation error on \"Dummy\" executor of type " - + "\"org.onap.policy.apex.core.engine.executor.DummyFailingTaskExecutor\"", - ex.getMessage()); - } + ExecutorFactoryImpl factoryInitError = new ExecutorFactoryImpl(); + assertThatThrownBy(() -> factoryInitError.getTaskExecutor(null, taskMock, internalContextMock)) + .hasMessage("Instantiation error on \"Dummy\" executor of type " + + "\"org.onap.policy.apex.core.engine.executor.DummyFailingTaskExecutor\""); executorPars.setTaskExecutorPluginClass( "org.onap.policy.apex.core.engine.executor.DummyStateFinalizerExecutor"); - try { - factory = new ExecutorFactoryImpl(); - } catch (StateMachineException e) { - fail("test should not throw an exception"); - } - - try { - factory.getTaskExecutor(null, taskMock, internalContextMock); - fail("test should throw an exception"); - } catch (Exception ex) { - assertEquals("Executor on \"Dummy\" " - + "of type \"class org.onap.policy.apex.core.engine.executor.DummyStateFinalizerExecutor\"" - + " is not an instance of \"org.onap.policy.apex.core.engine.executor.TaskExecutor\"", - ex.getMessage()); - } + ExecutorFactoryImpl factoryDummyError = new ExecutorFactoryImpl(); + + assertThatThrownBy(() -> factoryDummyError.getTaskExecutor(null, taskMock, internalContextMock)) + .hasMessage("Executor on \"Dummy\" " + + "of type \"class org.onap.policy.apex.core.engine.executor.DummyStateFinalizerExecutor\"" + + " is not an instance of \"org.onap.policy.apex.core.engine.executor.TaskExecutor\""); } /** |