Merge "Remove ActorService singleton"
[policy/models.git] / models-interactions / model-actors / actor.guard / src / test / java / org / onap / policy / controlloop / actor / guard / GuardOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 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.actor.guard;
22
23 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.never;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32
33 import java.util.Map;
34 import java.util.TreeMap;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.function.Consumer;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.Mock;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
42 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
43 import org.onap.policy.controlloop.actorserviceprovider.Util;
44 import org.onap.policy.controlloop.policy.PolicyResult;
45 import org.onap.policy.models.decisions.concepts.DecisionRequest;
46 import org.onap.policy.models.decisions.concepts.DecisionResponse;
47
48 public class GuardOperationTest extends BasicHttpOperation<DecisionRequest> {
49
50     @Mock
51     private Consumer<OperationOutcome> started;
52     @Mock
53     private Consumer<OperationOutcome> completed;
54
55     private GuardConfig guardConfig;
56     private GuardOperation oper;
57
58     /**
59      * Sets up.
60      */
61     @Before
62     public void setUp() throws Exception {
63         super.setUpBasic();
64
65         guardConfig = mock(GuardConfig.class);
66         when(guardConfig.makeRequest()).thenAnswer(args -> new TreeMap<>(Map.of("action", "guard")));
67
68         config = guardConfig;
69         initConfig();
70
71         params = params.toBuilder().startCallback(started).completeCallback(completed).build();
72
73         oper = new GuardOperation(params, config);
74     }
75
76     @Test
77     public void testConstructor() {
78         assertEquals(DEFAULT_ACTOR, oper.getActorName());
79         assertEquals(DEFAULT_OPERATION, oper.getName());
80     }
81
82     @Test
83     public void testStartOperationAsync() throws Exception {
84         CompletableFuture<OperationOutcome> future2 = oper.start();
85         executor.runAll(100);
86         assertFalse(future2.isDone());
87
88         DecisionResponse resp = new DecisionResponse();
89         resp.setStatus(GuardOperation.PERMIT);
90         when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
91
92         verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
93         callbackCaptor.getValue().completed(rawResponse);
94
95         executor.runAll(100);
96         assertTrue(future2.isDone());
97
98         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
99     }
100
101     /**
102      * Tests startOperationAsync() when the guard is disabled.
103      */
104     @Test
105     public void testStartOperationAsyncDisabled() throws Exception {
106         // indicate that it's disabled
107         when(guardConfig.isDisabled()).thenReturn(true);
108
109         CompletableFuture<OperationOutcome> future2 = oper.start();
110         executor.runAll(100);
111
112         verify(client, never()).post(any(), any(), any(), any());
113
114         // should already be done
115         assertTrue(future2.isDone());
116
117         assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
118
119         // ensure callbacks were invoked
120         verify(started).accept(any());
121         verify(completed).accept(any());
122     }
123
124     @Test
125     public void testMakeRequest() throws CoderException {
126         verifyPayload("makeReqStd.json", makePayload());
127         verifyPayload("makeReqDefault.json", new TreeMap<>());
128
129         Map<String, Object> payload = new TreeMap<>();
130         payload.put("action", "some action");
131         payload.put("hello", "world");
132         payload.put("r u there?", "yes");
133         payload.put("requestId", "some request id");
134
135         Map<String, Object> resource = new TreeMap<>();
136         payload.put("resource", resource);
137         resource.put("abc", "def");
138         resource.put("ghi", "jkl");
139
140         verifyPayload("makeReq.json", payload);
141
142         // null payload - start with fresh parameters and operation
143         params = params.toBuilder().payload(null).build();
144         oper = new GuardOperation(params, config);
145         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
146     }
147
148     private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
149         params.getPayload().clear();
150         params.getPayload().putAll(payload);
151
152         Map<String, Object> requestMap = oper.makeRequest();
153
154         verifyRequest(expectedJsonFile, requestMap, "requestId");
155     }
156
157     @Test
158     public void testPostProcessResponse() {
159         DecisionResponse response = new DecisionResponse();
160
161         // null status
162         response.setStatus(null);
163         verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
164
165         // permit, mixed case
166         response.setStatus("peRmit");
167         verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
168
169         // indeterminate, mixed case
170         response.setStatus("inDETerminate");
171         verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
172
173         // deny, mixed case
174         response.setStatus("deNY");
175         verifyOutcome(response, PolicyResult.FAILURE, "deNY");
176
177         // unknown status
178         response.setStatus("unknown");
179         verifyOutcome(response, PolicyResult.FAILURE, "unknown");
180     }
181
182     private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) {
183         oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
184         assertEquals(expectedResult, outcome.getResult());
185         assertEquals(expectedMessage, outcome.getMessage());
186     }
187
188     @Override
189     protected Map<String, Object> makePayload() {
190         DecisionRequest req = new DecisionRequest();
191         req.setAction("my-action");
192         req.setOnapComponent("my-onap-component");
193         req.setOnapInstance("my-onap-instance");
194         req.setOnapName("my-onap-name");
195         req.setRequestId("my-request-id");
196
197         // add resources
198         Map<String, Object> resource = new TreeMap<>();
199         req.setResource(resource);
200         resource.put("actor", "resource-actor");
201         resource.put("operation", "resource-operation");
202
203         @SuppressWarnings("unchecked")
204         Map<String, Object> map = Util.translate("", req, TreeMap.class);
205
206         return map;
207     }
208 }