cad318701e97a0905033ab9887ef3f442646e9c8
[policy/models.git] / models-interactions / model-actors / actor.xacml / src / test / java / org / onap / policy / controlloop / actor / xacml / DecisionOperationTest.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.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertTrue;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.never;
32 import static org.mockito.Mockito.verify;
33 import static org.mockito.Mockito.when;
34
35 import java.util.List;
36 import java.util.Map;
37 import java.util.concurrent.CompletableFuture;
38 import java.util.function.Consumer;
39 import org.junit.AfterClass;
40 import org.junit.Before;
41 import org.junit.BeforeClass;
42 import org.junit.Test;
43 import org.mockito.Mock;
44 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
45 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
46 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
47 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
48 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
49 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
50 import org.onap.policy.controlloop.actorserviceprovider.Util;
51 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
52 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.simulators.XacmlSimulatorJaxRs;
56
57 public class DecisionOperationTest extends BasicHttpOperation {
58     private static final List<String> PROPERTY_NAMES = List.of("prop-A", "prop-B");
59
60     @Mock
61     private Consumer<OperationOutcome> started;
62     @Mock
63     private Consumer<OperationOutcome> completed;
64
65     private DecisionConfig guardConfig;
66     private MyOper oper;
67
68     /**
69      * Starts the simulator.
70      */
71     @BeforeClass
72     public static void setUpBeforeClass() throws Exception {
73         org.onap.policy.simulators.Util.buildXacmlSim();
74
75         BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
76                         .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_SERVER_PORT)
77                         .build();
78         HttpClientFactoryInstance.getClientFactory().build(clientParams);
79     }
80
81     @AfterClass
82     public static void tearDownAfterClass() {
83         HttpClientFactoryInstance.getClientFactory().destroy();
84         HttpServletServerFactoryInstance.getServerFactory().destroy();
85     }
86
87     /**
88      * Sets up.
89      */
90     @Before
91     public void setUp() throws Exception {
92         super.setUpBasic();
93
94         guardConfig = mock(DecisionConfig.class);
95         when(guardConfig.makeRequest()).thenAnswer(args -> {
96             DecisionRequest req = new DecisionRequest();
97             req.setAction("guard");
98             req.setOnapComponent("my-onap-component");
99             req.setOnapInstance("my-onap-instance");
100             req.setOnapName("my-onap-name");
101             return req;
102         });
103
104         config = guardConfig;
105         initConfig();
106
107         params = params.toBuilder().startCallback(started).completeCallback(completed).build();
108
109         oper = new MyOper(params, config);
110     }
111
112     /**
113      * Tests with simulator.
114      */
115     @Test
116     public void testSimulator() throws Exception {
117         DecisionParams opParams = DecisionParams.builder().clientName(MY_CLIENT).path("decision").build();
118         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
119
120         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
121                         .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build();
122         oper = new MyOper(params, config);
123
124         outcome = oper.start().get();
125         assertEquals(OperationResult.FAILURE, outcome.getResult());
126         assertTrue(outcome.getResponse() instanceof DecisionResponse);
127     }
128
129     @Test
130     public void testConstructor() {
131         assertEquals(DEFAULT_ACTOR, oper.getActorName());
132         assertEquals(DEFAULT_OPERATION, oper.getName());
133     }
134
135     @Test
136     public void testGetPropertyNames() {
137         assertThat(oper.getPropertyNames()).isEqualTo(PROPERTY_NAMES);
138     }
139
140     @Test
141     public void testStartOperationAsync() throws Exception {
142         CompletableFuture<OperationOutcome> future2 = oper.start();
143         executor.runAll(100);
144         assertFalse(future2.isDone());
145
146         DecisionResponse resp = new DecisionResponse();
147         resp.setStatus(GuardOperation.PERMIT);
148         when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
149
150         verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
151         callbackCaptor.getValue().completed(rawResponse);
152
153         executor.runAll(100);
154         assertTrue(future2.isDone());
155
156         outcome = future2.get();
157         assertEquals(OperationResult.SUCCESS, outcome.getResult());
158         assertEquals(resp, outcome.getResponse());
159
160         assertNotNull(oper.getSubRequestId());
161         assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
162     }
163
164     /**
165      * Tests startOperationAsync() when the guard is disabled.
166      */
167     @Test
168     public void testStartOperationAsyncDisabled() throws Exception {
169         // indicate that it's disabled
170         when(guardConfig.isDisabled()).thenReturn(true);
171
172         CompletableFuture<OperationOutcome> future2 = oper.start();
173         executor.runAll(100);
174
175         verify(client, never()).post(any(), any(), any(), any());
176
177         // should already be done
178         assertTrue(future2.isDone());
179
180         outcome = future2.get();
181         assertEquals(OperationResult.SUCCESS, outcome.getResult());
182         assertNull(outcome.getResponse());
183
184         // ensure callbacks were invoked
185         verify(started).accept(any());
186         verify(completed).accept(any());
187     }
188
189     private class MyOper extends DecisionOperation {
190
191         public MyOper(ControlLoopOperationParams params, HttpConfig config) {
192             super(params, config, PROPERTY_NAMES);
193         }
194
195         @Override
196         protected DecisionRequest makeRequest() {
197             return guardConfig.makeRequest();
198         }
199     }
200 }