0ca98720cf0d468cf3bc38b94659af6334c31c93
[policy/drools-applications.git] / controlloop / common / eventmanager / src / test / java / org / onap / policy / controlloop / processor / ControlLoopProcessorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.processor;
22
23 import static org.assertj.core.api.Assertions.assertThatThrownBy;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertNull;
26
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.nio.charset.StandardCharsets;
32 import java.nio.file.Files;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.commons.lang3.StringUtils;
35 import org.junit.Test;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.ResourceUtils;
39 import org.onap.policy.controlloop.ControlLoopException;
40 import org.onap.policy.controlloop.actorserviceprovider.OperationFinalResult;
41 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
42 import org.onap.policy.drools.domain.models.operational.Operation;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class ControlLoopProcessorTest {
49     private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class);
50     private static final StandardCoder coder = new StandardCoder();
51
52     @Test
53     public void testControlLoopProcessor() throws IOException, ControlLoopException {
54         String yamlString = Files.readString(new File("src/test/resources/test.yaml").toPath(), StandardCharsets.UTF_8);
55         this.testSuccess(yamlString);
56         this.testFailure(yamlString);
57     }
58
59     private ToscaPolicy getPolicyFromResource(String resourcePath, String policyName) throws CoderException {
60         String policyJson = ResourceUtils.getResourceAsString(resourcePath);
61         ToscaServiceTemplate serviceTemplate = coder.decode(policyJson, ToscaServiceTemplate.class);
62         ToscaPolicy policy = serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
63         assertNotNull(policy);
64
65         /*
66          * name and version are used within a drl.  api component and drools core will ensure that these
67          * are populated.
68          */
69         if (StringUtils.isBlank(policy.getName())) {
70             policy.setName(policyName);
71         }
72
73         if (StringUtils.isBlank(policy.getVersion())) {
74             policy.setVersion(policy.getTypeVersion());
75         }
76
77         return serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
78     }
79
80     @Test
81     public void testControlLoopFromToscaCompliant()
82             throws CoderException, ControlLoopException {
83         assertNotNull(
84                 new ControlLoopProcessor(
85                         getPolicyFromResource(
86                                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart")
87                 ).getCurrentPolicy());
88
89
90         assertNotNull(
91                 new ControlLoopProcessor(
92                         getPolicyFromResource(
93                                 "policies/vFirewall.policy.operational.input.tosca.json", "operational.modifyconfig")
94                 ).getCurrentPolicy());
95
96         assertNotNull(
97                 new ControlLoopProcessor(
98                         getPolicyFromResource(
99                                 "policies/vDNS.policy.operational.input.tosca.json", "operational.scaleout")
100                 ).getCurrentPolicy());
101     }
102
103     @Test
104     public void testControlLoopFromToscaCompliantBad() throws CoderException {
105         ToscaPolicy toscaPolicy = getPolicyFromResource(
106                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart");
107         toscaPolicy.setVersion(null);
108         assertThatThrownBy(() -> new ControlLoopProcessor(toscaPolicy)).hasCauseInstanceOf(CoderException.class);
109     }
110
111     @Test
112     public void testControlLoopProcessorBadYaml() throws IOException {
113         InputStream is = new FileInputStream(new File("src/test/resources/string.yaml"));
114         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
115
116         assertThatThrownBy(() -> new ControlLoopProcessor(yamlString))
117             .hasMessageEndingWith("Cannot decode yaml into ToscaServiceTemplate");
118     }
119
120     @Test
121     public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException {
122         String yamlString = Files.readString(new File("src/test/resources/badtriggerpolicy.yaml").toPath(),
123                         StandardCharsets.UTF_8);
124
125         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
126         assertNull(clProcessor.getCurrentPolicy());
127
128         assertThatThrownBy(() -> clProcessor.nextPolicyForResult(OperationResult.SUCCESS))
129             .hasMessageStartingWith("There is no current policy to determine where to go to.");
130     }
131
132     @Test
133     public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException {
134         InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml"));
135         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
136
137         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
138         assertThatThrownBy(clProcessor::getCurrentPolicy)
139             .hasMessage("There are no policies defined.");
140     }
141
142     @Test
143     public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException {
144         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
145         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
146
147         for (OperationResult result : OperationResult.values()) {
148             checkResult(yamlString, result);
149         }
150     }
151
152     private void checkResult(String yamlString, OperationResult result) throws ControlLoopException {
153         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
154         clProcessor.getCurrentPolicy();
155         clProcessor.nextPolicyForResult(result);
156     }
157
158     /**
159      * Test policies in the given yaml following the successful path.
160      *
161      * @param yaml yaml containing the policies to test
162      * @throws ControlLoopException if an error occurs
163      */
164     public void testSuccess(String yaml) throws ControlLoopException {
165         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
166         logger.debug("testSuccess: {}", processor.getCurrentPolicy());
167         while (true) {
168             OperationFinalResult result = processor.checkIsCurrentPolicyFinal();
169             if (result != null) {
170                 logger.debug("{}", result);
171                 break;
172             }
173             Operation policy = processor.getCurrentPolicy();
174             assertNotNull(policy);
175             logger.debug("current policy is: {}", policy.getId());
176             processor.nextPolicyForResult(OperationResult.SUCCESS);
177         }
178     }
179
180     /**
181      * Test policies in the given yaml following the failure path.
182      *
183      * @param yaml yaml containing the policies to test
184      * @throws ControlLoopException if an error occurs
185      */
186     public void testFailure(String yaml) throws ControlLoopException {
187         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
188         logger.debug("testFailure: {}", processor.getCurrentPolicy());
189         while (true) {
190             OperationFinalResult result = processor.checkIsCurrentPolicyFinal();
191             if (result != null) {
192                 logger.debug("{}", result);
193                 break;
194             }
195             Operation policy = processor.getCurrentPolicy();
196             assertNotNull(policy);
197             logger.debug("current policy is: {}", policy.getId());
198             processor.nextPolicyForResult(OperationResult.FAILURE);
199         }
200     }
201 }