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\"}";
144 private static String withoutNfroleAndCloudRegionWithSpace = "{\"start\":[\"/business/customers/customer/globalCustomerId1with%20space%20360-as988q/service-subscriptions/service-subscription/TEST1%20360/service-instances\"],\"query\":\"query/vnfs-fromServiceInstance-filter\"}";
146 private static String responseJsonNfRole = "/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterNfRole.json";
147 private static String responseJsonCloudRegion ="/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterByCloudRegion.json";
151 public static Object[][] aaiPutCustomQueryData() {
152 return new Object[][] {
153 {"globalCustomerId1-360-as988q", "TEST1-360", "test360", null, nfRoleOnly, responseJsonNfRole, "908419144", 200},
154 {"globalCustomerId1-360-as988q", "TEST1-360", null, "cloudRegion-1", cloudRegionOnly, responseJsonCloudRegion, "1165906024", 200},
155 {"globalCustomerId1-360-as988q", "TEST1-360", "test360", "cloudRegion-1", nfRoleAndCloudRegion,
156 responseJsonCloudRegion, "1165906024", 200},
157 {"globalCustomerId1with space 360-as988q", "TEST1 360", null, null, withoutNfroleAndCloudRegionWithSpace, responseJsonNfRole, "908419144", 200},
158 {"globalCustomerId1-360-as988q", "TEST1-360", null, null, withoutNfroleAndCloudRegion, responseJsonNfRole, "908419144", 200},
162 @Test(dataProvider = "aaiPutCustomQueryData")
163 public void testAaiPutCustomQueryByParams(String globalCustomerId, String serviceType, String nfRole, String cloudRegion, String expectedPayload, String responseBody, String expectedId, int responseHttpCode) {
164 String queryFormat = "query?format=simple";
165 final ResponseWithRequestInfo mockedResponseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
166 TestUtils.readFileAsString(responseBody),
167 "query?format=simple&Mock=True",
169 when(aaiClientMock.doAaiPut(eq(queryFormat), anyString(), anyBoolean(), anyBoolean())).thenReturn(mockedResponseWithRequestInfo);
170 when(aaiClientMock.getVnfsByParamsForChangeManagement(anyString(), anyString(), nullable(String.class), nullable(String.class))).thenCallRealMethod();
171 AaiResponse<AaiGetVnfResponse> response = aaiClientMock.getVnfsByParamsForChangeManagement(globalCustomerId, serviceType, nfRole, cloudRegion);
172 verify(aaiClientMock).doAaiPut(eq(queryFormat), eq(expectedPayload), eq(false), eq(false));
173 assertEquals(response.getHttpCode(), responseHttpCode);
174 assertEquals(response.getT().getResults().get(0).id, expectedId);
177 @Test(dataProvider = "logicalLinkData")
178 public void getLogicalLink_Link_Is_Empty(String link, String expectedUrl) {
180 when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod();
181 aaiClientMock.getLogicalLink(link);
182 verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class));
186 public static Object[][] subscribersResults() {
187 return new Object[][] {
188 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); add(new Subscriber()); }}), true},
189 {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); }}), true},
190 {new SubscriberList(new ArrayList<Subscriber>()), false}
194 @Test(dataProvider = "subscribersResults")
195 public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){
196 ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata(
201 isAvailable ? "OK" : "No subscriber received",
204 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
205 new AaiResponseWithRequestInfo<>(
206 HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200),
208 Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
209 ExternalComponentStatus result = aaiClientMock.probeComponent();
210 assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus)));
211 assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata())));
214 @Test(expectedExceptions = Exception.class)
215 public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() {
216 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
217 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity");
218 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
219 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
223 aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
225 } catch (Exception e) {
226 assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
227 ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e);
228 assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()));
229 assertThat(e2.getRawData(), is("entity"));
230 assertThat(e2.getHttpMethod(), is(HttpMethod.GET));
231 assertThat(e2.getRequestedUrl(), is("/my/mocked/url"));
237 @Test(expectedExceptions = Exception.class)
238 public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() {
239 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
240 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity");
241 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
242 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
246 aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
248 } catch (Exception e) {
249 assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class));
250 assertThat(e.getCause(),
251 hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class)))
258 public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() {
259 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
260 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
261 "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }");
262 mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
264 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
266 final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
268 assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo"));
269 assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar"));
272 private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
273 return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
276 private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) {
277 final Response mockResponse = mock(Response.class);
278 when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
279 when(mockResponse.getStatusInfo()).thenReturn(status);
280 when(mockResponse.readEntity(String.class)).thenReturn(entity);
281 return new ResponseWithRequestInfo(mockResponse, requestUrl, method);
284 //serialize fields except of fields we cannot know ahead of time
285 private static String requestMetadataReflected(StatusMetadata metadata) {
286 return new ReflectionToStringBuilder(metadata, ToStringStyle.SHORT_PREFIX_STYLE)
287 .setExcludeFieldNames("duration")
291 private static String statusDataReflected(ExternalComponentStatus status) {
292 return new ReflectionToStringBuilder(status, ToStringStyle.SHORT_PREFIX_STYLE)
293 .setExcludeFieldNames("metadata")
298 public static Object[][] rawData() {
299 return new Object[][]{
300 {"errorMessage", }, {""}, {null}
304 @Test(dataProvider = "rawData")
305 public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){
306 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
307 new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null,
309 ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
310 assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
311 assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), rawData);
315 public static Object[][] exceptions() {
316 return new Object[][] {
317 {"NullPointerException", "errorMessage",
318 new ExceptionWithRequestInfo(HttpMethod.GET, "url",
319 "errorMessage", null, new NullPointerException())},
320 {"RuntimeException", null,
321 new ExceptionWithRequestInfo(HttpMethod.GET, "url",
322 null, null, new RuntimeException())},
323 {"RuntimeException", null,
324 new RuntimeException()},
328 @Test(dataProvider = "exceptions")
329 public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){
330 Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception);
331 ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
332 if (exception instanceof ExceptionWithRequestInfo) {
333 assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
334 assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), expectedRawData);
336 assertThat(result.getMetadata().getDescription(), containsString(description));
339 private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() {
340 Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
341 ExternalComponentStatus result = aaiClientMock.probeComponent();
342 assertFalse(result.isAvailable());
348 public void getTenants_Arguments_Are_Null_Or_Empty() {
350 when(aaiClientMock.getTenants(any(), any())).thenCallRealMethod();
352 AaiResponse response = aaiClientMock.getTenants("", "");
354 assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
357 response = aaiClientMock.getTenants(null, null);
359 assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
362 @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG)
363 public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() {
365 when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
367 Response generalEmptyResponse = mock(Response.class);
368 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
370 aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
374 public void whenCacheThrowException_thenGetTenantReturnAaiResponse() {
375 CacheProvider mockCacheProvider = mock(CacheProvider.class);
376 CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class);
377 AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider);
379 when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache);
380 when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG));
381 AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType");
382 assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode());
383 assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage());
387 public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() {
389 when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
392 Response generalEmptyResponse = mock(Response.class);
394 when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw);
395 when(generalEmptyResponse.getStatus()).thenReturn(200);
396 when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK);
399 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
401 AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
403 GetTenantsResponse[] tenants = response.getT();
405 Assert.assertTrue(response.t.length> 0);
407 Assert.assertEquals(tenants[0].cloudOwner,"irma-aic-cloud-owner");
410 final String tenantResponseRaw ="" +
412 "\"service-type\": \"VIRTUAL USP\"," +
413 "\"resource-version\": \"1494001841964\"," +
414 "\"relationship-list\": {" +
415 "\"relationship\": [{" +
416 "\"related-to\": \"tenant\"," +
417 "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," +
418 "\"relationship-data\": [{" +
419 "\"relationship-key\": \"cloud-region.cloud-owner\"," +
420 "\"relationship-value\": \"irma-aic-cloud-owner\"" +
423 "\"relationship-key\": \"cloud-region.cloud-region-id\"," +
424 "\"relationship-value\": \"AAIAIC25\"" +
427 "\"relationship-key\": \"tenant.tenant-id\"," +
428 "\"relationship-value\": \"092eb9e8e4b7412e8787dd091bc58e86\"" +
431 "\"related-to-property\": [{" +
432 "\"property-key\": \"tenant.tenant-name\"," +
433 "\"property-value\": \"USP-SIP-IC-24335-T-01\"" +
439 final String vfModuleHomingResponseRaw ="{" +
440 " \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," +
441 " \"vf-module-name\": \"apndns_az_02_module_1\"," +
442 " \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," +
443 " \"orchestration-status\": \"active\"," +
444 " \"is-base-vf-module\": false," +
445 " \"resource-version\": \"1530559380383\"," +
446 " \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," +
447 " \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," +
448 " \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," +
449 " \"module-index\": 0," +
450 " \"relationship-list\": {" +
451 " \"relationship\": [" +
453 " \"related-to\": \"l3-network\"," +
454 " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
455 " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," +
456 " \"relationship-data\": [" +
458 " \"relationship-key\": \"l3-network.network-id\"," +
459 " \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" +
462 " \"related-to-property\": [" +
464 " \"property-key\": \"l3-network.network-name\"," +
465 " \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" +
470 " \"related-to\": \"l3-network\"," +
471 " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," +
472 " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," +
473 " \"relationship-data\": [" +
475 " \"relationship-key\": \"l3-network.network-id\"," +
476 " \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" +
479 " \"related-to-property\": [" +
481 " \"property-key\": \"l3-network.network-name\"," +
482 " \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" +
487 " \"related-to\": \"volume-group\"," +
488 " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
489 " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," +
490 " \"relationship-data\": [" +
492 " \"relationship-key\": \"cloud-region.cloud-owner\"," +
493 " \"relationship-value\": \"irma-aic\"" +
496 " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
497 " \"relationship-value\": \"rdm5b\"" +
500 " \"relationship-key\": \"volume-group.volume-group-id\"," +
501 " \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" +
506 " \"related-to\": \"vserver\"," +
507 " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
508 " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," +
509 " \"relationship-data\": [" +
511 " \"relationship-key\": \"cloud-region.cloud-owner\"," +
512 " \"relationship-value\": \"irma-aic\"" +
515 " \"relationship-key\": \"cloud-region.cloud-region-id\"," +
516 " \"relationship-value\": \"rdm5b\"" +
519 " \"relationship-key\": \"tenant.tenant-id\"," +
520 " \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" +
523 " \"relationship-key\": \"vserver.vserver-id\"," +
524 " \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" +
527 " \"related-to-property\": [" +
529 " \"property-key\": \"vserver.vserver-name\"," +
530 " \"property-value\": \"zrdm5bfapn01dns002\"" +
538 public void get_homingDataForVfModule() {
539 when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
541 Response homingResponse = mock(Response.class);
543 when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw);
544 when(homingResponse.getStatus()).thenReturn(200);
545 when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK);
548 when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse);
550 GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
552 Assert.assertEquals(tenant.cloudOwner,"irma-aic" );
553 Assert.assertEquals(tenant.cloudRegionID,"rdm5b");
554 Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91");
557 @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'")
558 public void getVfModule_Homing_Arguments_Are_Valid_But_Not_Exists() {
559 when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
561 Response generalEmptyResponse = mock(Response.class);
562 when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
564 aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
568 public static Object[][] invalidDataId() {
569 return new String[][] {
575 @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.")
576 public void getVfModule_Homing_Arguments_Are_Empty_Or_Null(String data) {
577 when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod();
578 aaiClientMock.getHomingDataByVfModule(data, data);
582 public static Object[][] resourceTypesProvider() {
583 return new Object[][] {
584 {"service-instance", ResourceType.SERVICE_INSTANCE},
585 {"generic-vnf", ResourceType.GENERIC_VNF},
586 {"vf-module", ResourceType.VF_MODULE}
591 public static Object[][] nameAndResourceTypeProvider() {
592 return new Object[][] {
593 {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"},
594 {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"},
595 {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"},
596 {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"},
597 {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=MjVg1234"}
601 @Test(dataProvider = "nameAndResourceTypeProvider")
602 public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) {
603 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
604 ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}");
606 when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean()))
607 .thenReturn(responseWithRequestInfo);
609 AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
611 aaiClient.isNodeTypeExistsByName(name, type);
615 public static Object[][] aaiClientInternalExceptions() {
616 return Stream.<Pair<Class<? extends Throwable>, UncheckedBiConsumer<HttpsAuthClient, Client>>>of(
618 // Exception out of httpsAuthClientMock
619 Pair.of(CertificateException.class, (httpsAuthClientMock, javaxClientMock) -> {
620 final CertificateException e0 = new CertificateException("No X509TrustManager implementation available");
621 SSLHandshakeException e = new SSLHandshakeException(e0.toString());
624 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
627 Pair.of(StringIndexOutOfBoundsException.class, mockExceptionOnClientProvider(new StringIndexOutOfBoundsException(4))),
629 Pair.of(NullPointerException.class, mockExceptionOnClientProvider(new NullPointerException("null"))),
631 Pair.of(FileNotFoundException.class, mockExceptionOnClientProvider(new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12"))),
633 Pair.of(BadPaddingException.class, mockExceptionOnClientProvider(
634 new IOException("keystore password was incorrect", new BadPaddingException("Given final block not properly padded")))
636 Pair.of(GenericUncheckedException.class, mockExceptionOnClientProvider(new GenericUncheckedException("basa"))),
638 Pair.of(NullPointerException.class, (httpsAuthClientMock, javaxClientMock) ->
639 when(httpsAuthClientMock.getClient(any())).thenReturn(null)),
642 // Exception out of javax's Client
643 Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> {
644 when(javaxClientMock.target(nullable(String.class))).thenThrow(
645 new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))
649 Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> {
650 SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target");
651 when(javaxClientMock.target(nullable(String.class))).thenThrow(
652 new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0))
656 Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) ->
657 when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa")))
659 ).flatMap(l -> Stream.of(
660 // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work
661 ImmutableList.of(l.getLeft(), l.getRight(), true).toArray(),
662 ImmutableList.of(l.getLeft(), l.getRight(), false).toArray()
663 )).collect(toList()).toArray(new Object[][]{});
666 private static UncheckedBiConsumer<HttpsAuthClient, Client> mockExceptionOnClientProvider(Exception e) {
667 return (httpsAuthClientMock, javaxClientMock) ->
668 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
671 @Test(dataProvider = "aaiClientInternalExceptions")
672 public void propagateExceptions_internalsThrowException_ExceptionRethrown(Class<? extends Throwable> expectedType, BiConsumer<HttpsAuthClient, Client> setupMocks, boolean propagateExceptions) throws Exception {
675 this test -> AaiClient -> AAIRestInterface -> HttpsAuthClient -> javax's Client
677 In this test, *AaiClient* and *AAIRestInterface* are under test (actual
678 implementation is used), while HttpsAuthClient and the javax's Client are
679 mocked to return pseudo-responses or - better- throw exceptions.
683 HttpsAuthClient httpsAuthClientMock = mock(HttpsAuthClient.class);
684 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
685 Client javaxClientMock = mocks.getFakeClient();
686 Response responseMock = mocks.getFakeResponse();
688 // prepare real AAIRestInterface and AaiClient, and wire mocks
689 AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock,
690 mock(ServletRequestHelper.class),
691 mock(SystemPropertyHelper.class),
692 mock(Logging.class));
693 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
694 when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock);
696 // define atomic method under test, including reset of "aaiRestInterface.client"
697 final Function<Boolean, Response> doAaiGet = (propagateExceptions1) -> {
699 FieldUtils.writeField(aaiRestInterface, "client", null, true);
700 return aaiClient.doAaiGet("uri", false, propagateExceptions1).getResponse();
701 } catch (IllegalAccessException e) {
702 throw new RuntimeException(e);
706 // verify setup again
707 assertThat("mocks setup should make doAaiGet return our responseMock", doAaiGet.apply(true), is(sameInstance(responseMock)));
711 setupMocks.accept(httpsAuthClientMock, javaxClientMock);
714 final Response response = doAaiGet.apply(propagateExceptions);
715 } catch (Exception e) {
716 if (propagateExceptions) {
717 assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
720 // Verify that "don't propagate" really still work
721 Assert.fail("calling doAaiGet when propagateExceptions is false must result with no exception", e);
725 // If no exception caught
726 // We're asserting that the legacy behaviour is still in place. Hopefully
727 // one day we will remove the non-propagateExceptions case
728 assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)");
732 public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() {
734 final String cloudRegion = "{" +
735 " \"cloud-owner\": \"mure-royo-ru22\"," +
736 " \"cloud-region-id\": \"ravitu\"," +
737 " \"cloud-type\": \"openstack\"," +
738 " \"resource-version\": \"1523631256125\"," +
739 " \"relationship-list\": {" +
740 " \"relationship\": [{" +
741 " \"related-to\": \"pserver\"" +
747 String bodyWith0 = "{ \"cloud-region\": [" + " ]}";
748 String bodyWith1 = "{ \"cloud-region\": [" + cloudRegion + " ]}";
749 String bodyWith2 = "{ \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + " ]}";
750 String bodyWithDifferent2 = "{ \"cloud-region\": [" + cloudRegion + ", " +
751 cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") +
754 return new Object[][] {
755 { "regular single result", bodyWith1, false },
756 { "exceptional empty result", bodyWith0, true },
757 { "two same results", bodyWith2, false },
758 { "two incoherent results", bodyWithDifferent2, true },
762 @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId")
763 public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) {
764 final String cloudRegion = "ravitu";
765 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
766 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body);
767 when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)),
768 isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean()))
769 .thenReturn(responseWithRequestInfo);
771 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
774 final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion);
775 if (expectingException) fail("expected failure on " + desc + ", got " + result);
777 assertThat(result, is("mure-royo-ru22"));
779 } catch (Exception e) {
780 if (!expectingException) throw e;
782 assertThat(e.toString(), either(
783 containsString("No cloud-owner found for " + cloudRegion))
784 .or(containsString("Conflicting cloud-owner found for " + cloudRegion)));
790 public static Object[][] cloudRegionAndTenantDataProvider() {
791 return new Object[][] {
792 { "APPC-24595-T-IST-02C", "mtn23b" },
793 { "APPC-24595-T-IST-02C", null },
800 public static Object[][] versionsDataProvider() {
801 return new Object[][] {
802 { Stream.of("10","20","30"), "30" },
803 { Stream.of("10","20","20"), "20" },
804 { Stream.of("c","b","a"), "c" },
805 { Stream.of("1.0","2.0","1.8"), "2.0" },
806 { Stream.of("1.0.7","2.0.2","2.0.9"), "2.0.9" },
807 { Stream.of("0","0","0"), "0" },
808 { Stream.of("","10"), "10" },
813 @Test(dataProvider = "versionsDataProvider")
814 public void maxModelVer(Stream<String> input, String expected) {
815 Stream<ModelVer> modelVerStream = input.map(version -> {
816 ModelVer mv = new ModelVer();
817 mv.setModelVersion(version);
821 final AaiClient aaiClient = new AaiClient(null, null, null);
823 assertThat(aaiClient.maxModelVer(modelVerStream), hasProperty("modelVersion", is(expected)));
826 @Test(expectedExceptions = GenericUncheckedException.class)
827 public void maxModelVerException() {
828 final AaiClient aaiClient = new AaiClient(null, null, null);
829 aaiClient.maxModelVer(Stream.of(new ModelVer()));
831 @Test(dataProvider = "cloudRegionAndTenantDataProvider")
832 public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException {
833 SimpleResult tenant = new SimpleResult();
834 if (tenantName != null) {
835 tenant.setJsonNodeType("tenant");
836 Properties tenantProps = new Properties();
837 tenantProps.setTenantName(tenantName);
838 tenant.setJsonProperties(tenantProps);
841 SimpleResult cloudRegion = new SimpleResult();
842 if (cloudRegionId != null) {
843 cloudRegion.setJsonNodeType("cloud-region");
844 Properties cloudRegionProps = new Properties();
845 cloudRegionProps.setCloudRegionId(cloudRegionId);
846 cloudRegion.setJsonProperties(cloudRegionProps);
849 CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion));
850 String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult);
852 AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class);
853 final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT);
854 when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")),
855 any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean()))
856 .thenReturn(responseWithRequestInfo);
858 final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
859 Map<String, Properties> result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId");
860 if (tenantName != null) {
861 assertEquals(result.get("tenant").getTenantName(), tenantName);
863 assertNull(result.get("tenant"));
866 if (cloudRegionId != null) {
867 assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId);
869 assertNull(result.get("cloud-region"));
873 protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
874 when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean()))
875 .thenReturn(responseWithRequestInfo);
879 public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() {
880 AAIRestInterface restInterface = mock(AAIRestInterface.class);
881 PortDetailsTranslator portDetailsTranslator = mock(PortDetailsTranslator.class);
882 Response response = mock(Response.class);
883 when(response.getStatus()).thenReturn(404);
884 when(response.readEntity(String.class)).thenReturn("sampleEntity");
885 when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND);
886 ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET);
887 when(restInterface.RestGet(eq("VidAaiController"), any(String.class),
888 eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo);
889 AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null);
892 aaiClient.getAllSubscribers(true);
894 verify(response).readEntity(String.class);
898 public interface UncheckedBiConsumer<T, U> extends BiConsumer<T, U> {
900 default void accept(T t, U u) {
903 } catch (Exception e) {
904 throw new RuntimeException(e);
908 void acceptThrows(T t, U u) throws Exception;
912 public void getLatestVersionByInvariantId_verifyCallingExpectedApi(){
914 when(aaiClientMock.getLatestVersionByInvariantId(anyString())).thenCallRealMethod();
916 aaiClientMock.getLatestVersionByInvariantId("model-invariant-id");
918 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());
923 public static Object[][] getSubscriberDataDataProvider() {
924 return new Object[][] {
926 { "another id 123", false },
930 @Test(dataProvider = "getSubscriberDataDataProvider")
931 public void getSubscriberDataParams(String subscriberId, boolean omitServiceInstances) {
932 String depth = omitServiceInstances ? "1" : "2";
933 when(aaiClientMock.getSubscriberData(anyString(),anyBoolean())).thenCallRealMethod();
934 aaiClientMock.getSubscriberData(subscriberId, omitServiceInstances);
935 Mockito.verify(aaiClientMock).doAaiGet(argThat(s -> s.contains("customer/" + subscriberId + "?") && s.contains("depth=" + depth)),any(Boolean.class));
939 public void testToModelVerStream() throws IOException {
941 ModelVersions modelVersions = JACKSON_OBJECT_MAPPER.readValue("" +
943 " \"results\": [\n" +
946 " \"model-invariant-id\": \"f6342be5-d66b-4d03-a1aa-c82c3094c4ea\",\n" +
947 " \"model-type\": \"service\",\n" +
948 " \"resource-version\": \"1534274421300\"\n" +
952 " \"model-ver\": {\n" +
953 " \"model-version-id\": \"a92f899d-a3ec-465b-baed-1663b0a5aee1\",\n" +
954 " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
955 " \"model-version\": \"bbb\",\n" +
956 " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
957 " \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
958 " \"resource-version\": \"1534788756086\"\n" +
962 " \"model-ver\": {\n" +
963 " \"model-version-id\": \"d2fda667-e92e-4cfa-9620-5da5de01a319\",\n" +
964 " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" +
965 " \"model-version\": \"aaa\",\n" +
966 " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" +
967 " \"model-description\": \"Network Collection service for vLAN tagging\",\n" +
968 " \"resource-version\": \"1534444087221\"\n" +
970 " }]}", ModelVersions.class);
973 final AaiClient aaiClient = new AaiClient(null, null, null);
975 assertThat(aaiClient.toModelVerStream(modelVersions).collect(toList()),
977 hasProperty("modelVersionId", is("a92f899d-a3ec-465b-baed-1663b0a5aee1")),
978 hasProperty("modelVersionId", is("d2fda667-e92e-4cfa-9620-5da5de01a319"))