28e28fdd4e3cf3ef10a282e695293d7dfbbedf64
[policy/models.git] / models-interactions / model-actors / actor.xacml / src / test / java / org / onap / policy / controlloop / actor / xacml / GuardOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 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.actor.xacml;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertSame;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.when;
31
32 import java.util.Map;
33 import java.util.TreeMap;
34 import java.util.function.Consumer;
35 import org.junit.AfterClass;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.mockito.Mock;
40 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
41 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
42 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
47 import org.onap.policy.models.decisions.concepts.DecisionRequest;
48 import org.onap.policy.models.decisions.concepts.DecisionResponse;
49 import org.onap.policy.simulators.XacmlSimulatorJaxRs;
50
51 public class GuardOperationTest extends BasicHttpOperation {
52
53     @Mock
54     private Consumer<OperationOutcome> started;
55     @Mock
56     private Consumer<OperationOutcome> completed;
57
58     private DecisionConfig guardConfig;
59     private GuardOperation oper;
60
61     /**
62      * Starts the simulator.
63      */
64     @BeforeClass
65     public static void setUpBeforeClass() throws Exception {
66         org.onap.policy.simulators.Util.buildXacmlSim();
67
68         BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
69                         .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_SERVER_PORT)
70                         .build();
71         HttpClientFactoryInstance.getClientFactory().build(clientParams);
72     }
73
74     @AfterClass
75     public static void tearDownAfterClass() {
76         HttpClientFactoryInstance.getClientFactory().destroy();
77         HttpServletServerFactoryInstance.getServerFactory().destroy();
78     }
79
80     /**
81      * Sets up.
82      */
83     @Before
84     public void setUp() throws Exception {
85         super.setUpBasic();
86
87         guardConfig = mock(DecisionConfig.class);
88         when(guardConfig.makeRequest()).thenAnswer(args -> {
89             DecisionRequest req = new DecisionRequest();
90             req.setAction("guard");
91             req.setOnapComponent("my-onap-component");
92             req.setOnapInstance("my-onap-instance");
93             req.setOnapName("my-onap-name");
94             return req;
95         });
96
97         config = guardConfig;
98         initConfig();
99
100         params = params.toBuilder().startCallback(started).completeCallback(completed).build();
101
102         oper = new GuardOperation(params, config);
103     }
104
105     /**
106      * Tests "success" case with simulator.
107      */
108     @Test
109     public void testSuccess() throws Exception {
110         DecisionParams opParams =
111                         DecisionParams.builder().clientName(MY_CLIENT).path("decision").action("guard").build();
112         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
113
114         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
115         oper = new GuardOperation(params, config);
116
117         outcome = oper.start().get();
118         assertEquals(OperationResult.SUCCESS, outcome.getResult());
119         assertTrue(outcome.getResponse() instanceof DecisionResponse);
120     }
121
122     /**
123      * Tests "failure" case with simulator.
124      */
125     @Test
126     public void testFailure() throws Exception {
127         DecisionParams opParams =
128                         DecisionParams.builder().clientName(MY_CLIENT).path("decision").action("guard").build();
129         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
130
131         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
132                         .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build();
133         oper = new GuardOperation(params, config);
134
135         outcome = oper.start().get();
136         assertEquals(OperationResult.FAILURE, outcome.getResult());
137         assertTrue(outcome.getResponse() instanceof DecisionResponse);
138     }
139
140     @Test
141     public void testConstructor() {
142         assertEquals(DEFAULT_ACTOR, oper.getActorName());
143         assertEquals(DEFAULT_OPERATION, oper.getName());
144     }
145
146     @Test
147     public void testGetPropertyNames() {
148         assertThat(oper.getPropertyNames()).isEmpty();
149     }
150
151     @Test
152     public void testMakeRequest() throws CoderException {
153         oper.generateSubRequestId(2);
154
155         verifyPayload("makeReqStd.json", makePayload());
156         verifyPayload("makeReqDefault.json", new TreeMap<>());
157
158         // null payload - start with fresh parameters and operation
159         params = params.toBuilder().payload(null).build();
160         oper = new GuardOperation(params, config);
161         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
162     }
163
164     private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
165         params.getPayload().clear();
166         params.getPayload().putAll(payload);
167
168         DecisionRequest request = oper.makeRequest();
169
170         assertEquals("guard", request.getAction());
171         assertEquals("my-onap-component", request.getOnapComponent());
172         assertEquals("my-onap-instance", request.getOnapInstance());
173         assertEquals("my-onap-name", request.getOnapName());
174         assertNotNull(request.getRequestId());
175         assertEquals(Map.of("guard", payload), request.getResource());
176
177         verifyRequest(expectedJsonFile, request, "requestId");
178     }
179
180     @Test
181     public void testPostProcessResponse() {
182         DecisionResponse response = new DecisionResponse();
183
184         // null status
185         response.setStatus(null);
186         verifyOutcome(response, OperationResult.FAILURE, "response contains no status");
187
188         // permit, mixed case
189         response.setStatus("peRmit");
190         verifyOutcome(response, OperationResult.SUCCESS, "peRmit");
191
192         // indeterminate, mixed case
193         response.setStatus("inDETerminate");
194         verifyOutcome(response, OperationResult.SUCCESS, "inDETerminate");
195
196         // deny, mixed case
197         response.setStatus("deNY");
198         verifyOutcome(response, OperationResult.FAILURE, "deNY");
199
200         // unknown status
201         response.setStatus("unknown");
202         verifyOutcome(response, OperationResult.FAILURE, "unknown");
203     }
204
205     private void verifyOutcome(DecisionResponse response, OperationResult expectedResult, String expectedMessage) {
206         oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
207         assertEquals(expectedResult, outcome.getResult());
208         assertEquals(expectedMessage, outcome.getMessage());
209         assertSame(response, outcome.getResponse());
210     }
211
212     @Override
213     protected Map<String, Object> makePayload() {
214         return new TreeMap<>(Map.of("hello", "world", "abc", "123"));
215     }
216 }