2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.aai;
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;
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;
56 import java.security.cert.CertificateException;
57 import java.util.ArrayList;
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.Logging;
100 import org.onap.vid.utils.Unchecked;
101 import org.springframework.http.HttpMethod;
102 import org.springframework.test.context.ContextConfiguration;
103 import org.springframework.test.context.web.WebAppConfiguration;
104 import org.testng.Assert;
105 import org.testng.annotations.BeforeMethod;
106 import org.testng.annotations.DataProvider;
107 import org.testng.annotations.Test;
108 import sun.security.provider.certpath.SunCertPathBuilderException;
109 import sun.security.validator.ValidatorException;
111 @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class})
113 public class AaiClientTest {
115 private final String NO_LCP_REGION_AND_TENANTS_MSG = "A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'";
116 private AaiClient aaiClientMock;
117 private ServletContext servletContext;
120 public void initMocks(){
121 aaiClientMock = mock(AaiClient.class);
122 aaiClientMock.logger = mock(EELFLoggerDelegate.class);
123 aaiClientMock.objectMapper = new ObjectMapper();
124 servletContext = mock(ServletContext.class);
126 when(servletContext.getRealPath(any(String.class))).thenReturn("");
128 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null);
129 when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null);
133 public static Object[][] logicalLinkData() {
134 return new Object[][] {
135 {"", "network/logical-links/logical-link/"},
136 {"link", "network/logical-links/logical-link/link"}
140 private static String nfRoleOnly = "{\"start\":[\"/business/customers/customer/globalCustomerId1-360-as988q/service-subscriptions/service-subscription/TEST1-360/service-instances\"],\"query\":\"query/vnfs-fromServiceInstance-filter?nfRole=test360\"}";
141 private static String nfRoleAndCloudRegion = "{\"start\":[\"/business/customers/customer/globalCustomerId1-360-as988q/service-subscriptions/service-subscription/TEST1-360/service-instances\"],\"query\":\"query/vnfs-fromServiceInstance-filterByCloudRegion?nfRole=test360&cloudRegionID=cloudRegion-1\"}";
142 private static String cloudRegionOnly = "{\"start\":[\"/business/customers/customer/globalCustomerId1-360-as988q/service-subscriptions/service-subscription/TEST1-360/service-instances\"],\"query\":\"query/vnfs-fromServiceInstance-filterByCloudRegion?cloudRegionID=cloudRegion-1\"}";
143 private static String withoutNfroleAndCloudRegion = "{\"start\":[\"/business/customers/customer/globalCustomerId1-360-as988q/service-subscriptions/service-subscription/TEST1-360/service-instances\"],\"query\":\"query/vnfs-fromServiceInstance-filter\"}";
145 private static String responseJsonNfRole = "/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterNfRole.json";
146 private static String responseJsonCloudRegion ="/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterByCloudRegion.json";
150 public static Object[][] aaiPutCustomQueryData() {
151 return new Object[][] {
152 {"globalCustomerId1-360-as988q", "TEST1-360", "test360", null, nfRoleOnly, responseJsonNfRole, "908419144", 200},
153 {"globalCustomerId1-360-as988q", "TEST1-360", null, "cloudRegion-1", cloudRegionOnly, responseJsonCloudRegion, "1165906024", 200},
154 {"globalCustomerId1-360-as988q", "TEST1-360", "test360", "cloudRegion-1", nfRoleAndCloudRegion,
155 responseJsonCloudRegion, "1165906024", 200},
156 {"globalCustomerId1-360-as988q", "TEST1-360", null, null, withoutNfroleAndCloudRegion, responseJsonNfRole, "908419144", 200},
160 @Test(dataProvider = "aaiPutCustomQueryData")
161 public void testAaiPutCustomQueryByParams(String globalCustomerId, String serviceType, String nfRole, String cloudRegion, String expectedPayload, String responseBody, String expectedId, int responseHttpCode) {
162 String queryFormat = "query?format=simple";
163 final ResponseWithRequestInfo mockedResponseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
164 TestUtils.readFileAsString(responseBody),
165 "query?format=simple&Mock=True",
167 when(aaiClientMock.doAaiPut(eq(queryFormat), anyString(), anyBoolean(), anyBoolean())).thenReturn(mockedResponseWithRequestInfo);
168 when(aaiClientMock.getVnfsByParamsForChangeManagement(anyString(), anyString(), nullable(String.class), nullable(String.class))).thenCallRealMethod();
169 AaiResponse<AaiGetVnfResponse> response = aaiClientMock.getVnfsByParamsForChangeManagement(globalCustomerId, serviceType, nfRole, cloudRegion);
170 verify(aaiClientMock).doAaiPut(eq(queryFormat), eq(expectedPayload), eq(false), eq(false));
171 assertEquals(response.getHttpCode(), responseHttpCode);
172 assertEquals(response.getT().getResults().get(0).id, expectedId);
175 @Test(dataProvider = "logicalLinkData")
176 public void getLogicalLink_Link_Is_Empty(String link, String expectedUrl) {
178 when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod();
179 aaiClientMock.getLogicalLink(link);
180 verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class));
184 public static Object[][] subscribersResults() {
185 return new Object[][] {
186 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); add(new Subscriber()); }}), true},
187 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); }}), true},
188 {new SubscriberList(new ArrayList<Subscriber>()), false}
192 @Test(dataProvider = "subscribersResults")
193 public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){
194 ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata(
199 isAvailable ? "OK" : "No subscriber received",
202 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
203 new AaiResponseWithRequestInfo<>(
204 HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200),
206 Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
207 ExternalComponentStatus result = aaiClientMock.probeComponent();
208 assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus)));
209 assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata())));
212 @Test(expectedExceptions = Exception.class)
213 public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() {
214 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
215 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity");
216 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
217 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
221 aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
223 } catch (Exception e) {
224 assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
225 ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e);
226 assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
227 assertThat(e2.getRawData(), is("entity"));
228 assertThat(e2.getHttpMethod(), is(HttpMethod.GET));
229 assertThat(e2.getRequestedUrl(), is("/my/mocked/url"));
235 @Test(expectedExceptions = Exception.class)
236 public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() {
237 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
238 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity");
239 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
240 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
244 aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
246 } catch (Exception e) {
247 assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
248 assertThat(e.getCause(),
249 hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class)))
256 public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() {
257 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
258 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
259 "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }");
260 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
262 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
264 final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
266 assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo"));
267 assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar"));
270 private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
271 return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
274 private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) {
275 final Response mockResponse = mock(Response.class);
276 when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
277 when(mockResponse.getStatusInfo()).thenReturn(status);
278 when(mockResponse.readEntity(String.class)).thenReturn(entity);
279 return new ResponseWithRequestInfo(mockResponse, requestUrl, method);
282 //serialize fields except of fields we cannot know ahead of time
283 private static String requestMetadataReflected(StatusMetadata metadata) {
284 return new ReflectionToStringBuilder(metadata, ToStringStyle.SHORT_PREFIX_STYLE)
285 .setExcludeFieldNames("duration")
289 private static String statusDataReflected(ExternalComponentStatus status) {
290 return new ReflectionToStringBuilder(status, ToStringStyle.SHORT_PREFIX_STYLE)
291 .setExcludeFieldNames("metadata")
296 public static Object[][] rawData() {
297 return new Object[][]{
298 {"errorMessage", }, {""}, {null}
302 @Test(dataProvider = "rawData")
303 public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){
304 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
305 new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null,
307 ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
308 assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
309 assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), rawData);
313 public static Object[][] exceptions() {
314 return new Object[][] {
315 {"NullPointerException", "errorMessage",
316 new ExceptionWithRequestInfo(HttpMethod.GET, "url",
317 "errorMessage", null, new NullPointerException())},
318 {"RuntimeException", null,
319 new ExceptionWithRequestInfo(HttpMethod.GET, "url",
320 null, null, new RuntimeException())},
321 {"RuntimeException", null,
322 new RuntimeException()},
326 @Test(dataProvider = "exceptions")
327 public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){
328 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception);
329 ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
330 if (exception instanceof ExceptionWithRequestInfo) {
331 assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
332 assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), expectedRawData);
334 assertThat(result.getMetadata().getDescription(), containsString(description));
337 private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() {
338 Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
339 ExternalComponentStatus result = aaiClientMock.probeComponent();
340 assertFalse(result.isAvailable());
346 public void getTenants_Arguments_Are_Null_Or_Empty() {
348 when(aaiClientMock.getTenants(any(), any())).thenCallRealMethod();
350 AaiResponse response = aaiClientMock.getTenants("", "");
352 assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
355 response = aaiClientMock.getTenants(null, null);
357 assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
360 @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG)
361 public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() {
363 when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
365 Response generalEmptyResponse = mock(Response.class);
366 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
368 aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
372 public void whenCacheThrowException_thenGetTenantReturnAaiResponse() {
373 CacheProvider mockCacheProvider = mock(CacheProvider.class);
374 CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class);
375 AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider);
377 when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache);
378 when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG));
379 AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType");
380 assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode());
381 assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage());
385 public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() {
387 when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
390 Response generalEmptyResponse = mock(Response.class);
392 when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw);
393 when(generalEmptyResponse.getStatus()).thenReturn(200);
394 when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK);
397 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
399 AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
401 GetTenantsResponse[] tenants = response.getT();
403 Assert.assertTrue(response.t.length> 0);
405 Assert.assertEquals(tenants[0].cloudOwner,"irma-aic-cloud-owner");
408 final String tenantResponseRaw ="" +
410 "\"service-type\": \"VIRTUAL USP\"," +
411 "\"resource-version\": \"1494001841964\"," +
412 "\"relationship-list\": {" +
413 "\"relationship\": [{" +
414 "\"related-to\": \"tenant\"," +
415 "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," +
416 "\"relationship-data\": [{" +
417 "\"relationship-key\": \"cloud-region.cloud-owner\"," +
418 "\"relationship-value\": \"irma-aic-cloud-owner\"" +
421 "\"relationship-key\": \"cloud-region.cloud-region-id\"," +
422 "\"relationship-value\": \"AAIAIC25\"" +
425 "\"relationship-key\": \"tenant.tenant-id\"," +
426 "\"relationship-value\": \"092eb9e8e4b7412e8787dd091bc58e86\"" +
429 "\"related-to-property\": [{" +
430 "\"property-key\": \"tenant.tenant-name\"," +
431 "\"property-value\": \"USP-SIP-IC-24335-T-01\"" +
437 final String vfModuleHomingResponseRaw ="{" +
438 " \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," +
439 " \"vf-module-name\": \"apndns_az_02_module_1\"," +
440 " \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," +
441 " \"orchestration-status\": \"active\"," +
442 " \"is-base-vf-module\": false," +
443 " \"resource-version\": \"1530559380383\"," +
444 " \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," +
445 " \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," +
446 " \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," +
447 " \"module-index\": 0," +
448 " \"relationship-list\": {" +
449 " \"relationship\": [" +
451 " \"related-to\": \"l3-network\"," +
452 " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
453 " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," +
454 " \"relationship-data\": [" +
456 " \"relationship-key\": \"l3-network.network-id\"," +
457 " \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" +
460 " \"related-to-property\": [" +
462 " \"property-key\": \"l3-network.network-name\"," +
463 " \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" +
468 " \"related-to\": \"l3-network\"," +
469 " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
470 " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," +
471 " \"relationship-data\": [" +
473 " \"relationship-key\": \"l3-network.network-id\"," +
474 " \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" +
477 " \"related-to-property\": [" +
479 " \"property-key\": \"l3-network.network-name\"," +
480 " \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" +
485 " \"related-to\": \"volume-group\"," +
486 " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
487 " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," +
488 " \"relationship-data\": [" +
490 " \"relationship-key\": \"cloud-region.cloud-owner\"," +
491 " \"relationship-value\": \"irma-aic\"" +
494 " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
495 " \"relationship-value\": \"rdm5b\"" +
498 " \"relationship-key\": \"volume-group.volume-group-id\"," +
499 " \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" +
504 " \"related-to\": \"vserver\"," +
505 " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
506 " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," +
507 " \"relationship-data\": [" +
509 " \"relationship-key\": \"cloud-region.cloud-owner\"," +
510 " \"relationship-value\": \"irma-aic\"" +
513 " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
514 " \"relationship-value\": \"rdm5b\"" +
517 " \"relationship-key\": \"tenant.tenant-id\"," +
518 " \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" +
521 " \"relationship-key\": \"vserver.vserver-id\"," +
522 " \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" +
525 " \"related-to-property\": [" +
527 " \"property-key\": \"vserver.vserver-name\"," +
528 " \"property-value\": \"zrdm5bfapn01dns002\"" +
536 public void get_homingDataForVfModule() {
537 when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
539 Response homingResponse = mock(Response.class);
541 when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw);
542 when(homingResponse.getStatus()).thenReturn(200);
543 when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK);
546 when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse);
548 GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
550 Assert.assertEquals(tenant.cloudOwner,"irma-aic" );
551 Assert.assertEquals(tenant.cloudRegionID,"rdm5b");
552 Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91");
555 @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'")
556 public void getVfModule_Homing_Arguments_Are_Valid_But_Not_Exists() {
557 when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
559 Response generalEmptyResponse = mock(Response.class);
560 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
562 aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
566 public static Object[][] invalidDataId() {
567 return new String[][] {
573 @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.")
574 public void getVfModule_Homing_Arguments_Are_Empty_Or_Null(String data) {
575 when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod();
576 aaiClientMock.getHomingDataByVfModule(data, data);
580 public static Object[][] resourceTypesProvider() {
581 return new Object[][] {
582 {"service-instance", ResourceType.SERVICE_INSTANCE},
583 {"generic-vnf", ResourceType.GENERIC_VNF},
584 {"vf-module", ResourceType.VF_MODULE}
589 public static Object[][] nameAndResourceTypeProvider() {
590 return new Object[][] {
591 {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"},
592 {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"},
593 {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"},
594 {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"},
595 {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=MjVg1234"}
599 @Test(dataProvider = "nameAndResourceTypeProvider")
600 public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) {
601 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
602 ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}");
604 when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean()))
605 .thenReturn(responseWithRequestInfo);
607 AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
609 aaiClient.isNodeTypeExistsByName(name, type);
613 public static Object[][] aaiClientInternalExceptions() {
614 return Stream.<Pair<Class<? extends Throwable>, UncheckedBiConsumer<HttpsAuthClient, Client>>>of(
616 // Exception out of httpsAuthClientMock
617 Pair.of(CertificateException.class, (httpsAuthClientMock, javaxClientMock) -> {
618 final CertificateException e0 = new CertificateException("No X509TrustManager implementation available");
619 SSLHandshakeException e = new SSLHandshakeException(e0.toString());
622 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
625 Pair.of(StringIndexOutOfBoundsException.class, mockExceptionOnClientProvider(new StringIndexOutOfBoundsException(4))),
627 Pair.of(NullPointerException.class, mockExceptionOnClientProvider(new NullPointerException("null"))),
629 Pair.of(FileNotFoundException.class, mockExceptionOnClientProvider(new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12"))),
631 Pair.of(BadPaddingException.class, mockExceptionOnClientProvider(
632 new IOException("keystore password was incorrect", new BadPaddingException("Given final block not properly padded")))
634 Pair.of(GenericUncheckedException.class, mockExceptionOnClientProvider(new GenericUncheckedException("basa"))),
636 Pair.of(NullPointerException.class, (httpsAuthClientMock, javaxClientMock) ->
637 when(httpsAuthClientMock.getClient(any())).thenReturn(null)),
640 // Exception out of javax's Client
641 Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> {
642 when(javaxClientMock.target(nullable(String.class))).thenThrow(
643 new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))
647 Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> {
648 SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target");
649 when(javaxClientMock.target(nullable(String.class))).thenThrow(
650 new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0))
654 Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) ->
655 when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa")))
657 ).flatMap(l -> Stream.of(
658 // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work
659 ImmutableList.of(l.getLeft(), l.getRight(), true).toArray(),
660 ImmutableList.of(l.getLeft(), l.getRight(), false).toArray()
661 )).collect(toList()).toArray(new Object[][]{});
664 private static UncheckedBiConsumer<HttpsAuthClient, Client> mockExceptionOnClientProvider(Exception e) {
665 return (httpsAuthClientMock, javaxClientMock) ->
666 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
669 @Test(dataProvider = "aaiClientInternalExceptions")
670 public void propagateExceptions_internalsThrowException_ExceptionRethrown(Class<? extends Throwable> expectedType, BiConsumer<HttpsAuthClient, Client> setupMocks, boolean propagateExceptions) throws Exception {
673 this test -> AaiClient -> AAIRestInterface -> HttpsAuthClient -> javax's Client
675 In this test, *AaiClient* and *AAIRestInterface* are under test (actual
676 implementation is used), while HttpsAuthClient and the javax's Client are
677 mocked to return pseudo-responses or - better- throw exceptions.
681 HttpsAuthClient httpsAuthClientMock = mock(HttpsAuthClient.class);
682 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
683 Client javaxClientMock = mocks.getFakeClient();
684 Response responseMock = mocks.getFakeResponse();
686 // prepare real AAIRestInterface and AaiClient, and wire mocks
687 AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock,
688 mock(ServletRequestHelper.class),
689 mock(SystemPropertyHelper.class),
690 mock(Logging.class));
691 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
692 when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock);
694 // define atomic method under test, including reset of "aaiRestInterface.client"
695 final Function<Boolean, Response> doAaiGet = (propagateExceptions1) -> {
697 FieldUtils.writeField(aaiRestInterface, "client", null, true);
698 return aaiClient.doAaiGet("uri", false, propagateExceptions1).getResponse();
699 } catch (IllegalAccessException e) {
700 throw new RuntimeException(e);
704 // verify setup again
705 assertThat("mocks setup should make doAaiGet return our responseMock", doAaiGet.apply(true), is(sameInstance(responseMock)));
709 setupMocks.accept(httpsAuthClientMock, javaxClientMock);
712 final Response response = doAaiGet.apply(propagateExceptions);
713 } catch (Exception e) {
714 if (propagateExceptions) {
715 assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
718 // Verify that "don't propagate" really still work
719 Assert.fail("calling doAaiGet when propagateExceptions is false must result with no exception", e);
723 // If no exception caught
724 // We're asserting that the legacy behaviour is still in place. Hopefully
725 // one day we will remove the non-propagateExceptions case
726 assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)");
730 public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() {
732 final String cloudRegion = "{" +
733 " \"cloud-owner\": \"mure-royo-ru22\"," +
734 " \"cloud-region-id\": \"ravitu\"," +
735 " \"cloud-type\": \"openstack\"," +
736 " \"resource-version\": \"1523631256125\"," +
737 " \"relationship-list\": {" +
738 " \"relationship\": [{" +
739 " \"related-to\": \"pserver\"" +
745 String bodyWith0 = "{ \"cloud-region\": [" + " ]}";
746 String bodyWith1 = "{ \"cloud-region\": [" + cloudRegion + " ]}";
747 String bodyWith2 = "{ \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + " ]}";
748 String bodyWithDifferent2 = "{ \"cloud-region\": [" + cloudRegion + ", " +
749 cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") +
752 return new Object[][] {
753 { "regular single result", bodyWith1, false },
754 { "exceptional empty result", bodyWith0, true },
755 { "two same results", bodyWith2, false },
756 { "two incoherent results", bodyWithDifferent2, true },
760 @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId")
761 public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) {
762 final String cloudRegion = "ravitu";
763 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
764 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body);
765 when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)),
766 isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean()))
767 .thenReturn(responseWithRequestInfo);
769 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
772 final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion);
773 if (expectingException) fail("expected failure on " + desc + ", got " + result);
775 assertThat(result, is("mure-royo-ru22"));
777 } catch (Exception e) {
778 if (!expectingException) throw e;
780 assertThat(e.toString(), either(
781 containsString("No cloud-owner found for " + cloudRegion))
782 .or(containsString("Conflicting cloud-owner found for " + cloudRegion)));
788 public static Object[][] cloudRegionAndTenantDataProvider() {
789 return new Object[][] {
790 { "APPC-24595-T-IST-02C", "mtn23b" },
791 { "APPC-24595-T-IST-02C", null },
798 public static Object[][] versionsDataProvider() {
799 return new Object[][] {
800 { Stream.of("10","20","30"), "30" },
801 { Stream.of("10","20","20"), "20" },
802 { Stream.of("c","b","a"), "c" },
803 { Stream.of("1.0","2.0","1.8"), "2.0" },
804 { Stream.of("1.0.7","2.0.2","2.0.9"), "2.0.9" },
805 { Stream.of("0","0","0"), "0" },
806 { Stream.of("","10"), "10" },
811 @Test(dataProvider = "versionsDataProvider")
812 public void maxModelVer(Stream<String> input, String expected) {
813 Stream<ModelVer> modelVerStream = input.map(version -> {
814 ModelVer mv = new ModelVer();
815 mv.setModelVersion(version);
819 final AaiClient aaiClient = new AaiClient(null, null, null);
821 assertThat(aaiClient.maxModelVer(modelVerStream), hasProperty("modelVersion", is(expected)));
824 @Test(expectedExceptions = GenericUncheckedException.class)
825 public void maxModelVerException() {
826 final AaiClient aaiClient = new AaiClient(null, null, null);
827 aaiClient.maxModelVer(Stream.of(new ModelVer()));
829 @Test(dataProvider = "cloudRegionAndTenantDataProvider")
830 public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException {
831 SimpleResult tenant = new SimpleResult();
832 if (tenantName != null) {
833 tenant.setJsonNodeType("tenant");
834 Properties tenantProps = new Properties();
835 tenantProps.setTenantName(tenantName);
836 tenant.setJsonProperties(tenantProps);
839 SimpleResult cloudRegion = new SimpleResult();
840 if (cloudRegionId != null) {
841 cloudRegion.setJsonNodeType("cloud-region");
842 Properties cloudRegionProps = new Properties();
843 cloudRegionProps.setCloudRegionId(cloudRegionId);
844 cloudRegion.setJsonProperties(cloudRegionProps);
847 CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion));
848 String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult);
850 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
851 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT);
852 when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")),
853 any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean()))
854 .thenReturn(responseWithRequestInfo);
856 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
857 Map<String, Properties> result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId");
858 if (tenantName != null) {
859 assertEquals(result.get("tenant").getTenantName(), tenantName);
861 assertNull(result.get("tenant"));
864 if (cloudRegionId != null) {
865 assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId);
867 assertNull(result.get("cloud-region"));
871 protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
872 when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean()))
873 .thenReturn(responseWithRequestInfo);
877 public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() {
878 AAIRestInterface restInterface = mock(AAIRestInterface.class);
879 PortDetailsTranslator portDetailsTranslator = mock(PortDetailsTranslator.class);
880 Response response = mock(Response.class);
881 when(response.getStatus()).thenReturn(404);
882 when(response.readEntity(String.class)).thenReturn("sampleEntity");
883 when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND);
884 ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET);
885 when(restInterface.RestGet(eq("VidAaiController"), any(String.class),
886 eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo);
887 AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null);
890 aaiClient.getAllSubscribers(true);
892 verify(response).readEntity(String.class);
896 public interface UncheckedBiConsumer<T, U> extends BiConsumer<T, U> {
898 default void accept(T t, U u) {
901 } catch (Exception e) {
902 throw new RuntimeException(e);
906 void acceptThrows(T t, U u) throws Exception;
910 public void getLatestVersionByInvariantId_verifyCallingExpectedApi(){
912 when(aaiClientMock.getLatestVersionByInvariantId(anyString())).thenCallRealMethod();
914 aaiClientMock.getLatestVersionByInvariantId("model-invariant-id");
916 Mockito.verify(aaiClientMock).doAaiPut(argThat(url -> url.endsWith("query?format=resource&depth=0")),argThat(payload -> payload.contains("service-design-and-creation/models/model/model-invariant-id")),anyBoolean());
921 public static Object[][] getSubscriberDataDataProvider() {
922 return new Object[][] {
924 { "another id 123", false },
928 @Test(dataProvider = "getSubscriberDataDataProvider")
929 public void getSubscriberDataParams(String subscriberId, boolean omitServiceInstances) {
930 String depth = omitServiceInstances ? "1" : "2";
931 when(aaiClientMock.getSubscriberData(anyString(),anyBoolean())).thenCallRealMethod();
932 aaiClientMock.getSubscriberData(subscriberId, omitServiceInstances);
933 Mockito.verify(aaiClientMock).doAaiGet(argThat(s -> s.contains("customer/" + subscriberId + "?") && s.contains("depth=" + depth)),any(Boolean.class));
937 public void testToModelVerStream() throws IOException {
939 ModelVersions modelVersions = JACKSON_OBJECT_MAPPER.readValue("" +
941 " \"results\": [\n" +
944 " \"model-invariant-id\": \"f6342be5-d66b-4d03-a1aa-c82c3094c4ea\",\n" +
945 " \"model-type\": \"service\",\n" +
946 " \"resource-version\": \"1534274421300\"\n" +
950 " \"model-ver\": {\n" +
951 " \"model-version-id\": \"a92f899d-a3ec-465b-baed-1663b0a5aee1\",\n" +
952 " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
953 " \"model-version\": \"bbb\",\n" +
954 " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
955 " \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
956 " \"resource-version\": \"1534788756086\"\n" +
960 " \"model-ver\": {\n" +
961 " \"model-version-id\": \"d2fda667-e92e-4cfa-9620-5da5de01a319\",\n" +
962 " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
963 " \"model-version\": \"aaa\",\n" +
964 " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
965 " \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
966 " \"resource-version\": \"1534444087221\"\n" +
968 " }]}", ModelVersions.class);
971 final AaiClient aaiClient = new AaiClient(null, null, null);
973 assertThat(aaiClient.toModelVerStream(modelVersions).collect(toList()),
975 hasProperty("modelVersionId", is("a92f899d-a3ec-465b-baed-1663b0a5aee1")),
976 hasProperty("modelVersionId", is("d2fda667-e92e-4cfa-9620-5da5de01a319"))