b566714599f840536ee6cd4064f9b34da737ba02
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / ProviderSuper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Nordix Foundation.
7  * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pap.main.rest;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.junit.Assert.assertEquals;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.times;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32
33 import io.micrometer.core.instrument.MeterRegistry;
34 import java.io.File;
35 import java.util.ArrayList;
36 import java.util.Collections;
37 import java.util.List;
38 import java.util.stream.Collectors;
39 import org.junit.Before;
40 import org.mockito.ArgumentCaptor;
41 import org.mockito.Captor;
42 import org.mockito.Mock;
43 import org.mockito.MockitoAnnotations;
44 import org.onap.policy.common.utils.coder.Coder;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.ResourceUtils;
48 import org.onap.policy.common.utils.services.Registry;
49 import org.onap.policy.models.pap.concepts.PolicyNotification;
50 import org.onap.policy.models.pdp.concepts.PdpGroup;
51 import org.onap.policy.models.pdp.concepts.PdpGroups;
52 import org.onap.policy.models.pdp.concepts.PdpStateChange;
53 import org.onap.policy.models.pdp.concepts.PdpUpdate;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
56 import org.onap.policy.pap.main.PapConstants;
57 import org.onap.policy.pap.main.comm.PdpModifyRequestMap;
58 import org.onap.policy.pap.main.notification.PolicyNotifier;
59 import org.onap.policy.pap.main.service.PdpGroupService;
60 import org.onap.policy.pap.main.service.PolicyAuditService;
61 import org.onap.policy.pap.main.service.PolicyStatusService;
62 import org.onap.policy.pap.main.service.ToscaServiceTemplateService;
63
64 /**
65  * Super class for TestPdpGroupDeployProviderXxx classes.
66  */
67 public class ProviderSuper {
68     private static final Coder coder = new StandardCoder();
69     public static final String DEFAULT_USER = "PAP_TEST";
70
71     @Mock
72     protected PdpGroupService pdpGroupService;
73
74     @Mock
75     protected PolicyStatusService policyStatusService;
76
77     @Mock
78     protected PolicyAuditService policyAuditService;
79
80     @Mock
81     protected ToscaServiceTemplateService toscaService;
82
83     @Mock
84     protected PolicyNotifier notifier;
85
86     /**
87      * Used to capture input to dao.updatePdpGroups() and dao.createPdpGroups().
88      */
89     @Captor
90     private ArgumentCaptor<List<PdpGroup>> updateCaptor;
91
92     protected Object lockit;
93     protected PdpModifyRequestMap reqmap;
94     protected ToscaPolicy policy1;
95     protected PapStatisticsManager statsmanager;
96     protected MeterRegistry meterRegistry;
97
98     /**
99      * Configures DAO, captors, and various mocks.
100      */
101     @Before
102     public void setUp() throws Exception {
103
104         Registry.newRegistry();
105
106         MockitoAnnotations.openMocks(this);
107
108         reqmap = mock(PdpModifyRequestMap.class);
109
110         lockit = new Object();
111         policy1 = loadPolicy("policy.json");
112         statsmanager = mock(PapStatisticsManager.class);
113
114         meterRegistry = mock(MeterRegistry.class);
115
116         List<PdpGroup> groups = loadGroups("groups.json");
117
118         when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups);
119
120         when(pdpGroupService.createPdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class));
121         when(pdpGroupService.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class));
122
123         Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, lockit);
124         Registry.register(PapConstants.REG_PDP_MODIFY_MAP, reqmap);
125         Registry.register(PapConstants.REG_STATISTICS_MANAGER, statsmanager);
126         Registry.register(PapConstants.REG_METER_REGISTRY, meterRegistry);
127
128     }
129
130     /**
131      * Initialize services to the provider for tests.
132      *
133      * @param prov the provider
134      */
135     public void initialize(ProviderBase prov) {
136         prov.setPdpGroupService(pdpGroupService);
137         prov.setPolicyAuditService(policyAuditService);
138         prov.setPolicyStatusService(policyStatusService);
139         prov.setToscaService(toscaService);
140         prov.setPolicyNotifier(notifier);
141         prov.initialize();
142     }
143
144     protected void assertGroup(List<PdpGroup> groups, String name) {
145         PdpGroup group = groups.remove(0);
146
147         assertEquals(name, group.getName());
148     }
149
150     protected void assertUpdateIgnorePolicy(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
151
152         PdpUpdate update = updates.remove(0);
153
154         assertEquals(groupName, update.getPdpGroup());
155         assertEquals(pdpType, update.getPdpSubgroup());
156         assertEquals(pdpName, update.getName());
157     }
158
159     /**
160      * Gets the input to the create() method.
161      *
162      * @return the input that was passed to the dao.updatePdpGroups() method
163      * @throws Exception if an error occurred
164      */
165     protected List<PdpGroup> getGroupCreates() throws Exception {
166         verify(pdpGroupService).createPdpGroups(updateCaptor.capture());
167
168         return copyList(updateCaptor.getValue());
169     }
170
171     /**
172      * Gets the input to the update() method.
173      *
174      * @return the input that was passed to the dao.updatePdpGroups() method
175      * @throws Exception if an error occurred
176      */
177     protected List<PdpGroup> getGroupUpdates() throws Exception {
178         verify(pdpGroupService).updatePdpGroups(updateCaptor.capture());
179
180         return copyList(updateCaptor.getValue());
181     }
182
183     /**
184      * Gets the state-changes that were added to the request map.
185      *
186      * @param count the number of times the method is expected to have been called
187      * @return the state-changes that were added to the request map
188      */
189     protected List<PdpStateChange> getStateChangeRequests(int count) {
190         ArgumentCaptor<PdpStateChange> captor = ArgumentCaptor.forClass(PdpStateChange.class);
191
192         verify(reqmap, times(count)).addRequest(any(), captor.capture());
193
194         return captor.getAllValues().stream().filter(req -> req != null).collect(Collectors.toList());
195     }
196
197     /**
198      * Gets the updates that were added to the request map.
199      *
200      * @param count the number of times the method is expected to have been called
201      * @return the updates that were added to the request map
202      */
203     protected List<PdpUpdate> getUpdateRequests(int count) {
204         ArgumentCaptor<PdpUpdate> captor = ArgumentCaptor.forClass(PdpUpdate.class);
205
206         verify(reqmap, times(count)).addRequest(captor.capture(), any());
207
208         return captor.getAllValues().stream().filter(req -> req != null).collect(Collectors.toList());
209     }
210
211     /**
212      * Copies a list and sorts it by group name.
213      *
214      * @param source source list to copy
215      * @return a copy of the source list
216      */
217     private List<PdpGroup> copyList(List<PdpGroup> source) {
218         List<PdpGroup> newlst = new ArrayList<>(source);
219         Collections.sort(newlst, (left, right) -> left.getName().compareTo(right.getName()));
220         return newlst;
221     }
222
223     /**
224      * Loads a list of groups.
225      *
226      * @param fileName name of the file from which to load
227      * @return a list of groups
228      */
229     protected List<PdpGroup> loadGroups(String fileName) {
230         return loadPdpGroups(fileName).getGroups();
231     }
232
233     /**
234      * Loads a PdpGroups.
235      *
236      * @param fileName name of the file from which to load
237      * @return a PdpGroups
238      */
239     protected PdpGroups loadPdpGroups(String fileName) {
240         return loadFile(fileName, PdpGroups.class);
241     }
242
243     /**
244      * Loads a group.
245      *
246      * @param fileName name of the file from which to load
247      * @return a group
248      */
249     protected PdpGroup loadGroup(String fileName) {
250         return loadFile(fileName, PdpGroup.class);
251     }
252
253     /**
254      * Loads a list of policies.
255      *
256      * @param fileName name of the file from which to load
257      * @return a list of policies
258      */
259     protected List<ToscaPolicy> loadPolicies(String fileName) {
260         return loadFile(fileName, PolicyList.class).policies;
261     }
262
263     /**
264      * Loads a policy.
265      *
266      * @param fileName name of the file from which to load
267      * @return a policy
268      */
269     protected ToscaPolicy loadPolicy(String fileName) {
270         return loadFile(fileName, ToscaPolicy.class);
271     }
272
273     /**
274      * Loads a policy type.
275      *
276      * @param fileName name of the file from which to load
277      * @return a policy type
278      */
279     protected ToscaPolicyType loadPolicyType(String fileName) {
280         return loadFile(fileName, ToscaPolicyType.class);
281     }
282
283     /**
284      * Loads an object from a JSON file.
285      *
286      * @param fileName name of the file from which to load
287      * @param clazz the class of the object to be loaded
288      * @return the object that was loaded from the file
289      */
290     protected <T> T loadFile(String fileName, Class<T> clazz) {
291         File propFile = new File(ResourceUtils.getFilePath4Resource("simpleDeploy/" + fileName));
292         try {
293             return coder.decode(propFile, clazz);
294
295         } catch (CoderException e) {
296             throw new RuntimeException(e);
297         }
298     }
299
300     /**
301      * Verifies that an empty notification was published.
302      */
303     protected void checkEmptyNotification() {
304         ArgumentCaptor<PolicyNotification> captor = ArgumentCaptor.forClass(PolicyNotification.class);
305         verify(notifier).publish(captor.capture());
306         assertThat(captor.getValue().isEmpty()).isTrue();
307     }
308
309     /**
310      * Wraps a list of policies. The decoder doesn't work with generic lists, so we wrap
311      * the list and decode it into the wrapper before extracting the list contents.
312      */
313     private static class PolicyList {
314         private List<ToscaPolicy> policies;
315     }
316 }