1031c86c76dbff55ba97f2ac2d14f0359925acaf
[policy/drools-applications.git] /
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 java.nio.file.Paths;
34 import org.apache.commons.io.IOUtils;
35 import org.apache.commons.lang3.StringUtils;
36 import org.junit.Test;
37 import org.onap.policy.common.utils.coder.CoderException;
38 import org.onap.policy.common.utils.coder.StandardCoder;
39 import org.onap.policy.common.utils.resources.ResourceUtils;
40 import org.onap.policy.controlloop.ControlLoopException;
41 import org.onap.policy.controlloop.policy.FinalResult;
42 import org.onap.policy.controlloop.policy.Policy;
43 import org.onap.policy.controlloop.policy.PolicyResult;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class ControlLoopProcessorTest {
50     private static final Logger logger = LoggerFactory.getLogger(ControlLoopProcessorTest.class);
51     private static final StandardCoder coder = new StandardCoder();
52
53     @Test
54     public void testControlLoopProcessor() throws IOException, ControlLoopException {
55         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
56         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
57         this.testSuccess(yamlString);
58         this.testFailure(yamlString);
59     }
60
61     private ToscaPolicy getPolicyFromResource(String resourcePath, String policyName) throws CoderException {
62         String policyJson = ResourceUtils.getResourceAsString(resourcePath);
63         ToscaServiceTemplate serviceTemplate = coder.decode(policyJson, ToscaServiceTemplate.class);
64         ToscaPolicy policy = serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
65         assertNotNull(policy);
66
67         /*
68          * name and version are used within a drl.  api component and drools core will ensure that these
69          * are populated.
70          */
71         if (StringUtils.isBlank(policy.getName())) {
72             policy.setName(policyName);
73         }
74
75         if (StringUtils.isBlank(policy.getVersion())) {
76             policy.setVersion(policy.getTypeVersion());
77         }
78
79         return serviceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyName);
80     }
81
82     @Test
83     public void testControlLoopFromToscaCompliant()
84             throws CoderException, ControlLoopException {
85         assertNotNull(
86                 new ControlLoopProcessor(
87                         getPolicyFromResource(
88                                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart")
89                 ).getCurrentPolicy());
90
91
92         assertNotNull(
93                 new ControlLoopProcessor(
94                         getPolicyFromResource(
95                                 "policies/vFirewall.policy.operational.input.tosca.json", "operational.modifyconfig")
96                 ).getCurrentPolicy());
97
98         assertNotNull(
99                 new ControlLoopProcessor(
100                         getPolicyFromResource(
101                                 "policies/vDNS.policy.operational.input.tosca.json", "operational.scaleout")
102                 ).getCurrentPolicy());
103     }
104
105     @Test
106     public void testControlLoopFromToscaCompliantBad() throws CoderException {
107         ToscaPolicy toscaPolicy = getPolicyFromResource(
108                 "policies/vCPE.policy.operational.input.tosca.json", "operational.restart");
109         toscaPolicy.setVersion(null);
110         assertThatThrownBy(() -> new ControlLoopProcessor(toscaPolicy)).hasCauseInstanceOf(CoderException.class);
111     }
112
113     @Test
114     public void testControlLoopProcessorBadYaml() throws IOException {
115         InputStream is = new FileInputStream(new File("src/test/resources/string.yaml"));
116         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
117
118         assertThatThrownBy(() -> new ControlLoopProcessor(yamlString))
119             .hasMessageStartingWith("Cannot create property=string for JavaBean=ControlLoopPolicy");
120     }
121
122     @Test
123     public void testControlLoopProcessorBadTriggerYaml() throws IOException, ControlLoopException {
124         InputStream is = new FileInputStream(new File("src/test/resources/badtriggerpolicy.yaml"));
125         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
126
127         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
128         assertNull(clProcessor.getCurrentPolicy());
129
130         assertThatThrownBy(() -> clProcessor.nextPolicyForResult(PolicyResult.SUCCESS))
131             .hasMessageStartingWith("There is no current policy to determine where to go to.");
132     }
133
134     @Test
135     public void testControlLoopProcessorNoPolicyYaml() throws IOException, ControlLoopException {
136         InputStream is = new FileInputStream(new File("src/test/resources/nopolicy.yaml"));
137         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
138
139         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
140         assertThatThrownBy(clProcessor::getCurrentPolicy)
141             .hasMessage("There are no policies defined.");
142     }
143
144     @Test
145     public void testControlLoopProcessorNextPolicyForResult() throws IOException, ControlLoopException {
146         InputStream is = new FileInputStream(new File("src/test/resources/test.yaml"));
147         String yamlString = IOUtils.toString(is, StandardCharsets.UTF_8);
148
149         for (PolicyResult result : PolicyResult.values()) {
150             checkResult(yamlString, result);
151         }
152     }
153
154     private void checkResult(String yamlString, PolicyResult result) throws ControlLoopException {
155         ControlLoopProcessor clProcessor = new ControlLoopProcessor(yamlString);
156         clProcessor.getCurrentPolicy();
157         clProcessor.nextPolicyForResult(result);
158     }
159
160     /**
161      * Test policies in the given yaml following the successful path.
162      *
163      * @param yaml yaml containing the policies to test
164      * @throws ControlLoopException if an error occurs
165      */
166     public void testSuccess(String yaml) throws ControlLoopException {
167         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
168         logger.debug("testSuccess: {}", processor.getControlLoop());
169         while (true) {
170             FinalResult result = processor.checkIsCurrentPolicyFinal();
171             if (result != null) {
172                 logger.debug("{}", result);
173                 break;
174             }
175             Policy policy = processor.getCurrentPolicy();
176             assertNotNull(policy);
177             logger.debug("current policy is: {} {}", policy.getId(), policy.getName());
178             processor.nextPolicyForResult(PolicyResult.SUCCESS);
179         }
180     }
181
182     /**
183      * Test policies in the given yaml following the failure path.
184      *
185      * @param yaml yaml containing the policies to test
186      * @throws ControlLoopException if an error occurs
187      */
188     public void testFailure(String yaml) throws ControlLoopException {
189         ControlLoopProcessor processor = new ControlLoopProcessor(yaml);
190         logger.debug("testFailure: {}", processor.getControlLoop());
191         while (true) {
192             FinalResult result = processor.checkIsCurrentPolicyFinal();
193             if (result != null) {
194                 logger.debug("{}", result);
195                 break;
196             }
197             Policy policy = processor.getCurrentPolicy();
198             assertNotNull(policy);
199             logger.debug("current policy is: {} {}", policy.getId(), policy.getName());
200             processor.nextPolicyForResult(PolicyResult.FAILURE);
201         }
202     }
203 }