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