Implant vid-app-common org.onap.vid.job (main and test)
[vid.git] / vid-app-common / src / test / java / org / onap / vid / controller / AaiControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nokia.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.vid.controller;
23
24 import static org.mockito.ArgumentMatchers.any;
25 import static org.mockito.ArgumentMatchers.anyBoolean;
26 import static org.mockito.ArgumentMatchers.argThat;
27 import static org.mockito.ArgumentMatchers.booleanThat;
28 import static org.mockito.BDDMockito.given;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
33 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
34 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
35 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
36
37 import com.fasterxml.jackson.databind.ObjectMapper;
38 import com.google.common.collect.ImmutableList;
39 import com.google.common.collect.ImmutableMap;
40 import com.google.common.collect.ImmutableMultimap;
41 import com.google.common.collect.Lists;
42 import com.google.common.collect.Multimap;
43 import java.io.IOException;
44 import java.util.Map;
45 import java.util.UUID;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.ws.rs.core.Response;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.junit.runner.RunWith;
51 import org.mockito.Mock;
52 import org.mockito.MockitoAnnotations;
53 import org.mockito.junit.MockitoJUnitRunner;
54 import org.onap.vid.aai.AaiResponse;
55 import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData;
56 import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError;
57 import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk;
58 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
59 import org.onap.vid.aai.model.AaiGetAicZone.Zone;
60 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
61 import org.onap.vid.aai.model.PortDetailsTranslator.PortDetails;
62 import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsError;
63 import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsOk;
64 import org.onap.vid.aai.util.AAIRestInterface;
65 import org.onap.vid.properties.Features;
66 import org.onap.vid.roles.Role;
67 import org.onap.vid.model.VersionByInvariantIdsRequest;
68 import org.onap.vid.roles.RoleProvider;
69 import org.onap.vid.roles.RoleValidator;
70 import org.onap.vid.services.AaiService;
71 import org.onap.vid.utils.SystemPropertiesWrapper;
72 import org.springframework.http.HttpStatus;
73 import org.springframework.http.MediaType;
74 import org.springframework.test.web.servlet.MockMvc;
75 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
76 import org.togglz.core.manager.FeatureManager;
77
78 @RunWith(MockitoJUnitRunner.class)
79 public class AaiControllerTest {
80
81     private static final String ID_1 = "id1";
82     private static final String ID_2 = "id2";
83     private final ObjectMapper objectMapper = new ObjectMapper();
84     @Mock
85     private AaiService aaiService;
86     @Mock
87     private AAIRestInterface aaiRestInterface;
88     @Mock
89     private RoleProvider roleProvider;
90     @Mock
91     private SystemPropertiesWrapper systemPropertiesWrapper;
92
93     @Mock
94     private FeatureManager featureManager;
95
96     private MockMvc mockMvc;
97     private AaiController aaiController;
98
99     @Before
100     public void setUp() {
101         aaiController = new AaiController(aaiService, aaiRestInterface, roleProvider, systemPropertiesWrapper, featureManager);
102         mockMvc = MockMvcBuilders.standaloneSetup(aaiController).build();
103     }
104
105     @Test
106     public void getPortMirroringConfigData_givenIds_shouldReturnConfigDataMappedById() throws Exception {
107         PortMirroringConfigDataOk okConfigData = new PortMirroringConfigDataOk("foo");
108         PortMirroringConfigDataError errorConfigData = new PortMirroringConfigDataError("bar", "{ baz: qux }");
109         Map<String, PortMirroringConfigData> expectedJson = ImmutableMap.of(
110             ID_1, okConfigData,
111             ID_2, errorConfigData);
112         given(aaiService.getPortMirroringConfigData(ID_1)).willReturn(okConfigData);
113         given(aaiService.getPortMirroringConfigData(ID_2)).willReturn(errorConfigData);
114
115         mockMvc
116             .perform(get("/aai_getPortMirroringConfigsData")
117                 .param("configurationIds", ID_1, ID_2)
118                 .contentType(MediaType.APPLICATION_JSON)
119                 .accept(MediaType.APPLICATION_JSON))
120             .andExpect(status().isOk())
121             .andExpect(content().json(objectMapper.writeValueAsString(expectedJson)));
122     }
123
124     @Test
125     public void getPortMirroringSourcePorts_givenIds_shouldReturnPortDetailsMappedById() throws Exception {
126         PortDetailsOk portDetailsOk = new PortDetailsOk("foo", "testInterface", true);
127         PortDetailsError portDetailsError = new PortDetailsError("bar", "{ baz: qux }");
128         Multimap<String, PortDetails> expectedJson = ImmutableMultimap.of(
129             ID_1, portDetailsOk,
130             ID_2, portDetailsError);
131         given(aaiService.getPortMirroringSourcePorts(ID_1)).willReturn(Lists.newArrayList(portDetailsOk));
132         given(aaiService.getPortMirroringSourcePorts(ID_2)).willReturn(Lists.newArrayList(portDetailsError));
133
134         mockMvc
135             .perform(get("/aai_getPortMirroringSourcePorts")
136                 .param("configurationIds", ID_1, ID_2)
137                 .contentType(MediaType.APPLICATION_JSON)
138                 .accept(MediaType.APPLICATION_JSON))
139             .andExpect(status().isOk())
140             .andExpect(content().json(objectMapper.writeValueAsString(expectedJson.asMap())));
141     }
142
143     @Test
144     public void getNodeTemplateInstances_givenParams_shouldReturnCorrectResponse() throws Exception {
145         String globalCustomerId = "testCustomerId";
146         String serviceType = "testServiceType";
147         String modelVersionId = UUID.nameUUIDFromBytes("modelVersionId".getBytes()).toString();
148         String modelInvariantId = UUID.nameUUIDFromBytes("modelInvariantId".getBytes()).toString();
149         String cloudRegion = "testRegion";
150         String urlTemplate = "/aai_get_vnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}";
151         String expectedResponseBody = "myResponse";
152         AaiResponse<String> aaiResponse = new AaiResponse<>(expectedResponseBody, "", HttpStatus.OK.value());
153         given(aaiService
154             .getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion))
155             .willReturn(aaiResponse);
156
157         mockMvc
158             .perform(get(urlTemplate, globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion)
159                 .contentType(MediaType.APPLICATION_JSON)
160                 .accept(MediaType.APPLICATION_JSON))
161             .andExpect(status().isOk())
162             .andExpect(content().string(expectedResponseBody));
163     }
164
165     @Test
166     public void getAicZones_shouldReturnAaiZones_whenAaiHttpStatusIsOK() throws Exception {
167         AicZones aicZones = new AicZones(ImmutableList.of(new Zone("TEST_ZONE_ID", "TEST_ZONE_NAME")));
168         given(aaiService.getAaiZones()).willReturn(new AaiResponse(aicZones, "", HttpStatus.OK.value()));
169
170         mockMvc.perform(get("/aai_get_aic_zones")
171             .contentType(MediaType.APPLICATION_JSON)
172             .accept(MediaType.APPLICATION_JSON))
173             .andExpect(status().isOk())
174             .andExpect(content().json(objectMapper.writeValueAsString(aicZones)));
175     }
176
177     @Test
178     public void getAicZones_shouldReturnErrorResponse_whenAaiHttpStatusOtherThanOK() throws Exception {
179         String expectedErrorMessage = "Calling AAI Failed";
180         given(aaiService.getAaiZones())
181             .willReturn(new AaiResponse(null, expectedErrorMessage, HttpStatus.INTERNAL_SERVER_ERROR.value()));
182
183         mockMvc.perform(get("/aai_get_aic_zones")
184             .contentType(MediaType.APPLICATION_JSON)
185             .accept(MediaType.APPLICATION_JSON))
186             .andExpect(status().isInternalServerError())
187             .andExpect(content().string(expectedErrorMessage));
188     }
189
190     @Test
191     public void getSpecificPnf_shouldReturnPnfObjectForPnfId() throws Exception {
192         String pnfId = "MyPnfId";
193         Pnf pnf = Pnf.builder()
194             .withPnfId(pnfId)
195             .withPnfName("TestPnf")
196             .withPnfName2("pnfName2")
197             .withPnfName2Source("pnfNameSource")
198             .withEquipModel("model")
199             .withEquipType("type")
200             .withEquipVendor("vendor")
201             .build();
202         AaiResponse<Pnf> aaiResponse = new AaiResponse<>(pnf, "", HttpStatus.OK.value());
203         given(aaiService.getSpecificPnf(pnfId)).willReturn(aaiResponse);
204
205         mockMvc.perform(get("/aai_get_pnfs/pnf/{pnf_id}", pnfId)
206             .contentType(MediaType.APPLICATION_JSON)
207             .accept(MediaType.APPLICATION_JSON))
208             .andExpect(status().isOk())
209             .andExpect(content().json(objectMapper.writeValueAsString(pnf)));
210     }
211
212     @Test
213     public void getSpecificPnf_shouldHandleAAIServiceException() throws Exception {
214         String pnfId = "MyPnfId";
215         String expectedErrorMessage = "AAI Service Error";
216         given(aaiService.getSpecificPnf(pnfId)).willThrow(new RuntimeException(expectedErrorMessage));
217
218         mockMvc.perform(get("/aai_get_pnfs/pnf/{pnf_id}", pnfId)
219             .contentType(MediaType.APPLICATION_JSON)
220             .accept(MediaType.APPLICATION_JSON))
221             .andExpect(status().isInternalServerError())
222             .andExpect(content().string(expectedErrorMessage));
223     }
224
225     public void getPNFInstances_shouldReturnOKResponseFromAAIService() throws Exception {
226         String globalCustomerId = "testCustomerId";
227         String serviceType = "testServiceType";
228         String modelVersionId = UUID.nameUUIDFromBytes("modelVersionId".getBytes()).toString();
229         String modelInvariantId = UUID.nameUUIDFromBytes("modelInvariantId".getBytes()).toString();
230         String cloudRegion = "testRegion";
231         String equipVendor = "testVendor";
232         String equipModel = "model123";
233         String urlTemplate = "/aai_get_pnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}/{equipVendor}/{equipModel}";
234         String expectedResponseBody = "myResponse";
235         AaiResponse<String> aaiResponse = new AaiResponse<>(expectedResponseBody, "", HttpStatus.OK.value());
236
237         given(aaiService
238             .getPNFData(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion, equipVendor,
239                 equipModel)).willReturn(aaiResponse);
240
241         mockMvc.perform(
242             get(urlTemplate, globalCustomerId, serviceType, modelVersionId,
243                 modelInvariantId, cloudRegion, equipVendor, equipModel)
244                 .contentType(MediaType.APPLICATION_JSON)
245                 .accept(MediaType.APPLICATION_JSON))
246             .andExpect(status().isOk())
247             .andExpect(content().string(expectedResponseBody));
248     }
249
250     @Test
251     public void getVersionByInvariantId_shouldReturnOKResponse() throws Exception {
252         String expectedResponse = "OKResponse";
253         VersionByInvariantIdsRequest request = new VersionByInvariantIdsRequest();
254         request.versions = ImmutableList.of("ver1", "ver2");
255         Response response = mock(Response.class);
256         given(response.readEntity(String.class)).willReturn(expectedResponse);
257         given(aaiService
258             .getVersionByInvariantId(request.versions)).willReturn(response);
259
260         mockMvc.perform(
261             post("/aai_get_version_by_invariant_id")
262                 .content(new ObjectMapper().writeValueAsString(request))
263                 .contentType(MediaType.APPLICATION_JSON)
264                 .accept(MediaType.APPLICATION_JSON))
265             .andExpect(status().isOk())
266             .andExpect(content().string(expectedResponse));
267     }
268
269     @Test
270     public void getSubscriberDetailsOmitServiceInstances_reduceDepthEnabledAndOmitQueryParam() throws IOException {
271         getSubscriberDetailsOmitServiceInstances("some subscriber id",
272                 true, true, true);
273     }
274
275     @Test
276     public void getSubscriberDetailsOmitServiceInstances_reduceDepthDisabledAndOmitQueryParam() throws IOException {
277         getSubscriberDetailsOmitServiceInstances("another-subscriber-id-123",
278                 false, true, false);
279     }
280
281     @Test
282     public void getSubscriberDetailsOmitServiceInstances_reduceDepthDisabled() throws IOException {
283         getSubscriberDetailsOmitServiceInstances("123-456-789-123-345-567-6",
284                 false,  false,  false);
285     }
286
287     @Test
288     public void getSubscriberDetailsOmitServiceInstances_reduceDepthEnabled() throws IOException {
289         getSubscriberDetailsOmitServiceInstances("0000000000000000000000000",
290                 true, false,  false);
291     }
292
293     private void getSubscriberDetailsOmitServiceInstances(String subscriberId, boolean isFlag1906AaiSubDetailsReduceDepthEnabled,
294         boolean omitServiceInstancesQueryParam, boolean omitServiceInstancesExpectedGetSubscriberDataParam) throws IOException {
295         when(featureManager.isActive(Features.FLAG_1906_AAI_SUB_DETAILS_REDUCE_DEPTH)).thenReturn(isFlag1906AaiSubDetailsReduceDepthEnabled);
296         HttpServletRequest request = mock(HttpServletRequest.class);
297         when(roleProvider.getUserRoles(request)).thenReturn(ImmutableList.of(mock(Role.class), mock(Role.class)));
298         AaiResponse subscriberData = mock(AaiResponse.class);
299         when(subscriberData.getT()).thenReturn(null);
300         when(subscriberData.getHttpCode()).thenReturn(200);
301         when(aaiService.getSubscriberData(any(), any(), anyBoolean())).thenReturn(subscriberData);
302         aaiController.getSubscriberDetails(request, subscriberId, omitServiceInstancesQueryParam);
303         verify(aaiService).getSubscriberData(argThat(subscriberId::equals), any(RoleValidator.class), booleanThat(b -> omitServiceInstancesExpectedGetSubscriberDataParam == b));
304     }
305 }
306