Moving common polling code into HttpOperation
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / test / java / org / onap / policy / controlloop / actorserviceprovider / impl / HttpPollingOperationTest.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.actorserviceprovider.impl;
22
23 import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.when;
33
34 import java.util.concurrent.CompletableFuture;
35 import java.util.concurrent.ForkJoinPool;
36 import java.util.concurrent.TimeUnit;
37 import javax.ws.rs.client.InvocationCallback;
38 import javax.ws.rs.core.Response;
39 import org.junit.Before;
40 import org.junit.Test;
41 import org.mockito.Mock;
42 import org.mockito.MockitoAnnotations;
43 import org.mockito.stubbing.Answer;
44 import org.onap.policy.common.endpoints.http.client.HttpClient;
45 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
46 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
47 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
48 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
49 import org.onap.policy.controlloop.policy.PolicyResult;
50
51 /**
52  * Tests HttpOperation when polling is enabled.
53  */
54 public class HttpPollingOperationTest {
55     private static final String BASE_URI = "http://my-host:6969/base-uri/";
56     private static final String MY_PATH = "my-path";
57     private static final String FULL_PATH = BASE_URI + MY_PATH;
58     private static final int MAX_POLLS = 3;
59     private static final int POLL_WAIT_SEC = 20;
60     private static final String POLL_PATH = "my-poll-path";
61     private static final String MY_ACTOR = "my-actor";
62     private static final String MY_OPERATION = "my-operation";
63     private static final String MY_RESPONSE = "my-response";
64     private static final int RESPONSE_ACCEPT = 100;
65     private static final int RESPONSE_SUCCESS = 200;
66     private static final int RESPONSE_FAILURE = 500;
67
68     @Mock
69     private HttpPollingConfig config;
70     @Mock
71     private HttpClient client;
72     @Mock
73     private Response rawResponse;
74
75     protected ControlLoopOperationParams params;
76     private String response;
77     private OperationOutcome outcome;
78
79     private HttpOperation<String> oper;
80
81     /**
82      * Sets up.
83      */
84     @Before
85     public void setUp() throws Exception {
86         MockitoAnnotations.initMocks(this);
87
88         when(client.getBaseUrl()).thenReturn(BASE_URI);
89
90         when(config.getClient()).thenReturn(client);
91         when(config.getPath()).thenReturn(MY_PATH);
92         when(config.getMaxPolls()).thenReturn(MAX_POLLS);
93         when(config.getPollPath()).thenReturn(POLL_PATH);
94         when(config.getPollWaitSec()).thenReturn(POLL_WAIT_SEC);
95
96         response = MY_RESPONSE;
97
98         when(rawResponse.getStatus()).thenReturn(RESPONSE_SUCCESS);
99         when(rawResponse.readEntity(String.class)).thenReturn(response);
100
101         params = ControlLoopOperationParams.builder().actor(MY_ACTOR).operation(MY_OPERATION).build();
102         outcome = params.makeOutcome();
103
104         oper = new MyOper(params, config);
105     }
106
107     @Test
108     public void testConstructor_testGetWaitMsGet() {
109         assertEquals(MY_ACTOR, oper.getActorName());
110         assertEquals(MY_OPERATION, oper.getName());
111         assertSame(config, oper.getConfig());
112         assertEquals(1000 * POLL_WAIT_SEC, oper.getPollWaitMs());
113     }
114
115     @Test
116     public void testSetUsePollExceptions() {
117         // should be no exception
118         oper.setUsePolling();
119
120         // should throw an exception if we pass a plain HttpConfig
121         HttpConfig config2 = mock(HttpConfig.class);
122         when(config2.getClient()).thenReturn(client);
123         when(config2.getPath()).thenReturn(MY_PATH);
124
125         assertThatIllegalStateException().isThrownBy(() -> new MyOper(params, config2).setUsePolling());
126     }
127
128     @Test
129     public void testPostProcess() throws Exception {
130         // completed
131         oper.generateSubRequestId(2);
132         CompletableFuture<OperationOutcome> future2 =
133                         oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response);
134         assertTrue(future2.isDone());
135         assertSame(outcome, future2.get());
136         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
137         assertNotNull(oper.getSubRequestId());
138         assertSame(response, outcome.getResponse());
139
140         // failed
141         oper.generateSubRequestId(2);
142         when(rawResponse.getStatus()).thenReturn(RESPONSE_FAILURE);
143         future2 = oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response);
144         assertTrue(future2.isDone());
145         assertSame(outcome, future2.get());
146         assertEquals(PolicyResult.FAILURE, outcome.getResult());
147         assertNotNull(oper.getSubRequestId());
148         assertSame(response, outcome.getResponse());
149     }
150
151     /**
152      * Tests postProcess() when the poll is repeated a couple of times.
153      */
154     @Test
155     public void testPostProcessRepeated_testResetGetCount() throws Exception {
156         /*
157          * Two accepts and then a success - should result in two polls.
158          */
159         when(rawResponse.getStatus()).thenReturn(RESPONSE_ACCEPT, RESPONSE_ACCEPT, RESPONSE_SUCCESS, RESPONSE_SUCCESS);
160
161         when(client.get(any(), any(), any())).thenAnswer(provideResponse(rawResponse));
162
163         // use a real executor
164         params = params.toBuilder().executor(ForkJoinPool.commonPool()).build();
165
166         oper = new MyOper(params, config) {
167             @Override
168             public long getPollWaitMs() {
169                 return 1;
170             }
171         };
172
173         CompletableFuture<OperationOutcome> future2 =
174                         oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response);
175
176         assertSame(outcome, future2.get(5, TimeUnit.SECONDS));
177         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
178         assertEquals(2, oper.getPollCount());
179
180         /*
181          * repeat - this time, the "poll" count will be exhausted, so it should fail
182          */
183         when(rawResponse.getStatus()).thenReturn(RESPONSE_ACCEPT);
184
185         future2 = oper.postProcessResponse(outcome, FULL_PATH, rawResponse, response);
186
187         assertSame(outcome, future2.get(5, TimeUnit.SECONDS));
188         assertEquals(PolicyResult.FAILURE_TIMEOUT, outcome.getResult());
189         assertEquals(MAX_POLLS + 1, oper.getPollCount());
190
191         oper.resetPollCount();
192         assertEquals(0, oper.getPollCount());
193         assertNull(oper.getSubRequestId());
194     }
195
196     @Test
197     public void testDetmStatus() {
198         // make an operation that does NOT override detmStatus()
199         oper = new HttpOperation<String>(params, config, String.class) {};
200
201         assertThatThrownBy(() -> oper.detmStatus(rawResponse, response))
202                         .isInstanceOf(UnsupportedOperationException.class);
203     }
204
205     /**
206      * Provides a response to an asynchronous HttpClient call.
207      *
208      * @param response response to be provided to the call
209      * @return a function that provides the response to the call
210      */
211     protected Answer<CompletableFuture<Response>> provideResponse(Response response) {
212         return provideResponse(response, 0);
213     }
214
215     /**
216      * Provides a response to an asynchronous HttpClient call.
217      *
218      * @param response response to be provided to the call
219      * @param index index of the callback within the arguments
220      * @return a function that provides the response to the call
221      */
222     protected Answer<CompletableFuture<Response>> provideResponse(Response response, int index) {
223         return args -> {
224             InvocationCallback<Response> cb = args.getArgument(index);
225             cb.completed(response);
226             return CompletableFuture.completedFuture(response);
227         };
228     }
229
230     private static class MyOper extends HttpOperation<String> {
231
232         public MyOper(ControlLoopOperationParams params, HttpConfig config) {
233             super(params, config, String.class);
234
235             setUsePolling();
236         }
237
238         @Override
239         protected Status detmStatus(Response rawResponse, String response) {
240             switch (rawResponse.getStatus()) {
241                 case RESPONSE_ACCEPT:
242                     return Status.STILL_WAITING;
243                 case RESPONSE_SUCCESS:
244                     return Status.SUCCESS;
245                 default:
246                     return Status.FAILURE;
247             }
248         }
249
250         @Override
251         protected boolean isSuccess(Response rawResponse, String response) {
252             return true;
253         }
254     }
255 }