Implant vid-app-common org.onap.vid.job (main and test)
[vid.git] / vid-app-common / src / test / java / org / onap / vid / aai / AaiClientTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.vid.aai;
22
23 import static java.util.stream.Collectors.toList;
24 import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
25 import static org.hamcrest.MatcherAssert.assertThat;
26 import static org.hamcrest.Matchers.containsInAnyOrder;
27 import static org.hamcrest.Matchers.containsString;
28 import static org.hamcrest.Matchers.either;
29 import static org.hamcrest.Matchers.hasProperty;
30 import static org.hamcrest.Matchers.instanceOf;
31 import static org.hamcrest.Matchers.is;
32 import static org.hamcrest.Matchers.sameInstance;
33 import static org.mockito.ArgumentMatchers.any;
34 import static org.mockito.ArgumentMatchers.anyBoolean;
35 import static org.mockito.ArgumentMatchers.anyString;
36 import static org.mockito.ArgumentMatchers.argThat;
37 import static org.mockito.ArgumentMatchers.eq;
38 import static org.mockito.ArgumentMatchers.isNull;
39 import static org.mockito.ArgumentMatchers.nullable;
40 import static org.mockito.Mockito.mock;
41 import static org.mockito.Mockito.verify;
42 import static org.mockito.Mockito.when;
43 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
44 import static org.onap.vid.utils.Unchecked.toURI;
45 import static org.testng.Assert.assertEquals;
46 import static org.testng.Assert.assertFalse;
47 import static org.testng.Assert.assertNull;
48 import static org.testng.Assert.fail;
49
50 import com.fasterxml.jackson.core.JsonProcessingException;
51 import com.fasterxml.jackson.databind.ObjectMapper;
52 import com.google.common.collect.ImmutableList;
53 import java.io.FileNotFoundException;
54 import java.io.IOException;
55 import java.net.URI;
56 import java.security.cert.CertificateException;
57 import java.util.ArrayList;
58 import java.util.Map;
59 import java.util.function.BiConsumer;
60 import java.util.function.Function;
61 import java.util.stream.Stream;
62 import javax.crypto.BadPaddingException;
63 import javax.net.ssl.SSLHandshakeException;
64 import javax.servlet.ServletContext;
65 import javax.ws.rs.ProcessingException;
66 import javax.ws.rs.client.Client;
67 import javax.ws.rs.core.Response;
68 import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
69 import org.apache.commons.lang3.builder.ToStringStyle;
70 import org.apache.commons.lang3.exception.ExceptionUtils;
71 import org.apache.commons.lang3.reflect.FieldUtils;
72 import org.apache.commons.lang3.tuple.Pair;
73 import org.apache.http.HttpStatus;
74 import org.mockito.Mockito;
75 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
76 import org.onap.portalsdk.core.util.SystemProperties;
77 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
78 import org.onap.vid.aai.model.CustomQuerySimpleResult;
79 import org.onap.vid.aai.model.ModelVer;
80 import org.onap.vid.aai.model.ModelVersions;
81 import org.onap.vid.aai.model.PortDetailsTranslator;
82 import org.onap.vid.aai.model.Properties;
83 import org.onap.vid.aai.model.RelatedToProperty;
84 import org.onap.vid.aai.model.ResourceType;
85 import org.onap.vid.aai.model.SimpleResult;
86 import org.onap.vid.aai.util.AAIRestInterface;
87 import org.onap.vid.aai.util.CacheProvider;
88 import org.onap.vid.aai.util.HttpsAuthClient;
89 import org.onap.vid.aai.util.ServletRequestHelper;
90 import org.onap.vid.aai.util.SystemPropertyHelper;
91 import org.onap.vid.controller.LocalWebConfig;
92 import org.onap.vid.exceptions.GenericUncheckedException;
93 import org.onap.vid.model.Subscriber;
94 import org.onap.vid.model.SubscriberList;
95 import org.onap.vid.model.probes.ExternalComponentStatus;
96 import org.onap.vid.model.probes.HttpRequestMetadata;
97 import org.onap.vid.model.probes.StatusMetadata;
98 import org.onap.vid.testUtils.TestUtils;
99 import org.onap.vid.utils.Unchecked;
100 import org.springframework.http.HttpMethod;
101 import org.springframework.test.context.ContextConfiguration;
102 import org.springframework.test.context.web.WebAppConfiguration;
103 import org.testng.Assert;
104 import org.testng.annotations.BeforeMethod;
105 import org.testng.annotations.DataProvider;
106 import org.testng.annotations.Test;
107 import sun.security.provider.certpath.SunCertPathBuilderException;
108 import sun.security.validator.ValidatorException;
109
110 @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class})
111 @WebAppConfiguration
112 public class AaiClientTest {
113
114     private final String NO_LCP_REGION_AND_TENANTS_MSG = "A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'";
115     private AaiClient aaiClientMock;
116     private ServletContext servletContext;
117
118     @BeforeMethod
119     public void initMocks(){
120         aaiClientMock = mock(AaiClient.class);
121         aaiClientMock.logger = mock(EELFLoggerDelegate.class);
122         aaiClientMock.objectMapper = new ObjectMapper();
123         servletContext = mock(ServletContext.class);
124
125         when(servletContext.getRealPath(any(String.class))).thenReturn("");
126
127         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null);
128         when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null);
129     }
130
131     @DataProvider
132     public static Object[][] logicalLinkData() {
133         return new Object[][] {
134                 {"", "network/logical-links/logical-link/"},
135                 {"link", "network/logical-links/logical-link/link"}
136         };
137     }
138
139     @Test(dataProvider = "logicalLinkData")
140     public void getLogicalLink_Link_Is_Empty(String link, String expectedUrl) {
141
142         when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod();
143         aaiClientMock.getLogicalLink(link);
144         verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class));
145     }
146
147     @DataProvider
148     public static Object[][] subscribersResults() {
149         return new Object[][] {
150                 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber());  add(new Subscriber()); }}), true},
151                 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); }}), true},
152                 {new SubscriberList(new ArrayList<Subscriber>()), false}
153         };
154     }
155
156     @Test(dataProvider = "subscribersResults")
157     public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){
158         ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata(
159                 HttpMethod.GET,
160                 200,
161                 "url",
162                 "rawData",
163                 isAvailable ? "OK" : "No subscriber received",
164                 0
165         ));
166         Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
167                 new AaiResponseWithRequestInfo<>(
168                         HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200),
169                         "rawData"));
170         Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
171         ExternalComponentStatus result  = aaiClientMock.probeComponent();
172         assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus)));
173         assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata())));
174     }
175
176     @Test(expectedExceptions = Exception.class)
177     public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() {
178         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
179         final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity");
180         mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
181         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
182
183         try {
184
185             aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
186
187         } catch (Exception e) {
188             assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
189             ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e);
190             assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
191             assertThat(e2.getRawData(), is("entity"));
192             assertThat(e2.getHttpMethod(), is(HttpMethod.GET));
193             assertThat(e2.getRequestedUrl(), is("/my/mocked/url"));
194
195             throw e;
196         }
197     }
198
199     @Test(expectedExceptions = Exception.class)
200     public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() {
201         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
202         final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity");
203         mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
204         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
205
206         try {
207
208             aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
209
210         } catch (Exception e) {
211             assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
212             assertThat(e.getCause(),
213                     hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class)))
214             );
215             throw e;
216         }
217     }
218
219     @Test
220     public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() {
221         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
222         final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
223                 "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }");
224         mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
225
226         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
227
228         final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
229
230         assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo"));
231         assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar"));
232     }
233
234     private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
235         return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
236     }
237
238     private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) {
239         final Response mockResponse = mock(Response.class);
240         when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
241         when(mockResponse.getStatusInfo()).thenReturn(status);
242         when(mockResponse.readEntity(String.class)).thenReturn(entity);
243         return new ResponseWithRequestInfo(mockResponse, requestUrl, method);
244     }
245
246     //serialize fields except of fields we cannot know ahead of time
247     private static String requestMetadataReflected(StatusMetadata metadata) {
248         return new ReflectionToStringBuilder(metadata, ToStringStyle.SHORT_PREFIX_STYLE)
249                 .setExcludeFieldNames("duration")
250                 .toString();
251     }
252
253     private static String statusDataReflected(ExternalComponentStatus status) {
254         return new ReflectionToStringBuilder(status, ToStringStyle.SHORT_PREFIX_STYLE)
255                 .setExcludeFieldNames("metadata")
256                 .toString();
257     }
258
259     @DataProvider
260     public static Object[][] rawData() {
261         return new Object[][]{
262                 {"errorMessage", }, {""}, {null}
263         };
264     }
265
266     @Test(dataProvider = "rawData")
267     public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){
268         Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
269                 new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null,
270                         rawData));
271         ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
272         assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
273         assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), rawData);
274     }
275
276     @DataProvider
277     public static Object[][] exceptions() {
278         return new Object[][] {
279                 {"NullPointerException", "errorMessage",
280                         new ExceptionWithRequestInfo(HttpMethod.GET, "url",
281                                 "errorMessage", null, new NullPointerException())},
282                 {"RuntimeException", null,
283                         new ExceptionWithRequestInfo(HttpMethod.GET, "url",
284                                 null, null, new RuntimeException())},
285                 {"RuntimeException", null,
286                         new RuntimeException()},
287         };
288     }
289
290     @Test(dataProvider = "exceptions")
291     public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){
292         Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception);
293         ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
294         if (exception instanceof ExceptionWithRequestInfo) {
295             assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
296             assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), expectedRawData);
297         }
298         assertThat(result.getMetadata().getDescription(), containsString(description));
299     }
300
301     private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() {
302         Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
303         ExternalComponentStatus result  = aaiClientMock.probeComponent();
304         assertFalse(result.isAvailable());
305         return result;
306     }
307
308
309     @Test
310     public void getTenants_Arguments_Are_Null_Or_Empty() {
311
312         when(aaiClientMock.getTenants(any(), any())).thenCallRealMethod();
313
314         AaiResponse response = aaiClientMock.getTenants("", "");
315
316         assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
317
318
319         response = aaiClientMock.getTenants(null, null);
320
321         assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
322     }
323
324     @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG)
325     public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() {
326
327         when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
328
329         Response generalEmptyResponse = mock(Response.class);
330         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
331
332         aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
333     }
334
335     @Test
336     public void whenCacheThrowException_thenGetTenantReturnAaiResponse() {
337         CacheProvider mockCacheProvider = mock(CacheProvider.class);
338         CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class);
339         AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider);
340
341         when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache);
342         when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG));
343         AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType");
344         assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode());
345         assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage());
346     }
347
348     @Test
349     public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() {
350
351         when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
352
353
354         Response generalEmptyResponse = mock(Response.class);
355
356         when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw);
357         when(generalEmptyResponse.getStatus()).thenReturn(200);
358         when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK);
359
360
361         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
362
363         AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
364
365         GetTenantsResponse[] tenants = response.getT();
366
367         Assert.assertTrue(response.t.length> 0);
368
369         Assert.assertEquals(tenants[0].cloudOwner,"irma-aic-cloud-owner");
370     }
371
372     final String tenantResponseRaw ="" +
373             "{" +
374             "\"service-type\": \"VIRTUAL USP\"," +
375             "\"resource-version\": \"1494001841964\"," +
376             "\"relationship-list\": {" +
377             "\"relationship\": [{" +
378             "\"related-to\": \"tenant\"," +
379             "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," +
380             "\"relationship-data\": [{" +
381             "\"relationship-key\": \"cloud-region.cloud-owner\"," +
382             "\"relationship-value\": \"irma-aic-cloud-owner\"" +
383             "}," +
384             "{" +
385             "\"relationship-key\": \"cloud-region.cloud-region-id\"," +
386             "\"relationship-value\": \"AAIAIC25\"" +
387             "}," +
388             "{" +
389             "\"relationship-key\": \"tenant.tenant-id\"," +
390             "\"relationship-value\": \"092eb9e8e4b7412e8787dd091bc58e86\"" +
391             "}" +
392             "]," +
393             "\"related-to-property\": [{" +
394             "\"property-key\": \"tenant.tenant-name\"," +
395             "\"property-value\": \"USP-SIP-IC-24335-T-01\"" +
396             "}]" +
397             "}]" +
398             "}" +
399             "}";
400
401     final String vfModuleHomingResponseRaw ="{" +
402             "    \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," +
403             "    \"vf-module-name\": \"apndns_az_02_module_1\"," +
404             "    \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," +
405             "    \"orchestration-status\": \"active\"," +
406             "    \"is-base-vf-module\": false," +
407             "    \"resource-version\": \"1530559380383\"," +
408             "    \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," +
409             "    \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," +
410             "    \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," +
411             "    \"module-index\": 0," +
412             "    \"relationship-list\": {" +
413             "        \"relationship\": [" +
414             "            {" +
415             "                \"related-to\": \"l3-network\"," +
416             "                \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
417             "                \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," +
418             "                \"relationship-data\": [" +
419             "                    {" +
420             "                        \"relationship-key\": \"l3-network.network-id\"," +
421             "                        \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" +
422             "                    }" +
423             "                ]," +
424             "                \"related-to-property\": [" +
425             "                    {" +
426             "                        \"property-key\": \"l3-network.network-name\"," +
427             "                        \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" +
428             "                    }" +
429             "                ]" +
430             "            }," +
431             "            {" +
432             "                \"related-to\": \"l3-network\"," +
433             "                \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
434             "                \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," +
435             "                \"relationship-data\": [" +
436             "                    {" +
437             "                        \"relationship-key\": \"l3-network.network-id\"," +
438             "                        \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" +
439             "                    }" +
440             "                ]," +
441             "                \"related-to-property\": [" +
442             "                    {" +
443             "                        \"property-key\": \"l3-network.network-name\"," +
444             "                        \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" +
445             "                    }" +
446             "                ]" +
447             "            }," +
448             "            {" +
449             "                \"related-to\": \"volume-group\"," +
450             "                \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
451             "                \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," +
452             "                \"relationship-data\": [" +
453             "                    {" +
454             "                        \"relationship-key\": \"cloud-region.cloud-owner\"," +
455             "                        \"relationship-value\": \"irma-aic\"" +
456             "                    }," +
457             "                    {" +
458             "                        \"relationship-key\": \"cloud-region.cloud-region-id\"," +
459             "                        \"relationship-value\": \"rdm5b\"" +
460             "                    }," +
461             "                    {" +
462             "                        \"relationship-key\": \"volume-group.volume-group-id\"," +
463             "                        \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" +
464             "                    }" +
465             "                ]" +
466             "            }," +
467             "            {" +
468             "                \"related-to\": \"vserver\"," +
469             "                \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
470             "                \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," +
471             "                \"relationship-data\": [" +
472             "                    {" +
473             "                        \"relationship-key\": \"cloud-region.cloud-owner\"," +
474             "                        \"relationship-value\": \"irma-aic\"" +
475             "                    }," +
476             "                    {" +
477             "                        \"relationship-key\": \"cloud-region.cloud-region-id\"," +
478             "                        \"relationship-value\": \"rdm5b\"" +
479             "                    }," +
480             "                    {" +
481             "                        \"relationship-key\": \"tenant.tenant-id\"," +
482             "                        \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" +
483             "                    }," +
484             "                    {" +
485             "                        \"relationship-key\": \"vserver.vserver-id\"," +
486             "                        \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" +
487             "                    }" +
488             "                ]," +
489             "                \"related-to-property\": [" +
490             "                    {" +
491             "                        \"property-key\": \"vserver.vserver-name\"," +
492             "                        \"property-value\": \"zrdm5bfapn01dns002\"" +
493             "                    }" +
494             "                ]" +
495             "            }" +
496             "        ]" +
497             "    }" +
498             "}";
499     @Test
500     public void get_homingDataForVfModule() {
501         when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
502
503         Response homingResponse = mock(Response.class);
504
505         when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw);
506         when(homingResponse.getStatus()).thenReturn(200);
507         when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK);
508
509
510         when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse);
511
512         GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
513
514         Assert.assertEquals(tenant.cloudOwner,"irma-aic" );
515         Assert.assertEquals(tenant.cloudRegionID,"rdm5b");
516         Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91");
517
518     }
519     @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'")
520     public void getVfMoudule_Homing_Arguments_Are_Valid_But_Not_Exists() {
521         when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
522
523         Response generalEmptyResponse = mock(Response.class);
524         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
525
526         aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
527     }
528
529     @DataProvider
530     public static Object[][] invalidDataId() {
531         return new String[][] {
532                 {""},
533                 {null}
534         };
535     }
536
537     @Test(dataProvider = "invalidDataId", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.")
538     public void getVfMoudule_Homing_Arguments_Are_Empty_Or_Null(String data) {
539         when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod();
540              aaiClientMock.getHomingDataByVfModule(data, data);
541     }
542
543     @DataProvider
544     public static Object[][] resourceTypesProvider() {
545         return new Object[][] {
546                 {"service-instance", ResourceType.SERVICE_INSTANCE},
547                 {"generic-vnf", ResourceType.GENERIC_VNF},
548                 {"vf-module", ResourceType.VF_MODULE}
549         };
550     }
551
552     @DataProvider
553     public static Object[][] nameAndResourceTypeProvider() {
554         return new Object[][] {
555                 {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"},
556                 {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"},
557                 {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"},
558                 {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"},
559                 {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=MjVg1234"}
560         };
561     }
562
563     @Test(dataProvider = "nameAndResourceTypeProvider")
564     public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) {
565         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
566         ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}");
567
568         when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean()))
569                 .thenReturn(responseWithRequestInfo);
570
571         AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
572
573         aaiClient.isNodeTypeExistsByName(name, type);
574     }
575
576     @DataProvider
577     public static Object[][] aaiClientInternalExceptions() {
578         return Stream.<Pair<Class<? extends Throwable>, UncheckedBiConsumer<HttpsAuthClient, Client>>>of(
579
580                 // Exception out of httpsAuthClientMock
581                 Pair.of(CertificateException.class, (httpsAuthClientMock, javaxClientMock) -> {
582                     final CertificateException e0 = new CertificateException("No X509TrustManager implementation available");
583                     SSLHandshakeException e = new SSLHandshakeException(e0.toString());
584                     e.initCause(e0);
585
586                     when(httpsAuthClientMock.getClient(any())).thenThrow(e);
587                 }),
588
589                 Pair.of(StringIndexOutOfBoundsException.class, mockExceptionOnClientProvider(new StringIndexOutOfBoundsException(4))),
590
591                 Pair.of(NullPointerException.class, mockExceptionOnClientProvider(new NullPointerException("null"))),
592
593                 Pair.of(FileNotFoundException.class, mockExceptionOnClientProvider(new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12"))),
594
595                 Pair.of(BadPaddingException.class, mockExceptionOnClientProvider(
596                         new IOException("keystore password was incorrect", new BadPaddingException("Given final block not properly padded")))
597                 ),
598                 Pair.of(GenericUncheckedException.class, mockExceptionOnClientProvider(new GenericUncheckedException("basa"))),
599
600                 Pair.of(NullPointerException.class, (httpsAuthClientMock, javaxClientMock) ->
601                         when(httpsAuthClientMock.getClient(any())).thenReturn(null)),
602
603
604                 // Exception out of javax's Client
605                 Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> {
606                     when(javaxClientMock.target(nullable(String.class))).thenThrow(
607                             new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))
608                     );
609                 }),
610
611                 Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> {
612                     SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target");
613                     when(javaxClientMock.target(nullable(String.class))).thenThrow(
614                             new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0))
615                     );
616                 }),
617
618                 Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) ->
619                         when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa")))
620
621         ).flatMap(l -> Stream.of(
622                 // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work
623                 ImmutableList.of(l.getLeft(), l.getRight(), true).toArray(),
624                 ImmutableList.of(l.getLeft(), l.getRight(), false).toArray()
625         )).collect(toList()).toArray(new Object[][]{});
626     }
627
628     private static UncheckedBiConsumer<HttpsAuthClient, Client> mockExceptionOnClientProvider(Exception e) {
629         return (httpsAuthClientMock, javaxClientMock) ->
630                 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
631     }
632
633     @Test(dataProvider = "aaiClientInternalExceptions")
634     public void propagateExceptions_internalsThrowException_ExceptionRethrown(Class<? extends Throwable> expectedType, BiConsumer<HttpsAuthClient, Client> setupMocks, boolean propagateExceptions) throws Exception {
635         /*
636         Call chain is like:
637             this test -> AaiClient -> AAIRestInterface -> HttpsAuthClient -> javax's Client
638
639         In this test, *AaiClient* and *AAIRestInterface* are under test (actual
640         implementation is used), while HttpsAuthClient and the javax's Client are
641         mocked to return pseudo-responses or - better- throw exceptions.
642          */
643
644         // prepare mocks
645         HttpsAuthClient httpsAuthClientMock = mock(HttpsAuthClient.class);
646         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
647         Client javaxClientMock = mocks.getFakeClient();
648         Response responseMock = mocks.getFakeResponse();
649
650         // prepare real AAIRestInterface and AaiClient, and wire mocks
651         AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, mock(ServletRequestHelper.class), mock(SystemPropertyHelper.class));
652         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
653         when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock);
654
655         // define atomic method under test, including reset of "aaiRestInterface.client"
656         final Function<Boolean, Response> doAaiGet = (propagateExceptions1) -> {
657             try {
658                 FieldUtils.writeField(aaiRestInterface, "client", null, true);
659                 return aaiClient.doAaiGet("uri", false, propagateExceptions1).getResponse();
660             } catch (IllegalAccessException e) {
661                 throw new RuntimeException(e);
662             }
663         };
664
665         // verify setup again
666         assertThat("mocks setup should make doAaiGet return our responseMock", doAaiGet.apply(true), is(sameInstance(responseMock)));
667
668
669         /// TEST:
670         setupMocks.accept(httpsAuthClientMock, javaxClientMock);
671
672         try {
673             final Response response = doAaiGet.apply(propagateExceptions);
674         } catch (Exception e) {
675             if (propagateExceptions) {
676                 assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
677                 return; // ok, done
678             } else {
679                 // Verify that "don't propagate" really still work
680                 Assert.fail("calling doAaiGet when propagateExceptions is false must result with no exception", e);
681             }
682         }
683
684         // If no exception caught
685         // We're asserting that the legacy behaviour is still in place. Hopefully
686         // one day we will remove the non-propagateExceptions case
687         assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)");
688     }
689
690     @DataProvider
691     public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() {
692
693         final String cloudRegion = "{" +
694                 "      \"cloud-owner\": \"mure-royo-ru22\"," +
695                 "      \"cloud-region-id\": \"ravitu\"," +
696                 "      \"cloud-type\": \"openstack\"," +
697                 "      \"resource-version\": \"1523631256125\"," +
698                 "      \"relationship-list\": {" +
699                 "        \"relationship\": [{" +
700                 "            \"related-to\": \"pserver\"" +
701                 "          }" +
702                 "        ]" +
703                 "      }" +
704                 "    }";
705
706         String bodyWith0 = "{  \"cloud-region\": [" + "  ]}";
707         String bodyWith1 = "{  \"cloud-region\": [" + cloudRegion + "  ]}";
708         String bodyWith2 = "{  \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + "  ]}";
709         String bodyWithDifferent2 = "{  \"cloud-region\": [" + cloudRegion + ", " +
710                 cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") +
711                 "]}";
712
713         return new Object[][] {
714                 { "regular single result", bodyWith1, false },
715                 { "exceptional empty result", bodyWith0, true },
716                 { "two same results", bodyWith2, false },
717                 { "two incoherent results", bodyWithDifferent2, true },
718         };
719     }
720
721     @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId")
722     public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) {
723         final String cloudRegion = "ravitu";
724         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
725         final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body);
726         when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)),
727                 isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean()))
728                 .thenReturn(responseWithRequestInfo);
729
730         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
731
732         try {
733             final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion);
734             if (expectingException) fail("expected failure on " + desc + ", got " + result);
735             else {
736                 assertThat(result, is("mure-royo-ru22"));
737             }
738         } catch (Exception e) {
739             if (!expectingException) throw e;
740             else {
741                 assertThat(e.toString(), either(
742                         containsString("No cloud-owner found for " + cloudRegion))
743                         .or(containsString("Conflicting cloud-owner found for " + cloudRegion)));
744             }
745         }
746     }
747
748     @DataProvider
749     public static Object[][]  cloudRegionAndTenantDataProvider() {
750         return new Object[][] {
751                 { "APPC-24595-T-IST-02C", "mtn23b" },
752                 { "APPC-24595-T-IST-02C", null },
753                 { null, "mtn23b" },
754                 { null, null },
755         };
756     }
757
758     @Test
759     public void testGetLatestVersionByInvariantId() throws IOException {
760
761         ModelVersions modelVersions = JACKSON_OBJECT_MAPPER.readValue("" +
762                 "{\n" +
763                 "    \"results\": [\n" +
764                 "        {\n" +
765                 "            \"model\": {\n" +
766                 "                \"model-invariant-id\": \"f6342be5-d66b-4d03-a1aa-c82c3094c4ea\",\n" +
767                 "                \"model-type\": \"service\",\n" +
768                 "                \"resource-version\": \"1534274421300\"\n" +
769                 "            }\n" +
770                 "        },\n" +
771                 "        {\n" +
772                 "            \"model-ver\": {\n" +
773                 "                \"model-version-id\": \"a92f899d-a3ec-465b-baed-1663b0a5aee1\",\n" +
774                 "                \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
775                 "                \"model-version\": \"bbb\",\n" +
776                 "                \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
777                 "                \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
778                 "                \"resource-version\": \"1534788756086\"\n" +
779                 "            }\n" +
780                 "        },\n" +
781                 "        {\n" +
782                 "            \"model-ver\": {\n" +
783                 "                \"model-version-id\": \"d2fda667-e92e-4cfa-9620-5da5de01a319\",\n" +
784                 "                \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
785                 "                \"model-version\": \"aaa\",\n" +
786                 "                \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
787                 "                \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
788                 "                \"resource-version\": \"1534444087221\"\n" +
789                 "            }\n" +
790                 "        }]}", ModelVersions.class);
791
792
793         final AaiClient aaiClient = new AaiClient(null, null, null);
794
795         assertThat(aaiClient.toModelVerStream(modelVersions).collect(toList()),
796                 containsInAnyOrder(
797                         hasProperty("modelVersionId", is("a92f899d-a3ec-465b-baed-1663b0a5aee1")),
798                         hasProperty("modelVersionId", is("d2fda667-e92e-4cfa-9620-5da5de01a319"))
799                 ));
800
801     }
802
803     @DataProvider
804     public static Object[][]  versionsDataProvider() {
805         return new Object[][] {
806                 { Stream.of("10","20","30"), "30" },
807                 { Stream.of("10","20","20"), "20" },
808                 { Stream.of("c","b","a"), "c" },
809                 { Stream.of("1.0","2.0","1.8"), "2.0" },
810                 { Stream.of("1.0.7","2.0.2","2.0.9"), "2.0.9" },
811                 { Stream.of("0","0","0"), "0" },
812                 { Stream.of("","10"), "10" },
813
814         };
815     }
816
817     @Test(dataProvider = "versionsDataProvider")
818     public void maxModelVer(Stream<String> input, String expected) {
819         Stream<ModelVer> modelVerStream = input.map(version -> {
820             ModelVer mv = new ModelVer();
821             mv.setModelVersion(version);
822             return mv;
823         });
824
825         final AaiClient aaiClient = new AaiClient(null, null, null);
826
827         assertThat(aaiClient.maxModelVer(modelVerStream), hasProperty("modelVersion", is(expected)));
828     }
829
830     @Test(expectedExceptions = GenericUncheckedException.class)
831     public void maxModelVerException() {
832         final AaiClient aaiClient = new AaiClient(null, null, null);
833         aaiClient.maxModelVer(Stream.of(new ModelVer()));
834     }
835     @Test(dataProvider = "cloudRegionAndTenantDataProvider")
836     public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException {
837         SimpleResult tenant = new SimpleResult();
838         if (tenantName != null) {
839             tenant.setJsonNodeType("tenant");
840             Properties tenantProps = new Properties();
841             tenantProps.setTenantName(tenantName);
842             tenant.setJsonProperties(tenantProps);
843         }
844
845         SimpleResult cloudRegion = new SimpleResult();
846         if (cloudRegionId != null) {
847             cloudRegion.setJsonNodeType("cloud-region");
848             Properties cloudRegionProps = new Properties();
849             cloudRegionProps.setCloudRegionId(cloudRegionId);
850             cloudRegion.setJsonProperties(cloudRegionProps);
851         }
852
853         CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion));
854         String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult);
855
856         AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
857         final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT);
858         when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")),
859                 any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean()))
860                 .thenReturn(responseWithRequestInfo);
861
862         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
863         Map<String, Properties> result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId");
864         if (tenantName != null) {
865             assertEquals(result.get("tenant").getTenantName(), tenantName);
866         } else {
867             assertNull(result.get("tenant"));
868         }
869
870         if (cloudRegionId != null) {
871             assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId);
872         } else {
873             assertNull(result.get("cloud-region"));
874         }
875     }
876
877     protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
878         when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean()))
879                 .thenReturn(responseWithRequestInfo);
880     }
881
882     @Test
883     public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() {
884         AAIRestInterface restInterface = mock(AAIRestInterface.class);
885         PortDetailsTranslator portDetailsTranslator = mock(PortDetailsTranslator.class);
886         Response response = mock(Response.class);
887         when(response.getStatus()).thenReturn(404);
888         when(response.readEntity(String.class)).thenReturn("sampleEntity");
889         when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND);
890         ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET);
891         when(restInterface.RestGet(eq("VidAaiController"), any(String.class),
892                 eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo);
893         AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null);
894
895
896         aaiClient.getAllSubscribers(true);
897
898         verify(response).readEntity(String.class);
899     }
900
901     @FunctionalInterface
902     public interface UncheckedBiConsumer<T, U> extends BiConsumer<T, U> {
903         @Override
904         default void accept(T t, U u) {
905             try {
906                 acceptThrows(t, u);
907             } catch (Exception e) {
908                 throw new RuntimeException(e);
909             }
910         }
911
912         void acceptThrows(T t, U u) throws Exception;
913     }
914
915 }