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