More actor clean-up
[policy/models.git] / models-interactions / model-actors / actorServiceProvider / src / test / java / org / onap / policy / controlloop / actorserviceprovider / impl / HttpOperationTest.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.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatCode;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.assertj.core.api.Assertions.assertThatThrownBy;
27 import static org.junit.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertSame;
31 import static org.junit.Assert.assertTrue;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.when;
34
35 import java.util.Collections;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.UUID;
39 import java.util.concurrent.CancellationException;
40 import java.util.concurrent.CompletableFuture;
41 import java.util.concurrent.ExecutionException;
42 import java.util.concurrent.Executor;
43 import java.util.concurrent.Future;
44 import java.util.concurrent.TimeUnit;
45 import java.util.concurrent.TimeoutException;
46 import java.util.concurrent.atomic.AtomicReference;
47 import javax.ws.rs.Consumes;
48 import javax.ws.rs.DELETE;
49 import javax.ws.rs.GET;
50 import javax.ws.rs.POST;
51 import javax.ws.rs.PUT;
52 import javax.ws.rs.Path;
53 import javax.ws.rs.Produces;
54 import javax.ws.rs.client.Entity;
55 import javax.ws.rs.client.InvocationCallback;
56 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.Response;
58 import javax.ws.rs.core.Response.Status;
59 import lombok.Getter;
60 import lombok.Setter;
61 import org.junit.AfterClass;
62 import org.junit.Before;
63 import org.junit.BeforeClass;
64 import org.junit.Test;
65 import org.mockito.Mock;
66 import org.mockito.MockitoAnnotations;
67 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
68 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
69 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams.TopicParamsBuilder;
70 import org.onap.policy.common.endpoints.http.client.HttpClient;
71 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
72 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
73 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
74 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
75 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
76 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
77 import org.onap.policy.common.gson.GsonMessageBodyHandler;
78 import org.onap.policy.common.utils.coder.CoderException;
79 import org.onap.policy.common.utils.network.NetworkUtil;
80 import org.onap.policy.controlloop.VirtualControlLoopEvent;
81 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
82 import org.onap.policy.controlloop.actorserviceprovider.controlloop.ControlLoopEventContext;
83 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
84 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig;
85 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams;
86 import org.onap.policy.controlloop.policy.PolicyResult;
87
88 public class HttpOperationTest {
89
90     private static final IllegalStateException EXPECTED_EXCEPTION = new IllegalStateException("expected exception");
91     private static final String ACTOR = "my-actor";
92     private static final String OPERATION = "my-name";
93     private static final String HTTP_CLIENT = "my-client";
94     private static final String HTTP_NO_SERVER = "my-http-no-server-client";
95     private static final String MEDIA_TYPE_APPLICATION_JSON = "application/json";
96     private static final String BASE_URI = "oper";
97     private static final String PATH = "/my-path";
98     private static final String TEXT = "my-text";
99     private static final UUID REQ_ID = UUID.randomUUID();
100
101     /**
102      * {@code True} if the server should reject the request, {@code false} otherwise.
103      */
104     private static boolean rejectRequest;
105
106     // call counts of each method type in the server
107     private static int nget;
108     private static int npost;
109     private static int nput;
110     private static int ndelete;
111
112     @Mock
113     private HttpClient client;
114     @Mock
115     private HttpClientFactory clientFactory;
116     @Mock
117     private Response response;
118     @Mock
119     private Executor executor;
120
121     private VirtualControlLoopEvent event;
122     private ControlLoopEventContext context;
123     private ControlLoopOperationParams params;
124     private OperationOutcome outcome;
125     private AtomicReference<InvocationCallback<Response>> callback;
126     private Future<Response> future;
127     private HttpConfig config;
128     private MyGetOperation<String> oper;
129
130     /**
131      * Starts the simulator.
132      */
133     @BeforeClass
134     public static void setUpBeforeClass() throws Exception {
135         // allocate a port
136         int port = NetworkUtil.allocPort();
137
138         /*
139          * Start the simulator. Must use "Properties" to configure it, otherwise the
140          * server will use the wrong serialization provider.
141          */
142         Properties svrprops = getServerProperties("my-server", port);
143         HttpServletServerFactoryInstance.getServerFactory().build(svrprops).forEach(HttpServletServer::start);
144
145         if (!NetworkUtil.isTcpPortOpen("localhost", port, 100, 100)) {
146             HttpServletServerFactoryInstance.getServerFactory().destroy();
147             throw new IllegalStateException("server is not running");
148         }
149
150         /*
151          * Start the clients, one to the server, and one to a non-existent server.
152          */
153         TopicParamsBuilder builder = BusTopicParams.builder().managed(true).hostname("localhost").basePath(BASE_URI)
154                         .serializationProvider(GsonMessageBodyHandler.class.getName());
155
156         HttpClientFactoryInstance.getClientFactory().build(builder.clientName(HTTP_CLIENT).port(port).build());
157
158         HttpClientFactoryInstance.getClientFactory()
159                         .build(builder.clientName(HTTP_NO_SERVER).port(NetworkUtil.allocPort()).build());
160     }
161
162     /**
163      * Destroys the Http factories and stops the appender.
164      */
165     @AfterClass
166     public static void tearDownAfterClass() {
167         HttpClientFactoryInstance.getClientFactory().destroy();
168         HttpServletServerFactoryInstance.getServerFactory().destroy();
169     }
170
171     /**
172      * Initializes fields, including {@link #oper}, and resets the static fields used by
173      * the REST server.
174      */
175     @Before
176     public void setUp() {
177         MockitoAnnotations.initMocks(this);
178
179         rejectRequest = false;
180         nget = 0;
181         npost = 0;
182         nput = 0;
183         ndelete = 0;
184
185         when(response.readEntity(String.class)).thenReturn(TEXT);
186         when(response.getStatus()).thenReturn(200);
187
188         event = new VirtualControlLoopEvent();
189         event.setRequestId(REQ_ID);
190
191         context = new ControlLoopEventContext(event);
192         params = ControlLoopOperationParams.builder().actor(ACTOR).operation(OPERATION).context(context).build();
193
194         outcome = params.makeOutcome();
195
196         callback = new AtomicReference<>();
197         future = new CompletableFuture<>();
198
199         when(clientFactory.get(any())).thenReturn(client);
200
201         initConfig(HTTP_CLIENT);
202
203         oper = new MyGetOperation<>(String.class);
204     }
205
206     @Test
207     public void testHttpOperator() {
208         assertEquals(ACTOR, oper.getActorName());
209         assertEquals(OPERATION, oper.getName());
210         assertEquals(ACTOR + "." + OPERATION, oper.getFullName());
211     }
212
213     @Test
214     public void testMakeHeaders() {
215         assertEquals(Collections.emptyMap(), oper.makeHeaders());
216     }
217
218     @Test
219     public void testMakePath() {
220         assertEquals(PATH, oper.makePath());
221     }
222
223     @Test
224     public void testMakeUrl() {
225         // use a real client
226         initRealConfig(HTTP_CLIENT);
227
228         oper = new MyGetOperation<>(String.class);
229
230         assertThat(oper.makeUrl()).endsWith("/" + BASE_URI + PATH);
231     }
232
233     @Test
234     public void testDoConfigureMapOfStringObject_testGetClient_testGetPath_testGetTimeoutMs() {
235
236         // use value from operator
237         assertEquals(1000L, oper.getTimeoutMs(null));
238         assertEquals(1000L, oper.getTimeoutMs(0));
239
240         // should use given value
241         assertEquals(20 * 1000L, oper.getTimeoutMs(20));
242     }
243
244     /**
245      * Tests handleResponse() when it completes.
246      */
247     @Test
248     public void testHandleResponseComplete() throws Exception {
249         CompletableFuture<OperationOutcome> future2 = oper.handleResponse(outcome, PATH, cb -> {
250             callback.set(cb);
251             return future;
252         });
253
254         assertFalse(future2.isDone());
255         assertNotNull(callback.get());
256         callback.get().completed(response);
257
258         assertSame(outcome, future2.get(5, TimeUnit.SECONDS));
259
260         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
261     }
262
263     /**
264      * Tests handleResponse() when it fails.
265      */
266     @Test
267     public void testHandleResponseFailed() throws Exception {
268         CompletableFuture<OperationOutcome> future2 = oper.handleResponse(outcome, PATH, cb -> {
269             callback.set(cb);
270             return future;
271         });
272
273         assertFalse(future2.isDone());
274         assertNotNull(callback.get());
275         callback.get().failed(EXPECTED_EXCEPTION);
276
277         assertThatThrownBy(() -> future2.get(5, TimeUnit.SECONDS)).hasCause(EXPECTED_EXCEPTION);
278
279         // future and future2 may be completed in parallel so we must wait again
280         assertThatThrownBy(() -> future.get(5, TimeUnit.SECONDS)).isInstanceOf(CancellationException.class);
281         assertTrue(future.isCancelled());
282     }
283
284     /**
285      * Tests processResponse() when it's a success and the response type is a String.
286      */
287     @Test
288     public void testProcessResponseSuccessString() throws Exception {
289         CompletableFuture<OperationOutcome> result = oper.processResponse(outcome, PATH, response);
290         assertTrue(result.isDone());
291         assertSame(outcome, result.get());
292         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
293     }
294
295     /**
296      * Tests processResponse() when it's a failure.
297      */
298     @Test
299     public void testProcessResponseFailure() throws Exception {
300         when(response.getStatus()).thenReturn(555);
301         CompletableFuture<OperationOutcome> result = oper.processResponse(outcome, PATH, response);
302         assertTrue(result.isDone());
303         assertSame(outcome, result.get());
304         assertEquals(PolicyResult.FAILURE, outcome.getResult());
305     }
306
307     /**
308      * Tests processResponse() when the decoder succeeds.
309      */
310     @Test
311     public void testProcessResponseDecodeOk() throws Exception {
312         when(response.readEntity(String.class)).thenReturn("10");
313
314         MyGetOperation<Integer> oper2 = new MyGetOperation<>(Integer.class);
315
316         CompletableFuture<OperationOutcome> result = oper2.processResponse(outcome, PATH, response);
317         assertTrue(result.isDone());
318         assertSame(outcome, result.get());
319         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
320     }
321
322     /**
323      * Tests processResponse() when the decoder throws an exception.
324      */
325     @Test
326     public void testProcessResponseDecodeExcept() throws CoderException {
327         MyGetOperation<Integer> oper2 = new MyGetOperation<>(Integer.class);
328
329         assertThatIllegalArgumentException().isThrownBy(() -> oper2.processResponse(outcome, PATH, response));
330     }
331
332     @Test
333     public void testPostProcessResponse() {
334         assertThatCode(() -> oper.postProcessResponse(outcome, PATH, null, null)).doesNotThrowAnyException();
335     }
336
337     @Test
338     public void testIsSuccess() {
339         when(response.getStatus()).thenReturn(200);
340         assertTrue(oper.isSuccess(response, null));
341
342         when(response.getStatus()).thenReturn(555);
343         assertFalse(oper.isSuccess(response, null));
344     }
345
346     /**
347      * Tests a GET.
348      */
349     @Test
350     public void testGet() throws Exception {
351         // use a real client
352         initRealConfig(HTTP_CLIENT);
353
354         MyGetOperation<MyResponse> oper2 = new MyGetOperation<>(MyResponse.class);
355
356         OperationOutcome outcome = runOperation(oper2);
357         assertNotNull(outcome);
358         assertEquals(1, nget);
359         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
360     }
361
362     /**
363      * Tests a DELETE.
364      */
365     @Test
366     public void testDelete() throws Exception {
367         // use a real client
368         initRealConfig(HTTP_CLIENT);
369
370         MyDeleteOperation oper2 = new MyDeleteOperation();
371
372         OperationOutcome outcome = runOperation(oper2);
373         assertNotNull(outcome);
374         assertEquals(1, ndelete);
375         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
376     }
377
378     /**
379      * Tests a POST.
380      */
381     @Test
382     public void testPost() throws Exception {
383         // use a real client
384         initRealConfig(HTTP_CLIENT);
385         MyPostOperation oper2 = new MyPostOperation();
386
387         OperationOutcome outcome = runOperation(oper2);
388         assertNotNull(outcome);
389         assertEquals(1, npost);
390         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
391     }
392
393     /**
394      * Tests a PUT.
395      */
396     @Test
397     public void testPut() throws Exception {
398         // use a real client
399         initRealConfig(HTTP_CLIENT);
400
401         MyPutOperation oper2 = new MyPutOperation();
402
403         OperationOutcome outcome = runOperation(oper2);
404         assertNotNull(outcome);
405         assertEquals(1, nput);
406         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
407     }
408
409     @Test
410     public void testMakeDecoder() {
411         assertNotNull(oper.makeCoder());
412     }
413
414     /**
415      * Gets server properties.
416      *
417      * @param name server name
418      * @param port server port
419      * @return server properties
420      */
421     private static Properties getServerProperties(String name, int port) {
422         final Properties props = new Properties();
423         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, name);
424
425         final String svcpfx = PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + name;
426
427         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, Server.class.getName());
428         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, "localhost");
429         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, String.valueOf(port));
430         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
431         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "false");
432
433         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
434                         GsonMessageBodyHandler.class.getName());
435         return props;
436     }
437
438     /**
439      * Initializes the configuration.
440      *
441      * @param operator operator to be initialized
442      * @param clientName name of the client which it should use
443      */
444     private void initConfig(String clientName) {
445         initConfig(clientName, clientFactory);
446     }
447
448     /**
449      * Initializes the configuration with a real client.
450      *
451      * @param operator operator to be initialized
452      * @param clientName name of the client which it should use
453      */
454     private void initConfig(String clientName, HttpClientFactory factory) {
455         HttpParams params = HttpParams.builder().clientName(clientName).path(PATH).timeoutSec(1).build();
456         config = new HttpConfig(executor, params, factory);
457     }
458
459     /**
460      * Initializes the configuration with a real client.
461      *
462      * @param operator operator to be initialized
463      * @param clientName name of the client which it should use
464      */
465     private void initRealConfig(String clientName) {
466         initConfig(clientName, HttpClientFactoryInstance.getClientFactory());
467     }
468
469     /**
470      * Runs the operation.
471      *
472      * @param operator operator on which to start the operation
473      * @return the outcome of the operation, or {@code null} if it does not complete in
474      *         time
475      */
476     private <T> OperationOutcome runOperation(HttpOperation<T> operator)
477                     throws InterruptedException, ExecutionException, TimeoutException {
478
479         CompletableFuture<OperationOutcome> future = operator.start();
480
481         return future.get(5, TimeUnit.SECONDS);
482     }
483
484     @Getter
485     @Setter
486     public static class MyRequest {
487         private String input = "some input";
488     }
489
490     @Getter
491     @Setter
492     public static class MyResponse {
493         private String output = "some output";
494     }
495
496     private class MyGetOperation<T> extends HttpOperation<T> {
497         public MyGetOperation(Class<T> responseClass) {
498             super(HttpOperationTest.this.params, HttpOperationTest.this.config, responseClass);
499         }
500
501         @Override
502         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
503             Map<String, Object> headers = makeHeaders();
504
505             headers.put("Accept", MediaType.APPLICATION_JSON);
506             String url = makeUrl();
507
508             logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
509
510             // @formatter:off
511             return handleResponse(outcome, url,
512                 callback -> getClient().get(callback, makePath(), headers));
513             // @formatter:on
514         }
515     }
516
517     private class MyPostOperation extends HttpOperation<MyResponse> {
518         public MyPostOperation() {
519             super(HttpOperationTest.this.params, HttpOperationTest.this.config, MyResponse.class);
520         }
521
522         @Override
523         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
524
525             MyRequest request = new MyRequest();
526
527             Entity<MyRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
528
529             Map<String, Object> headers = makeHeaders();
530
531             headers.put("Accept", MediaType.APPLICATION_JSON);
532             String url = makeUrl();
533
534             logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
535
536             // @formatter:off
537             return handleResponse(outcome, url,
538                 callback -> getClient().post(callback, makePath(), entity, headers));
539             // @formatter:on
540         }
541     }
542
543     private class MyPutOperation extends HttpOperation<MyResponse> {
544         public MyPutOperation() {
545             super(HttpOperationTest.this.params, HttpOperationTest.this.config, MyResponse.class);
546         }
547
548         @Override
549         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
550
551             MyRequest request = new MyRequest();
552
553             Entity<MyRequest> entity = Entity.entity(request, MediaType.APPLICATION_JSON);
554
555             Map<String, Object> headers = makeHeaders();
556
557             headers.put("Accept", MediaType.APPLICATION_JSON);
558             String url = makeUrl();
559
560             logMessage(EventType.OUT, CommInfrastructure.REST, url, request);
561
562             // @formatter:off
563             return handleResponse(outcome, url,
564                 callback -> getClient().put(callback, makePath(), entity, headers));
565             // @formatter:on
566         }
567     }
568
569     private class MyDeleteOperation extends HttpOperation<String> {
570         public MyDeleteOperation() {
571             super(HttpOperationTest.this.params, HttpOperationTest.this.config, String.class);
572         }
573
574         @Override
575         protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
576             Map<String, Object> headers = makeHeaders();
577
578             headers.put("Accept", MediaType.APPLICATION_JSON);
579             String url = makeUrl();
580
581             logMessage(EventType.OUT, CommInfrastructure.REST, url, null);
582
583             // @formatter:off
584             return handleResponse(outcome, url,
585                 callback -> getClient().delete(callback, makePath(), headers));
586             // @formatter:on
587         }
588     }
589
590     /**
591      * Simulator.
592      */
593     @Path("/" + BASE_URI)
594     @Produces(MEDIA_TYPE_APPLICATION_JSON)
595     @Consumes(value = {MEDIA_TYPE_APPLICATION_JSON})
596     public static class Server {
597
598         /**
599          * Generates a response to a GET.
600          *
601          * @return resulting response
602          */
603         @GET
604         @Path(PATH)
605         public Response getRequest() {
606             ++nget;
607
608             if (rejectRequest) {
609                 return Response.status(Status.BAD_REQUEST).build();
610
611             } else {
612                 return Response.status(Status.OK).entity(new MyResponse()).build();
613             }
614         }
615
616         /**
617          * Generates a response to a POST.
618          *
619          * @param request incoming request
620          * @return resulting response
621          */
622         @POST
623         @Path(PATH)
624         public Response postRequest(MyRequest request) {
625             ++npost;
626
627             if (rejectRequest) {
628                 return Response.status(Status.BAD_REQUEST).build();
629
630             } else {
631                 return Response.status(Status.OK).entity(new MyResponse()).build();
632             }
633         }
634
635         /**
636          * Generates a response to a PUT.
637          *
638          * @param request incoming request
639          * @return resulting response
640          */
641         @PUT
642         @Path(PATH)
643         public Response putRequest(MyRequest request) {
644             ++nput;
645
646             if (rejectRequest) {
647                 return Response.status(Status.BAD_REQUEST).build();
648
649             } else {
650                 return Response.status(Status.OK).entity(new MyResponse()).build();
651             }
652         }
653
654         /**
655          * Generates a response to a DELETE.
656          *
657          * @return resulting response
658          */
659         @DELETE
660         @Path(PATH)
661         public Response deleteRequest() {
662             ++ndelete;
663
664             if (rejectRequest) {
665                 return Response.status(Status.BAD_REQUEST).build();
666
667             } else {
668                 return Response.status(Status.OK).entity(new MyResponse()).build();
669             }
670         }
671     }
672 }