Add cloud-region and nf-role as an optional search criteria
[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.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;
110
111 @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class})
112 @WebAppConfiguration
113 public class AaiClientTest {
114
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;
118
119     @BeforeMethod
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);
125
126         when(servletContext.getRealPath(any(String.class))).thenReturn("");
127
128         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null);
129         when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null);
130     }
131
132     @DataProvider
133     public static Object[][] logicalLinkData() {
134         return new Object[][] {
135                 {"", "network/logical-links/logical-link/"},
136                 {"link", "network/logical-links/logical-link/link"}
137         };
138     }
139
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
145     private static String responseJsonNfRole = "/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterNfRole.json";
146     private static String responseJsonCloudRegion ="/payload_jsons/changeManagement/vnfs-fromServiceInstance-filterByCloudRegion.json";
147
148
149     @DataProvider
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},
157         };
158     }
159
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",
166             HttpMethod.PUT);
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);
173     }
174
175     @Test(dataProvider = "logicalLinkData")
176     public void getLogicalLink_Link_Is_Empty(String link, String expectedUrl) {
177
178         when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod();
179         aaiClientMock.getLogicalLink(link);
180         verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class));
181     }
182
183     @DataProvider
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}
189         };
190     }
191
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(
195                 HttpMethod.GET,
196                 200,
197                 "url",
198                 "rawData",
199                 isAvailable ? "OK" : "No subscriber received",
200                 0
201         ));
202         Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn(
203                 new AaiResponseWithRequestInfo<>(
204                         HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200),
205                         "rawData"));
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())));
210     }
211
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);
218
219         try {
220
221             aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
222
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"));
230
231             throw e;
232         }
233     }
234
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);
241
242         try {
243
244             aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
245
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)))
250             );
251             throw e;
252         }
253     }
254
255     @Test
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);
261
262         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
263
264         final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class);
265
266         assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo"));
267         assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar"));
268     }
269
270     private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
271         return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
272     }
273
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);
280     }
281
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")
286                 .toString();
287     }
288
289     private static String statusDataReflected(ExternalComponentStatus status) {
290         return new ReflectionToStringBuilder(status, ToStringStyle.SHORT_PREFIX_STYLE)
291                 .setExcludeFieldNames("metadata")
292                 .toString();
293     }
294
295     @DataProvider
296     public static Object[][] rawData() {
297         return new Object[][]{
298                 {"errorMessage", }, {""}, {null}
299         };
300     }
301
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,
306                         rawData));
307         ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable();
308         assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class));
309         assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), rawData);
310     }
311
312     @DataProvider
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()},
323         };
324     }
325
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);
333         }
334         assertThat(result.getMetadata().getDescription(), containsString(description));
335     }
336
337     private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() {
338         Mockito.when(aaiClientMock.probeComponent()).thenCallRealMethod();
339         ExternalComponentStatus result  = aaiClientMock.probeComponent();
340         assertFalse(result.isAvailable());
341         return result;
342     }
343
344
345     @Test
346     public void getTenants_Arguments_Are_Null_Or_Empty() {
347
348         when(aaiClientMock.getTenants(any(), any())).thenCallRealMethod();
349
350         AaiResponse response = aaiClientMock.getTenants("", "");
351
352         assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
353
354
355         response = aaiClientMock.getTenants(null, null);
356
357         assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}");
358     }
359
360     @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG)
361     public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() {
362
363         when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
364
365         Response generalEmptyResponse = mock(Response.class);
366         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
367
368         aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
369     }
370
371     @Test
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);
376
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());
382     }
383
384     @Test
385     public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() {
386
387         when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod();
388
389
390         Response generalEmptyResponse = mock(Response.class);
391
392         when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw);
393         when(generalEmptyResponse.getStatus()).thenReturn(200);
394         when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK);
395
396
397         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
398
399         AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType");
400
401         GetTenantsResponse[] tenants = response.getT();
402
403         Assert.assertTrue(response.t.length> 0);
404
405         Assert.assertEquals(tenants[0].cloudOwner,"irma-aic-cloud-owner");
406     }
407
408     final String tenantResponseRaw ="" +
409             "{" +
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\"" +
419             "}," +
420             "{" +
421             "\"relationship-key\": \"cloud-region.cloud-region-id\"," +
422             "\"relationship-value\": \"AAIAIC25\"" +
423             "}," +
424             "{" +
425             "\"relationship-key\": \"tenant.tenant-id\"," +
426             "\"relationship-value\": \"092eb9e8e4b7412e8787dd091bc58e86\"" +
427             "}" +
428             "]," +
429             "\"related-to-property\": [{" +
430             "\"property-key\": \"tenant.tenant-name\"," +
431             "\"property-value\": \"USP-SIP-IC-24335-T-01\"" +
432             "}]" +
433             "}]" +
434             "}" +
435             "}";
436
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\": [" +
450             "            {" +
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\": [" +
455             "                    {" +
456             "                        \"relationship-key\": \"l3-network.network-id\"," +
457             "                        \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" +
458             "                    }" +
459             "                ]," +
460             "                \"related-to-property\": [" +
461             "                    {" +
462             "                        \"property-key\": \"l3-network.network-name\"," +
463             "                        \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" +
464             "                    }" +
465             "                ]" +
466             "            }," +
467             "            {" +
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\": [" +
472             "                    {" +
473             "                        \"relationship-key\": \"l3-network.network-id\"," +
474             "                        \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" +
475             "                    }" +
476             "                ]," +
477             "                \"related-to-property\": [" +
478             "                    {" +
479             "                        \"property-key\": \"l3-network.network-name\"," +
480             "                        \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" +
481             "                    }" +
482             "                ]" +
483             "            }," +
484             "            {" +
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\": [" +
489             "                    {" +
490             "                        \"relationship-key\": \"cloud-region.cloud-owner\"," +
491             "                        \"relationship-value\": \"irma-aic\"" +
492             "                    }," +
493             "                    {" +
494             "                        \"relationship-key\": \"cloud-region.cloud-region-id\"," +
495             "                        \"relationship-value\": \"rdm5b\"" +
496             "                    }," +
497             "                    {" +
498             "                        \"relationship-key\": \"volume-group.volume-group-id\"," +
499             "                        \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" +
500             "                    }" +
501             "                ]" +
502             "            }," +
503             "            {" +
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\": [" +
508             "                    {" +
509             "                        \"relationship-key\": \"cloud-region.cloud-owner\"," +
510             "                        \"relationship-value\": \"irma-aic\"" +
511             "                    }," +
512             "                    {" +
513             "                        \"relationship-key\": \"cloud-region.cloud-region-id\"," +
514             "                        \"relationship-value\": \"rdm5b\"" +
515             "                    }," +
516             "                    {" +
517             "                        \"relationship-key\": \"tenant.tenant-id\"," +
518             "                        \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" +
519             "                    }," +
520             "                    {" +
521             "                        \"relationship-key\": \"vserver.vserver-id\"," +
522             "                        \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" +
523             "                    }" +
524             "                ]," +
525             "                \"related-to-property\": [" +
526             "                    {" +
527             "                        \"property-key\": \"vserver.vserver-name\"," +
528             "                        \"property-value\": \"zrdm5bfapn01dns002\"" +
529             "                    }" +
530             "                ]" +
531             "            }" +
532             "        ]" +
533             "    }" +
534             "}";
535     @Test
536     public void get_homingDataForVfModule() {
537         when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod();
538
539         Response homingResponse = mock(Response.class);
540
541         when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw);
542         when(homingResponse.getStatus()).thenReturn(200);
543         when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK);
544
545
546         when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse);
547
548         GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
549
550         Assert.assertEquals(tenant.cloudOwner,"irma-aic" );
551         Assert.assertEquals(tenant.cloudRegionID,"rdm5b");
552         Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91");
553
554     }
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();
558
559         Response generalEmptyResponse = mock(Response.class);
560         when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse);
561
562         aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId");
563     }
564
565     @DataProvider
566     public static Object[][] invalidDataId() {
567         return new String[][] {
568                 {""},
569                 {null}
570         };
571     }
572
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);
577     }
578
579     @DataProvider
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}
585         };
586     }
587
588     @DataProvider
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"}
596         };
597     }
598
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, "{}");
603
604         when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean()))
605                 .thenReturn(responseWithRequestInfo);
606
607         AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
608
609         aaiClient.isNodeTypeExistsByName(name, type);
610     }
611
612     @DataProvider
613     public static Object[][] aaiClientInternalExceptions() {
614         return Stream.<Pair<Class<? extends Throwable>, UncheckedBiConsumer<HttpsAuthClient, Client>>>of(
615
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());
620                     e.initCause(e0);
621
622                     when(httpsAuthClientMock.getClient(any())).thenThrow(e);
623                 }),
624
625                 Pair.of(StringIndexOutOfBoundsException.class, mockExceptionOnClientProvider(new StringIndexOutOfBoundsException(4))),
626
627                 Pair.of(NullPointerException.class, mockExceptionOnClientProvider(new NullPointerException("null"))),
628
629                 Pair.of(FileNotFoundException.class, mockExceptionOnClientProvider(new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12"))),
630
631                 Pair.of(BadPaddingException.class, mockExceptionOnClientProvider(
632                         new IOException("keystore password was incorrect", new BadPaddingException("Given final block not properly padded")))
633                 ),
634                 Pair.of(GenericUncheckedException.class, mockExceptionOnClientProvider(new GenericUncheckedException("basa"))),
635
636                 Pair.of(NullPointerException.class, (httpsAuthClientMock, javaxClientMock) ->
637                         when(httpsAuthClientMock.getClient(any())).thenReturn(null)),
638
639
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"))
644                     );
645                 }),
646
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))
651                     );
652                 }),
653
654                 Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) ->
655                         when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa")))
656
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[][]{});
662     }
663
664     private static UncheckedBiConsumer<HttpsAuthClient, Client> mockExceptionOnClientProvider(Exception e) {
665         return (httpsAuthClientMock, javaxClientMock) ->
666                 when(httpsAuthClientMock.getClient(any())).thenThrow(e);
667     }
668
669     @Test(dataProvider = "aaiClientInternalExceptions")
670     public void propagateExceptions_internalsThrowException_ExceptionRethrown(Class<? extends Throwable> expectedType, BiConsumer<HttpsAuthClient, Client> setupMocks, boolean propagateExceptions) throws Exception {
671         /*
672         Call chain is like:
673             this test -> AaiClient -> AAIRestInterface -> HttpsAuthClient -> javax's Client
674
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.
678          */
679
680         // prepare mocks
681         HttpsAuthClient httpsAuthClientMock = mock(HttpsAuthClient.class);
682         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
683         Client javaxClientMock = mocks.getFakeClient();
684         Response responseMock = mocks.getFakeResponse();
685
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);
693
694         // define atomic method under test, including reset of "aaiRestInterface.client"
695         final Function<Boolean, Response> doAaiGet = (propagateExceptions1) -> {
696             try {
697                 FieldUtils.writeField(aaiRestInterface, "client", null, true);
698                 return aaiClient.doAaiGet("uri", false, propagateExceptions1).getResponse();
699             } catch (IllegalAccessException e) {
700                 throw new RuntimeException(e);
701             }
702         };
703
704         // verify setup again
705         assertThat("mocks setup should make doAaiGet return our responseMock", doAaiGet.apply(true), is(sameInstance(responseMock)));
706
707
708         /// TEST:
709         setupMocks.accept(httpsAuthClientMock, javaxClientMock);
710
711         try {
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));
716                 return; // ok, done
717             } else {
718                 // Verify that "don't propagate" really still work
719                 Assert.fail("calling doAaiGet when propagateExceptions is false must result with no exception", e);
720             }
721         }
722
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)");
727     }
728
729     @DataProvider
730     public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() {
731
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\"" +
740                 "          }" +
741                 "        ]" +
742                 "      }" +
743                 "    }";
744
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") +
750                 "]}";
751
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 },
757         };
758     }
759
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);
768
769         final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null);
770
771         try {
772             final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion);
773             if (expectingException) fail("expected failure on " + desc + ", got " + result);
774             else {
775                 assertThat(result, is("mure-royo-ru22"));
776             }
777         } catch (Exception e) {
778             if (!expectingException) throw e;
779             else {
780                 assertThat(e.toString(), either(
781                         containsString("No cloud-owner found for " + cloudRegion))
782                         .or(containsString("Conflicting cloud-owner found for " + cloudRegion)));
783             }
784         }
785     }
786
787     @DataProvider
788     public static Object[][]  cloudRegionAndTenantDataProvider() {
789         return new Object[][] {
790                 { "APPC-24595-T-IST-02C", "mtn23b" },
791                 { "APPC-24595-T-IST-02C", null },
792                 { null, "mtn23b" },
793                 { null, null },
794         };
795     }
796
797     @DataProvider
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" },
807
808         };
809     }
810
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);
816             return mv;
817         });
818
819         final AaiClient aaiClient = new AaiClient(null, null, null);
820
821         assertThat(aaiClient.maxModelVer(modelVerStream), hasProperty("modelVersion", is(expected)));
822     }
823
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()));
828     }
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);
837         }
838
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);
845         }
846
847         CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion));
848         String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult);
849
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);
855
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);
860         } else {
861             assertNull(result.get("tenant"));
862         }
863
864         if (cloudRegionId != null) {
865             assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId);
866         } else {
867             assertNull(result.get("cloud-region"));
868         }
869     }
870
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);
874     }
875
876     @Test
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);
888
889
890         aaiClient.getAllSubscribers(true);
891
892         verify(response).readEntity(String.class);
893     }
894
895     @FunctionalInterface
896     public interface UncheckedBiConsumer<T, U> extends BiConsumer<T, U> {
897         @Override
898         default void accept(T t, U u) {
899             try {
900                 acceptThrows(t, u);
901             } catch (Exception e) {
902                 throw new RuntimeException(e);
903             }
904         }
905
906         void acceptThrows(T t, U u) throws Exception;
907     }
908
909     @Test
910     public void getLatestVersionByInvariantId_verifyCallingExpectedApi(){
911
912         when(aaiClientMock.getLatestVersionByInvariantId(anyString())).thenCallRealMethod();
913
914         aaiClientMock.getLatestVersionByInvariantId("model-invariant-id");
915
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());
917
918     }
919
920     @DataProvider
921     public static Object[][]  getSubscriberDataDataProvider() {
922         return new Object[][] {
923             { "Some-ID", true },
924             { "another id 123", false },
925         };
926     }
927
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));
934     }
935
936     @Test
937     public void testToModelVerStream() throws IOException {
938
939         ModelVersions modelVersions = JACKSON_OBJECT_MAPPER.readValue("" +
940             "{\n" +
941             "    \"results\": [\n" +
942             "        {\n" +
943             "            \"model\": {\n" +
944             "                \"model-invariant-id\": \"f6342be5-d66b-4d03-a1aa-c82c3094c4ea\",\n" +
945             "                \"model-type\": \"service\",\n" +
946             "                \"resource-version\": \"1534274421300\"\n" +
947             "            }\n" +
948             "        },\n" +
949             "        {\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" +
957             "            }\n" +
958             "        },\n" +
959             "        {\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" +
967             "            }\n" +
968             "        }]}", ModelVersions.class);
969
970
971         final AaiClient aaiClient = new AaiClient(null, null, null);
972
973         assertThat(aaiClient.toModelVerStream(modelVersions).collect(toList()),
974             containsInAnyOrder(
975                 hasProperty("modelVersionId", is("a92f899d-a3ec-465b-baed-1663b0a5aee1")),
976                 hasProperty("modelVersionId", is("d2fda667-e92e-4cfa-9620-5da5de01a319"))
977             ));
978
979     }
980 }