Parallel execution of Client Health check
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / TestPolicyComponentsHealthCheckProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation.
4  *  Modifications Copyright (C) 2020 AT&T Corp.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.main.rest;
23
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.when;
29
30 import java.io.File;
31 import java.net.HttpURLConnection;
32 import java.util.List;
33 import java.util.Map;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.Response.Status;
36 import org.apache.commons.lang3.tuple.Pair;
37 import org.junit.After;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.mockito.Mock;
41 import org.mockito.MockitoAnnotations;
42 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
43 import org.onap.policy.common.endpoints.http.client.HttpClient;
44 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
45 import org.onap.policy.common.endpoints.report.HealthCheckReport;
46 import org.onap.policy.common.parameters.ParameterService;
47 import org.onap.policy.common.utils.coder.Coder;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.common.utils.resources.ResourceUtils;
51 import org.onap.policy.common.utils.services.Registry;
52 import org.onap.policy.models.pdp.concepts.Pdp;
53 import org.onap.policy.models.pdp.concepts.PdpGroup;
54 import org.onap.policy.models.pdp.concepts.PdpGroups;
55 import org.onap.policy.models.pdp.enums.PdpHealthStatus;
56 import org.onap.policy.models.provider.PolicyModelsProvider;
57 import org.onap.policy.pap.main.PapConstants;
58 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
59 import org.onap.policy.pap.main.parameters.CommonTestData;
60 import org.onap.policy.pap.main.parameters.PapParameterGroup;
61 import org.onap.policy.pap.main.startstop.PapActivator;
62
63 public class TestPolicyComponentsHealthCheckProvider {
64
65     private static final String CLIENT_1 = "client1";
66     private static final String PDP_GROUP_DATA_FILE = "rest/pdpGroup.json";
67     private static final String PAP_GROUP_PARAMS_NAME = "PapGroup";
68     private static final String HEALTHY = "healthy";
69
70     @Mock
71     private PolicyModelsProvider dao;
72
73     @Mock
74     private PolicyModelsProviderFactoryWrapper daofact;
75
76     @Mock
77     private HttpClientFactory clientFactory;
78
79     @Mock
80     PapActivator papActivator;
81
82     @Mock
83     private HttpClient client1;
84
85     @Mock
86     private HttpClient client2;
87
88     @Mock
89     private Response response1;
90
91     @Mock
92     private Response response2;
93
94     private List<PdpGroup> groups;
95
96     private PapParameterGroup savedPapParameterGroup;
97
98     /**
99      * Configures mocks and objects.
100      *
101      * @throws Exception if an error occurs
102      */
103     @Before
104     public void setUp() throws Exception {
105         MockitoAnnotations.initMocks(this);
106
107         groups = loadPdpGroupsFromFile().getGroups();
108         when(dao.getPdpGroups(any())).thenReturn(groups);
109
110         when(daofact.create()).thenReturn(dao);
111         Registry.newRegistry();
112         Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact);
113
114         when(papActivator.isAlive()).thenReturn(true);
115         Registry.register(PapConstants.REG_PAP_ACTIVATOR, papActivator);
116
117         if (ParameterService.contains(PAP_GROUP_PARAMS_NAME)) {
118             savedPapParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME);
119         }
120         CommonTestData testData = new CommonTestData();
121         ParameterService.register(testData.getPapParameterGroup(0), true);
122
123         when(client1.getName()).thenReturn(CLIENT_1);
124         when(client1.getBaseUrl()).thenReturn("url1");
125         when(response1.getStatus()).thenReturn(HttpURLConnection.HTTP_OK);
126         when(response1.readEntity(HealthCheckReport.class)).thenReturn(createReport(HttpURLConnection.HTTP_OK, true));
127         when(client1.get()).thenReturn(response1);
128
129         when(client2.getName()).thenReturn("client2");
130         when(client2.getBaseUrl()).thenReturn("url2");
131         when(response2.getStatus()).thenReturn(HttpURLConnection.HTTP_OK);
132         when(response2.readEntity(HealthCheckReport.class)).thenReturn(createReport(HttpURLConnection.HTTP_OK, true));
133         when(client2.get()).thenReturn(response2);
134
135         PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME);
136         List<BusTopicParams> params = papParameterGroup.getHealthCheckRestClientParameters();
137         when(clientFactory.build(params.get(0))).thenReturn(client1);
138         when(clientFactory.build(params.get(1))).thenReturn(client2);
139
140         PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
141             clientFactory);
142     }
143
144     /**
145      * Tear down.
146      */
147     @After
148     public void tearDown() {
149         if (savedPapParameterGroup != null) {
150             ParameterService.register(savedPapParameterGroup, true);
151         } else {
152             ParameterService.deregister(PAP_GROUP_PARAMS_NAME);
153         }
154         PolicyComponentsHealthCheckProvider.cleanup();
155     }
156
157
158     @Test
159     public void testFetchPolicyComponentsHealthStatus_allHealthy() {
160         PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider();
161         Pair<Status, Map<String, Object>> ret = provider.fetchPolicyComponentsHealthStatus();
162         assertEquals(Response.Status.OK, ret.getLeft());
163         assertTrue((Boolean) ret.getRight().get(HEALTHY));
164     }
165
166     @Test
167     public void testFetchPolicyComponentsHealthStatus_unhealthyClient() {
168         when(response1.getStatus()).thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR);
169         when(response1.readEntity(HealthCheckReport.class))
170             .thenReturn(createReport(HttpURLConnection.HTTP_INTERNAL_ERROR, false));
171         Map<String, Object> result = callFetchPolicyComponentsHealthStatus();
172         assertFalse((Boolean) result.get(HEALTHY));
173         HealthCheckReport report = (HealthCheckReport) result.get(CLIENT_1);
174         assertFalse(report.isHealthy());
175
176         when(response1.getStatus()).thenReturn(HttpURLConnection.HTTP_OK);
177         when(response1.readEntity(HealthCheckReport.class)).thenReturn(createReport(HttpURLConnection.HTTP_OK, false));
178         Map<String, Object> result2 = callFetchPolicyComponentsHealthStatus();
179         assertFalse((Boolean) result2.get(HEALTHY));
180         HealthCheckReport report2 = (HealthCheckReport) result.get(CLIENT_1);
181         assertFalse(report2.isHealthy());
182     }
183
184     @SuppressWarnings("unchecked")
185     @Test
186     public void testFetchPolicyComponentsHealthStatus_unhealthyPdps() {
187         // Get a PDP and set it unhealthy
188         groups.get(0).getPdpSubgroups().get(0).getPdpInstances().get(0).setHealthy(PdpHealthStatus.NOT_HEALTHY);
189         Map<String, Object> result = callFetchPolicyComponentsHealthStatus();
190         Map<String, List<Pdp>> pdpListWithType = (Map<String, List<Pdp>>) result.get(PapConstants.POLICY_PDPS);
191         assertEquals(2, pdpListWithType.size());
192         assertFalse((Boolean) result.get(HEALTHY));
193     }
194
195     @Test
196     public void testFetchPolicyComponentsHealthStatus_unhealthyPap() {
197         when(papActivator.isAlive()).thenReturn(false);
198         Map<String, Object> result = callFetchPolicyComponentsHealthStatus();
199         assertFalse((Boolean) result.get(HEALTHY));
200         HealthCheckReport report = (HealthCheckReport) result.get(PapConstants.POLICY_PAP);
201         assertFalse(report.isHealthy());
202     }
203
204     private Map<String, Object> callFetchPolicyComponentsHealthStatus() {
205         PolicyComponentsHealthCheckProvider provider = new PolicyComponentsHealthCheckProvider();
206         return provider.fetchPolicyComponentsHealthStatus().getRight();
207     }
208
209     private HealthCheckReport createReport(int code, boolean healthy) {
210         HealthCheckReport report = new HealthCheckReport();
211         report.setName("name");
212         report.setUrl("url");
213         report.setCode(code);
214         report.setHealthy(healthy);
215         report.setMessage("message");
216         return report;
217     }
218
219     private static PdpGroups loadPdpGroupsFromFile() {
220         final File propFile = new File(ResourceUtils.getFilePath4Resource(PDP_GROUP_DATA_FILE));
221         try {
222             Coder coder = new StandardCoder();
223             return coder.decode(propFile, PdpGroups.class);
224         } catch (final CoderException e) {
225             throw new RuntimeException(e);
226         }
227     }
228 }