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