From 4eaf0290dd2572f40526da9cfd09a1ccee4da76d Mon Sep 17 00:00:00 2001 From: Shiwei Tian Date: Tue, 26 Sep 2017 14:22:11 +0800 Subject: [PATCH] add httpsutil and modify query from aai Issue-ID: HOLMES-44 Change-Id: I8f699296ae6465016bf6e802c3d9e6cea07b5612 Signed-off-by: Shiwei Tian --- .../java/org/onap/holmes/common/aai/AaiQuery.java | 88 +++--- .../onap/holmes/common/aai/CorrelationUtil.java | 14 +- .../org/onap/holmes/common/utils/HttpsUtils.java | 177 +++++++++++ .../org/onap/holmes/common/aai/AaiQueryTest.java | 304 +++++++++++++++++++ .../holmes/common/aai/AaiResponseUtilTest.java | 326 +++++++++++++++++++++ .../holmes/common/aai/CorrelationUtilTest.java | 119 ++++++++ .../common/config/MicroServiceConfigTest.java | 34 +-- .../onap/holmes/common/dmaap/DmaapServiceTest.java | 216 ++++++++++++++ 8 files changed, 1213 insertions(+), 65 deletions(-) create mode 100644 holmes-actions/src/main/java/org/onap/holmes/common/utils/HttpsUtils.java create mode 100644 holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiQueryTest.java create mode 100644 holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiResponseUtilTest.java create mode 100644 holmes-actions/src/test/java/org/onap/holmes/common/aai/CorrelationUtilTest.java create mode 100644 holmes-actions/src/test/java/org/onap/holmes/common/dmaap/DmaapServiceTest.java diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/aai/AaiQuery.java b/holmes-actions/src/main/java/org/onap/holmes/common/aai/AaiQuery.java index 71472ed..36479d7 100644 --- a/holmes-actions/src/main/java/org/onap/holmes/common/aai/AaiQuery.java +++ b/holmes-actions/src/main/java/org/onap/holmes/common/aai/AaiQuery.java @@ -13,35 +13,21 @@ */ package org.onap.holmes.common.aai; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MultivaluedHashMap; -import org.glassfish.jersey.client.ClientConfig; +import java.util.HashMap; +import java.util.Map; import org.onap.holmes.common.aai.config.AaiConfig; import org.onap.holmes.common.aai.entity.VmEntity; import org.onap.holmes.common.aai.entity.VnfEntity; import org.onap.holmes.common.config.MicroServiceConfig; import org.onap.holmes.common.exception.CorrelationException; +import org.onap.holmes.common.utils.HttpsUtils; public class AaiQuery { private AaiResponseUtil aaiResponseUtil; public VnfEntity getAaiVnfData(String vnfId, String vnfName) throws CorrelationException { - Client client = ClientBuilder.newClient(new ClientConfig()); - WebTarget webTarget = client - .target(MicroServiceConfig.getMsbServerAddr() + AaiConfig.VNF_ADDR + "vnf-id=" - + vnfId); - String response = webTarget.request("application/json").headers(getHeaders()).get() - .readEntity(String.class); - if (response == null) { - webTarget = client - .target(MicroServiceConfig.getMsbServerAddr() + AaiConfig.VNF_ADDR + "vnf-name=" - + vnfName); - response = webTarget.request("application/json").headers(getHeaders()).get() - .readEntity(String.class); - } + String response = getVnfDataResponse(vnfId, vnfName); try { return aaiResponseUtil.convertJsonToVnfEntity(response); } catch (Exception e) { @@ -50,11 +36,8 @@ public class AaiQuery { } public VmEntity getAaiVmData(String vserverId, String vserverName) throws CorrelationException { - Client client = ClientBuilder.newClient(new ClientConfig()); - String response = client - .target(MicroServiceConfig.getMsbServerAddr() + getVmResourceLinks(client, - vserverId, vserverName)).request("application/json").headers(getHeaders()) - .get().readEntity(String.class); + String url = MicroServiceConfig.getMsbServerAddr() + getVmResourceLinks(vserverId, vserverName); + String response = getResponse(url); try { return aaiResponseUtil.convertJsonToVmEntity(response); } catch (Exception e) { @@ -62,18 +45,8 @@ public class AaiQuery { } } - private String getVmResourceLinks(Client client, String vserverId, String vserverName) throws CorrelationException { - WebTarget webTarget = client - .target(MicroServiceConfig.getMsbServerAddr() + AaiConfig.VM_ADDR - + "vserver-id:EQUALS:" + vserverId); - String response = webTarget.request("application/json").headers(getHeaders()).get() - .readEntity(String.class); - if (response == null) { - webTarget = client.target(MicroServiceConfig.getMsbServerAddr() + AaiConfig.VM_ADDR - + "vserver-name:EQUALS:" + vserverName); - response = webTarget.request("application/json").headers(getHeaders()).get() - .readEntity(String.class); - } + private String getVmResourceLinks(String vserverId, String vserverName) throws CorrelationException { + String response = getResourceLinksResponse(vserverId, vserverName); try { return aaiResponseUtil.convertJsonToVmResourceLink(response).get(0).getResourceLink(); } catch (Exception e) { @@ -81,11 +54,46 @@ public class AaiQuery { } } - private MultivaluedHashMap getHeaders() { - MultivaluedHashMap headers = new MultivaluedHashMap<>(); - headers.add("X-TransactionId", AaiConfig.X_TRANSACTION_ID); - headers.add("X-FromAppId", AaiConfig.X_FROMAPP_ID); - headers.add("Authorization", AaiConfig.getAuthenticationCredentials()); + private String getResourceLinksResponse(String vserverId, String vserverName) throws CorrelationException { + String url = + MicroServiceConfig.getMsbServerAddr() + AaiConfig.VM_ADDR + "vserver-id:EQUALS:" + + vserverId; + String response = getResponse(url); + if (response.equals("")) { + url = MicroServiceConfig.getMsbServerAddr() + AaiConfig.VM_ADDR + + "vserver-name:EQUALS:" + vserverName; + response = getResponse(url); + } + return response; + } + + private String getVnfDataResponse(String vnfId, String vnfName) throws CorrelationException { + String url = MicroServiceConfig.getMsbServerAddr() + AaiConfig.VNF_ADDR + "vnf-id=" + vnfId; + String response = getResponse(url); + if (response.equals("")) { + url = MicroServiceConfig.getMsbServerAddr() + AaiConfig.VNF_ADDR + "vnf-name=" + + vnfName; + response = getResponse(url); + } + return response; + } + + private String getResponse(String url) throws CorrelationException { + String response = ""; + try { + response = HttpsUtils.get(url, getHeaders()); + } catch (Exception e) { + throw new CorrelationException("Failed to get data from aai", e); + } + return response; + } + + private Map getHeaders() { + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); return headers; } } diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/aai/CorrelationUtil.java b/holmes-actions/src/main/java/org/onap/holmes/common/aai/CorrelationUtil.java index d0a4160..894b6f1 100644 --- a/holmes-actions/src/main/java/org/onap/holmes/common/aai/CorrelationUtil.java +++ b/holmes-actions/src/main/java/org/onap/holmes/common/aai/CorrelationUtil.java @@ -34,17 +34,17 @@ public class CorrelationUtil { return LazyHolder.INSTANCE; } - public boolean isTopologicallyRelated(String childId, String rootId) { + public boolean isTopologicallyRelated(String eventId, String sourceId, String sourceName) { - return Optional.ofNullable(getVmEntity(rootId)).map(vmEntity -> - getIsRelated(childId, vmEntity)).orElse(false); + return Optional.ofNullable(getVmEntity(sourceId, sourceName)).map(vmEntity -> + getIsRelated(eventId, vmEntity)).orElse(false); } - private boolean getIsRelated(String childId, VmEntity vmEntity) { + private boolean getIsRelated(String eventId, VmEntity vmEntity) { List relationships = vmEntity.getRelationshipList().getRelationships(); for (Relationship relationship : relationships) { boolean isRelated = relationship.getRelationshipDataList().stream().anyMatch( - relationshipData -> relationshipData.getRelationshipValue().equals(childId)); + relationshipData -> relationshipData.getRelationshipValue().equals(eventId)); if (isRelated) { return true; } @@ -52,10 +52,10 @@ public class CorrelationUtil { return false; } - private VmEntity getVmEntity(String rootId) { + private VmEntity getVmEntity(String sourceId, String sourceName) { VmEntity vmEntity = null; try { - vmEntity = aaiQuery.getAaiVmData("", rootId); + vmEntity = aaiQuery.getAaiVmData(sourceId, sourceName); } catch (CorrelationException e) { log.error("Failed to get vm data", e.getMessage()); } diff --git a/holmes-actions/src/main/java/org/onap/holmes/common/utils/HttpsUtils.java b/holmes-actions/src/main/java/org/onap/holmes/common/utils/HttpsUtils.java new file mode 100644 index 0000000..3ef1201 --- /dev/null +++ b/holmes-actions/src/main/java/org/onap/holmes/common/utils/HttpsUtils.java @@ -0,0 +1,177 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package org.onap.holmes.common.utils; + +import java.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.Consts; +import org.apache.http.HeaderIterator; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.util.EntityUtils; +import org.onap.holmes.common.exception.CorrelationException; + +@Slf4j +public class HttpsUtils { + private static final String HTTP = "http"; + private static final String HTTPS = "https"; + private static SSLConnectionSocketFactory sslConnectionSocketFactory = null; + private static PoolingHttpClientConnectionManager connectionManager = null; + private static SSLContextBuilder sslContextBuilder = null; + static { + try { + sslContextBuilder = new SSLContextBuilder(); + sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() { + public boolean isTrusted(X509Certificate[] x509Certificates, String s) + throws CertificateException { + return true; + } + }); + sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), + new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, + NoopHostnameVerifier.INSTANCE); + Registry registry = RegistryBuilder.create() + .register(HTTP, new PlainConnectionSocketFactory()) + .register(HTTPS, sslConnectionSocketFactory) + .build(); + connectionManager = new PoolingHttpClientConnectionManager(registry); + connectionManager.setMaxTotal(200); + } catch (Exception e) { + log.error("Failed to init ssl builder" + e.getMessage()); + } + } + + public static String post(String url, Map header, Map param, + HttpEntity entity) throws Exception { + String result = ""; + CloseableHttpClient httpClient = null; + try { + httpClient = getHttpClient(); + HttpPost httpPost = new HttpPost(url); + if (!header.isEmpty()) { + for (Map.Entry entry : header.entrySet()) { + httpPost.addHeader(entry.getKey(), entry.getValue()); + } + } + if (!param.isEmpty()) { + List formparams = new ArrayList<>(); + for (Map.Entry entry : param.entrySet()) { + formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); + } + UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, + Consts.UTF_8); + httpPost.setEntity(urlEncodedFormEntity); + } + if (entity != null) { + httpPost.setEntity(entity); + } + HttpResponse httpResponse = httpClient.execute(httpPost); + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_OK) { + HttpEntity resEntity = httpResponse.getEntity(); + result = EntityUtils.toString(resEntity); + } else { + readHttpResponse(httpResponse); + } + } catch (Exception e) { + throw new CorrelationException("Failed to use post method to get data from server"); + } finally { + if (httpClient != null) { + httpClient.close(); + } + } + return result; + } + + public static String get(String url, Map header) throws Exception { + String result = ""; + CloseableHttpClient httpClient = null; + try { + httpClient = getHttpClient(); + HttpGet httpGet = new HttpGet(url); + if (!header.isEmpty()) { + for (Map.Entry entry : header.entrySet()) { + httpGet.addHeader(entry.getKey(), entry.getValue()); + } + } + HttpResponse httpResponse = httpClient.execute(httpGet); + int statusCode = httpResponse.getStatusLine().getStatusCode(); + if (statusCode == HttpStatus.SC_OK) { + HttpEntity resEntity = httpResponse.getEntity(); + result = EntityUtils.toString(resEntity); + } else { + readHttpResponse(httpResponse); + } + } catch (Exception e) { + throw new CorrelationException("Failed to use get method get data from server"); + } finally { + if (httpClient != null) { + httpClient.close(); + } + } + return result; + } + + private static CloseableHttpClient getHttpClient() throws Exception { + CloseableHttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(sslConnectionSocketFactory) + .setConnectionManager(connectionManager) + .setConnectionManagerShared(true) + .build(); + return httpClient; + } + + private static String readHttpResponse(HttpResponse httpResponse) + throws ParseException, IOException { + StringBuilder builder = new StringBuilder(); + HttpEntity entity = httpResponse.getEntity(); + builder.append("status:" + httpResponse.getStatusLine()); + builder.append("headers:"); + HeaderIterator iterator = httpResponse.headerIterator(); + while (iterator.hasNext()) { + builder.append("\t" + iterator.next()); + } + if (entity != null) { + String responseString = EntityUtils.toString(entity); + builder.append("response length:" + responseString.length()); + builder.append("response content:" + responseString.replace("\r\n", "")); + } + return builder.toString(); + } +} diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiQueryTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiQueryTest.java new file mode 100644 index 0000000..f089881 --- /dev/null +++ b/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiQueryTest.java @@ -0,0 +1,304 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.holmes.common.aai; +import static org.easymock.EasyMock.anyObject; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.powermock.api.mockito.PowerMockito.when; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.onap.holmes.common.aai.config.AaiConfig; +import org.onap.holmes.common.aai.entity.VmEntity; +import org.onap.holmes.common.aai.entity.VnfEntity; +import org.onap.holmes.common.config.MicroServiceConfig; +import org.onap.holmes.common.exception.CorrelationException; +import org.onap.holmes.common.utils.HttpsUtils; +import org.powermock.api.easymock.PowerMock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + + +@PrepareForTest({AaiQuery.class, HttpsUtils.class, MicroServiceConfig.class}) +@RunWith(PowerMockRunner.class) +public class AaiQueryTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private AaiQuery aaiQuery; + private AaiResponseUtil aaiResponseUtil; + + @Test + public void testAaiQuery_getAaiVnfData_ok() throws Exception { + PowerMock.resetAll(); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getVnfDataResponse"); + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMock.expectPrivate(aaiQuery, "getVnfDataResponse", "test1", "test2").andReturn("{}"); + + PowerMock.replayAll(); + VnfEntity vnfEntity = Whitebox.invokeMethod(aaiQuery, "getAaiVnfData", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(vnfEntity == null, equalTo(true)); + } + + @Test + public void testAaiQuery_getAaiVnfData_exception() throws Exception { + PowerMock.resetAll(); + thrown.expect(CorrelationException.class); + thrown.expectMessage("Failed to convert aai vnf response data to vnf entity"); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getVnfDataResponse"); + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + PowerMock.expectPrivate(aaiQuery, "getVnfDataResponse", "test1", "test2") + .andReturn("{***}"); + + PowerMock.replayAll(); + aaiQuery.getAaiVnfData("test1", "test2"); + PowerMock.verifyAll(); + } + + @Test + public void testAaiQuery_getAaiVmData_ok() throws Exception { + PowerMock.resetAll(); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getVmResourceLinks"); + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + PowerMockito.mockStatic(HttpsUtils.class); + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); + String url = "host_url"; + when(HttpsUtils.get(url, headers)).thenReturn("{}"); + + PowerMockito.mockStatic(MicroServiceConfig.class); + when(MicroServiceConfig.getMsbServerAddr()).thenReturn("host_url"); + + PowerMock.expectPrivate(aaiQuery, "getVmResourceLinks", "test1", "test2").andReturn(""); + PowerMock.replayAll(); + VmEntity vmEntity = Whitebox.invokeMethod(aaiQuery, "getAaiVmData", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(vmEntity == null, equalTo(true)); + } + + + + @Test + public void testAaiQuery_getAaiVmData_exception() throws Exception { + PowerMock.resetAll(); + thrown.expect(CorrelationException.class); + thrown.expectMessage("Failed to convert aai vm response data to vm entity"); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getVmResourceLinks"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMockito.mockStatic(HttpsUtils.class); + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); + String url = "host_url"; + + when(HttpsUtils.get(url, headers)).thenReturn(""); + + PowerMockito.mockStatic(MicroServiceConfig.class); + when(MicroServiceConfig.getMsbServerAddr()).thenReturn("host_url"); + + PowerMock.expectPrivate(aaiQuery, "getVmResourceLinks", "test1", "test2").andReturn(""); + + PowerMock.replayAll(); + Whitebox.invokeMethod(aaiQuery, "getAaiVmData", "test1", "test2"); + PowerMock.verifyAll(); + } + + @Test + public void testAaiQuery_getAaiVmData_httpsutils_exception() throws Exception { + PowerMock.resetAll(); + thrown.expect(CorrelationException.class); + thrown.expectMessage("Failed to get data from aai"); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getVmResourceLinks"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMockito.mockStatic(HttpsUtils.class); + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); + String url = "host_url"; + + when(HttpsUtils.get(url, headers)).thenThrow(new CorrelationException("")); + + PowerMockito.mockStatic(MicroServiceConfig.class); + when(MicroServiceConfig.getMsbServerAddr()).thenReturn("host_url"); + + PowerMock.expectPrivate(aaiQuery, "getVmResourceLinks", "test1", "test2").andReturn(""); + PowerMock.replayAll(); + Whitebox.invokeMethod(aaiQuery, "getAaiVmData", "test1", "test2"); + PowerMock.verifyAll(); + } + + @Test + public void testAaiQuery_getVmResourceLinks_ok() throws Exception { + PowerMock.resetAll(); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getResourceLinksResponse"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + String result = "{\"result-data\":[{\"resource-type\":\"vserver\",\"resource-link\":\"le-vserver-id-val-51834\"}]}"; + + PowerMock.expectPrivate(aaiQuery, "getResourceLinksResponse", "test1", "test2").andReturn(result); + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getVmResourceLinks", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("le-vserver-id-val-51834")); + } + + @Test + public void testAaiQuery_getVmResourceLinks_exception() throws Exception { + PowerMock.resetAll(); + thrown.expect(CorrelationException.class); + thrown.expectMessage("Failed to get aai resource link"); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getResourceLinksResponse"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMock.expectPrivate(aaiQuery, "getResourceLinksResponse", "test1", "test2").andReturn(""); + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getVmResourceLinks", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("le-vserver-id-val-51834")); + } + + @Test + public void testAaiQuery_getResourceLinksResponse() throws Exception { + PowerMock.resetAll(); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getResponse"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMockito.mockStatic(MicroServiceConfig.class); + when(MicroServiceConfig.getMsbServerAddr()).thenReturn("host_url"); + + PowerMock.expectPrivate(aaiQuery, "getResponse", anyObject(String.class)).andReturn("").anyTimes(); + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getResourceLinksResponse", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("")); + } + + @Test + public void testAaiQuery_getVnfDataResponse() throws Exception { + PowerMock.resetAll(); + aaiQuery = PowerMock.createPartialMock(AaiQuery.class, "getResponse"); + + aaiResponseUtil = new AaiResponseUtil(); + Whitebox.setInternalState(aaiQuery, "aaiResponseUtil", aaiResponseUtil); + + PowerMockito.mockStatic(MicroServiceConfig.class); + when(MicroServiceConfig.getMsbServerAddr()).thenReturn("host_url"); + + PowerMock.expectPrivate(aaiQuery, "getResponse", anyObject(String.class)).andReturn("").anyTimes(); + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getVnfDataResponse", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("")); + } + + @Test + public void testAaiQuery_getResponse_ok() throws Exception { + PowerMock.resetAll(); + aaiQuery = new AaiQuery(); + PowerMockito.mockStatic(HttpsUtils.class); + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); + String url = "host_url"; + + when(HttpsUtils.get(url, headers)).thenReturn(""); + + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getResponse", "host_url"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("")); + } + + @Test + public void testAaiQuery_getResponse_exceptioin() throws Exception { + PowerMock.resetAll(); + thrown.expect(CorrelationException.class); + thrown.expectMessage("Failed to get data from aai"); + aaiQuery = new AaiQuery(); + + PowerMockito.mockStatic(HttpsUtils.class); + Map headers = new HashMap<>(); + headers.put("X-TransactionId", AaiConfig.X_TRANSACTION_ID); + headers.put("X-FromAppId", AaiConfig.X_FROMAPP_ID); + headers.put("Authorization", AaiConfig.getAuthenticationCredentials()); + headers.put("Accept", "application/json"); + String url = "host_url"; + + when(HttpsUtils.get(url, headers)).thenThrow(new CorrelationException("")); + + PowerMock.replayAll(); + String resource = Whitebox.invokeMethod(aaiQuery, "getResponse", "host_url"); + PowerMock.verifyAll(); + + assertThat(resource, equalTo("")); + + } + + @Test + public void testAaiQuery_getHeaders() throws Exception { + PowerMock.resetAll(); + aaiQuery = new AaiQuery(); + PowerMock.replayAll(); + Map actual = Whitebox.invokeMethod(aaiQuery, "getHeaders"); + PowerMock.verifyAll(); + + assertThat(actual.get("X-TransactionId"), equalTo("9999")); + assertThat(actual.get("X-FromAppId"), equalTo("jimmy-postman")); + assertThat(actual.get("Authorization"), equalTo("Basic QUFJOkFBSQ==")); + assertThat(actual.get("Accept"), equalTo("application/json")); + } +} diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiResponseUtilTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiResponseUtilTest.java new file mode 100644 index 0000000..fee98b9 --- /dev/null +++ b/holmes-actions/src/test/java/org/onap/holmes/common/aai/AaiResponseUtilTest.java @@ -0,0 +1,326 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.holmes.common.aai; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.io.IOException; +import java.util.List; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.holmes.common.aai.entity.VmEntity; +import org.onap.holmes.common.aai.entity.VmResourceLink; +import org.onap.holmes.common.aai.entity.VnfEntity; +import org.powermock.core.classloader.annotations.PrepareForTest; + +@PrepareForTest(AaiResponseUtil.class) +public class AaiResponseUtilTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private AaiResponseUtil aaiResponseUtil; + + @Before + public void setUp() { + aaiResponseUtil = new AaiResponseUtil(); + } + + @Test + public void testAaiResponseUtil_convert_resouce_link_success() throws IOException { + String json = "{" + + "\"result-data\": [" + + "{" + + "\"resource-link\": \"/aai/example-vserver-id-val-2\"," + + "\"resource-type\": \"vserver\"" + + "}," + + "{" + + "\"resource-link\": \"/111aai/example-vserver-id-val-2\"," + + "\"resource-type\": \"111vserver\"" + + "}" + + "]" + + "}"; + + List actual = aaiResponseUtil.convertJsonToVmResourceLink(json); + + assertThat(actual.get(0).getResourceLink(), equalTo("/aai/example-vserver-id-val-2")); + assertThat(actual.get(0).getResourceType(), equalTo("vserver")); + assertThat(actual.get(1).getResourceLink(), equalTo("/111aai/example-vserver-id-val-2")); + assertThat(actual.get(1).getResourceType(), equalTo("111vserver")); + } + + @Test + public void testAaiResponseUtil_convert_resource_link_input_empty_array() throws IOException { + String json = "{" + + "\"result-data\": [" + + "]" + + "}"; + List actual = aaiResponseUtil.convertJsonToVmResourceLink(json); + assertThat(actual.isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_resource_link_input_empty() throws IOException { + String json = "{}"; + List actual = aaiResponseUtil.convertJsonToVmResourceLink(json); + assertThat(actual.isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_resource_link_input_error() throws IOException { + String json = "{" + + "\"result-data\": [" + + "{" + + "\"resource-link1\": \"/aai/example-vserver-id-val-2\"," + + "\"resource-type\": \"vserver\"" + + "}," + + "{" + + "\"resource-link\": \"/111aai/example-vserver-id-val-2\"," + + "\"resource-type\": \"111vserver\"" + + "}" + + "]" + + "}"; + List actual = aaiResponseUtil.convertJsonToVmResourceLink(json); + assertThat(actual.size(), equalTo(1)); + assertThat(actual.get(0).getResourceType(), equalTo("111vserver")); + } + + @Test + public void testAaiResponseUtil_convert_resource_link_input_error1() throws IOException { + String json = "{" + + "\"result-data1\": [" + + "]" + + "}"; + List actual = aaiResponseUtil.convertJsonToVmResourceLink(json); + assertThat(actual.isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_resource_link_throw_IOException() throws IOException { + thrown.expect(IOException.class); + String json = "{**}"; + aaiResponseUtil.convertJsonToVmResourceLink(json); + } + + @Test + public void testAaiResponseUtil_convert_VmEntity_success() throws IOException { + String json = "{" + + "\"in-maint\": true," + + "\"is-closed-loop-disabled\": true," + + "\"prov-status\": \"example-prov-status-val-2\"," + + "\"resource-version\": \"1504912891060\"," + + "\"vserver-id\": \"example-vserver-id-val-2\"," + + "\"vserver-name\": \"example-vserver-name-val-2\"," + + "\"vserver-name2\": \"example-vserver-name2-val-2\"," + + "\"vserver-selflink\": \"example-vserver-selflink-val-2\"" + + "}"; + VmEntity actual = aaiResponseUtil.convertJsonToVmEntity(json); + assertThat(actual.getInMaint(), equalTo(true)); + assertThat(actual.getClosedLoopDisable(), equalTo(true)); + assertThat(actual.getProvStatus(), equalTo("example-prov-status-val-2")); + assertThat(actual.getResourceVersion(), equalTo("1504912891060")); + assertThat(actual.getVserverId(), equalTo("example-vserver-id-val-2")); + assertThat(actual.getVserverName(), equalTo("example-vserver-name-val-2")); + assertThat(actual.getVserverName2(), equalTo("example-vserver-name2-val-2")); + assertThat(actual.getVserverSelflink(), equalTo("example-vserver-selflink-val-2")); + } + + @Test + public void testAaiResponseUtil_convert_VmEntity_throw_IOException() throws IOException { + thrown.expect(IOException.class); + String json = "{**}"; + aaiResponseUtil.convertJsonToVmEntity(json); + } + + @Test + public void testAaiResponseUtil_convert_VmEntity_input_empty() throws IOException { + String json = "{}"; + VmEntity actual = aaiResponseUtil.convertJsonToVmEntity(json); + assertThat(actual == null, equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_VmEntity_input_error() throws IOException { + String json = "{" + + "\"in-maint1\": true," + + "\"is-closed-loop-disabled\": true," + + "\"prov-status\": \"example-prov-status-val-2\"," + + "\"resource-version\": \"1504912891060\"," + + "\"vserver-id\": \"example-vserver-id-val-2\"," + + "\"vserver-name\": \"example-vserver-name-val-2\"," + + "\"vserver-name2\": \"example-vserver-name2-val-2\"," + + "\"vserver-selflink\": \"example-vserver-selflink-val-2\"" + + "}"; + VmEntity actual = aaiResponseUtil.convertJsonToVmEntity(json); + assertThat(actual.getInMaint() == null, equalTo(true)); + assertThat(actual.getClosedLoopDisable(), equalTo(true)); + assertThat(actual.getProvStatus(), equalTo("example-prov-status-val-2")); + assertThat(actual.getResourceVersion(), equalTo("1504912891060")); + assertThat(actual.getVserverId(), equalTo("example-vserver-id-val-2")); + assertThat(actual.getVserverName(), equalTo("example-vserver-name-val-2")); + assertThat(actual.getVserverName2(), equalTo("example-vserver-name2-val-2")); + assertThat(actual.getVserverSelflink(), equalTo("example-vserver-selflink-val-2")); + } + + @Test + public void testAaiResponseUtil_convert_success() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-link\":\"/aai/v11/e8fe\"," + + "\"related-to\":\"service-instance\"," + + "\"related-to-property\":[" + + "{" + + "\"property-key\":\"service-i\"," + + "\"property-value\":\"vCPEInfraSI13\"" + + "}" + + "]," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"custome\"," + + "\"relationship-value\":\"Demonstration3\"" + + "}" + + "]" + + "}" + + "]" + + "}" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + + assertThat(actual.getInMaint(), equalTo(false)); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedLink(), + equalTo("/aai/v11/e8fe")); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedTo(), + equalTo("service-instance")); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedToPropertyList() + .get(0).getPropertyKey(), equalTo("service-i")); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedToPropertyList() + .get(0).getPropertyValue(), equalTo("vCPEInfraSI13")); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelationshipDataList().get(0) + .getRelationshipKey(), equalTo("custome")); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelationshipDataList().get(0) + .getRelationshipValue(), equalTo("Demonstration3")); + } + + @Test + public void testAaiResponseUtil_throw_IOException() throws IOException { + thrown.expect(IOException.class); + String json = "{**}"; + aaiResponseUtil.convertJsonToVnfEntity(json); + } + + @Test + public void testAaiResponseUtil_convert_VnfEntity_input_empty() throws IOException { + String json = "{}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual == null, equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_input_not_include_relationship_list() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"vnf-type\":\"vCPEInfraService10/vCPEInfraService10 0\"" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual.getRelationshipList().getRelationships().isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_input_not_include_relationship() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"is-closed-loop-disabled\":false," + + "\"relationship-list\":{" + + "}," + + "\"service-id\":\"e8cb8968-5411-478b-906a-f28747de72cd\"" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual.getRelationshipList().getRelationships().isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_input_relationship_empty() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "]" + + "}," + + "\"vnf-type\":\"vCPEInfraService10/vCPEInfraService10 0\"" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual.getRelationshipList().getRelationships().isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_input_not_include_related_to_property() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-link\":\"/aai/6\"," + + "\"related-to\":\"service-instance\"," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"service-instance.service-instance-id\"," + + "\"relationship-value\":\"e8feceb6-28ae-480a-bfbc-1985ce333526\"" + + "}" + + "]" + + "}" + + "]" + + "}," + + "\"vnf-type\":\"vCPEInfraSe0\"" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedToPropertyList() + .isEmpty(), equalTo(true)); + } + + @Test + public void testAaiResponseUtil_convert_input_related_to_property_empty() throws IOException { + String json = "{" + + "\"in-maint\":false," + + "\"relationship-list\":{" + + "\"relationship\":[" + + "{" + + "\"related-link\":\"/aai/3526\"," + + "\"related-to\":\"service-instance\"," + + "\"related-to-property\":[" + + "]," + + "\"relationship-data\":[" + + "{" + + "\"relationship-key\":\"servicnce-id\"," + + "\"relationship-value\":\"e8feceb6-28a6\"" + + "}" + + "]" + + "}" + + "]" + + "}," + + "\"vnf-type\":\"vCPEce10\"" + + "}"; + VnfEntity actual = aaiResponseUtil.convertJsonToVnfEntity(json); + assertThat(actual.getRelationshipList().getRelationships().get(0).getRelatedToPropertyList() + .isEmpty(), equalTo(true)); + } +} \ No newline at end of file diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/aai/CorrelationUtilTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/aai/CorrelationUtilTest.java new file mode 100644 index 0000000..f5da5df --- /dev/null +++ b/holmes-actions/src/test/java/org/onap/holmes/common/aai/CorrelationUtilTest.java @@ -0,0 +1,119 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.holmes.common.aai; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.onap.holmes.common.aai.entity.RelationshipList.Relationship; +import org.onap.holmes.common.aai.entity.RelationshipList.RelationshipData; +import org.onap.holmes.common.aai.entity.VmEntity; +import org.onap.holmes.common.exception.CorrelationException; +import org.powermock.api.easymock.PowerMock; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@PrepareForTest({CorrelationUtil.class, AaiQuery.class}) +@RunWith(PowerMockRunner.class) +public class CorrelationUtilTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private CorrelationUtil correlationUtil; + private AaiQuery aaiQuery; + + @Before + public void testCorrelationUtil() { + correlationUtil = CorrelationUtil.getInstance(); + aaiQuery = PowerMock.createMock(AaiQuery.class); + Whitebox.setInternalState(correlationUtil, "aaiQuery", aaiQuery); + } + + @Test + public void testCorrelationUtil_isTopologicallyRelated_true() throws Exception { + PowerMock.resetAll(); + VmEntity vmEntity = new VmEntity(); + List relationships = new ArrayList<>(); + + List relationshipDataList = new ArrayList<>(); + RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey("vnf-id"); + relationshipData.setRelationshipValue("123"); + relationshipDataList.add(relationshipData); + Relationship relationship = new Relationship(); + relationship.setRelationshipDataList(relationshipDataList); + relationships.add(relationship); + vmEntity.getRelationshipList().setRelationships(relationships); + + PowerMock.expectPrivate(aaiQuery, "getAaiVmData", "test1", "test2").andReturn(vmEntity).anyTimes(); + + PowerMock.replayAll(); + boolean actual = Whitebox + .invokeMethod(correlationUtil, "isTopologicallyRelated", "123", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(actual, equalTo(true)); + } + + @Test + public void testCorrelationUtil_isTopologicalRelated_false() throws Exception { + PowerMock.resetAll(); + VmEntity vmEntity = new VmEntity(); + List relationships = new ArrayList<>(); + List relationshipDataList = new ArrayList<>(); + RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey("vnf-id"); + relationshipData.setRelationshipValue("1231"); + relationshipDataList.add(relationshipData); + Relationship relationship = new Relationship(); + relationship.setRelationshipDataList(relationshipDataList); + relationships.add(relationship); + vmEntity.getRelationshipList().setRelationships(relationships); + + PowerMock.expectPrivate(aaiQuery, "getAaiVmData", "test1", "test2").andReturn(vmEntity) + .anyTimes(); + + PowerMock.replayAll(); + boolean actual = Whitebox + .invokeMethod(correlationUtil, "isTopologicallyRelated", "123", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(actual, equalTo(false)); + } + + @Test + public void testCorrelationUtil_isTopologicalRelated_exception_false() throws Exception { + PowerMock.resetAll(); + PowerMock.expectPrivate(aaiQuery, "getAaiVmData", "test1", "test2") + .andThrow(new CorrelationException("")).anyTimes(); + + PowerMock.replayAll(); + boolean actual = Whitebox + .invokeMethod(correlationUtil, "isTopologicallyRelated", "123", "test1", "test2"); + PowerMock.verifyAll(); + + assertThat(actual, equalTo(false)); + } +} \ No newline at end of file diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/config/MicroServiceConfigTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/config/MicroServiceConfigTest.java index 4b697b0..13064c5 100644 --- a/holmes-actions/src/test/java/org/onap/holmes/common/config/MicroServiceConfigTest.java +++ b/holmes-actions/src/test/java/org/onap/holmes/common/config/MicroServiceConfigTest.java @@ -135,9 +135,7 @@ public class MicroServiceConfigTest { .andReturn("{}"); PowerMock.replayAll(); - assertThat(getServiceAddrInfoFromCBS(HOSTNAME), is(nullValue())); - PowerMock.verifyAll(); } @@ -170,11 +168,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getMsbAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("127.0.0.3")); assertThat(msbInfo[1], equalTo("5432")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } @@ -189,11 +187,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getMsbAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("1545")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } @@ -208,11 +206,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("127.0.0.3")); assertThat(msbInfo[1], equalTo("5432")); - PowerMock.verifyAll(); - System.clearProperty(HOSTNAME); } @@ -227,11 +225,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("1545")); - PowerMock.verifyAll(); - System.clearProperty(HOSTNAME); } @@ -246,11 +244,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("1545")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } @@ -265,11 +263,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("80")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } @@ -284,11 +282,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("80")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } @@ -303,11 +301,11 @@ public class MicroServiceConfigTest { PowerMock.replayAll(); String[] msbInfo = getServiceAddrInfo(); + PowerMock.verifyAll(); + assertThat(msbInfo[0], equalTo("10.74.5.8")); assertThat(msbInfo[1], equalTo("5432")); - PowerMock.verifyAll(); - System.clearProperty(MSB_ADDR); } } \ No newline at end of file diff --git a/holmes-actions/src/test/java/org/onap/holmes/common/dmaap/DmaapServiceTest.java b/holmes-actions/src/test/java/org/onap/holmes/common/dmaap/DmaapServiceTest.java new file mode 100644 index 0000000..b6f57ce --- /dev/null +++ b/holmes-actions/src/test/java/org/onap/holmes/common/dmaap/DmaapServiceTest.java @@ -0,0 +1,216 @@ +/** + * Copyright 2017 ZTE Corporation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.holmes.common.dmaap; + +import static org.easymock.EasyMock.anyObject; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.List; +import org.junit.runner.RunWith; +import org.onap.holmes.common.aai.AaiQuery; +import org.onap.holmes.common.aai.entity.RelationshipList.Relationship; +import org.onap.holmes.common.aai.entity.RelationshipList.RelationshipData; +import org.onap.holmes.common.aai.entity.VmEntity; +import org.onap.holmes.common.aai.entity.VnfEntity; +import org.onap.holmes.common.api.stat.VesAlarm; +import org.onap.holmes.common.exception.CorrelationException; +import org.powermock.core.classloader.annotations.PrepareForTest; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.holmes.common.dmaap.entity.PolicyMsg; +import org.powermock.api.easymock.PowerMock; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@PrepareForTest({DmaapService.class, Publisher.class, AaiQuery.class}) +@RunWith(PowerMockRunner.class) +public class DmaapServiceTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private Publisher publisher; + + private AaiQuery aaiQuery; + + @Before + public void setUp() { + publisher = PowerMock.createMock(Publisher.class); + Whitebox.setInternalState(DmaapService.class, "publisher", publisher); + aaiQuery = PowerMock.createMock(AaiQuery.class); + Whitebox.setInternalState(DmaapService.class, "aaiQuery", aaiQuery); + PowerMock.replayAll(); + } + + @Test + public void testDmaapService_publish_ok() throws Exception { + PowerMock.resetAll(); + PolicyMsg policyMsg = new PolicyMsg(); + PowerMock.expectPrivate(publisher, "publish", anyObject(PolicyMsg.class)).andReturn(true) + .anyTimes(); + PowerMock.replayAll(); + Whitebox.invokeMethod(DmaapService.class, "publishPolicyMsg", policyMsg); + PowerMock.verifyAll(); + } + + @Test + public void testDmaapService_publish_exception() throws Exception { + PowerMock.resetAll(); + final PolicyMsg policyMsg = new PolicyMsg(); + PowerMock.expectPrivate(publisher, "publish", policyMsg) + .andThrow(new CorrelationException("")).anyTimes(); + PowerMock.replayAll(); + Whitebox.invokeMethod(DmaapService.class, "publishPolicyMsg", policyMsg); + PowerMock.verifyAll(); + } + + @Test + public void testDmaapService_getDefaultPolicyMsg_ok() throws Exception { + PowerMock.resetAll(); + + PowerMock.replayAll(); + PolicyMsg policyMsg = Whitebox + .invokeMethod(DmaapService.class, "getDefaultPolicyMsg", "tetss"); + PowerMock.verifyAll(); + + assertThat(policyMsg.getTarget(), equalTo("vserver.vserver-name")); + assertThat(policyMsg.getTargetType(), equalTo("VM")); + assertThat(policyMsg.getAai().get("vserver.vserver-name"), equalTo("tetss")); + } + + @Test + public void testDmaapService_getVnfEntity_ok() throws Exception { + PowerMock.resetAll(); + VnfEntity expect = new VnfEntity(); + expect.setVnfName("test"); + PowerMock.expectPrivate(aaiQuery, "getAaiVnfData", anyObject(String.class), + anyObject(String.class)).andReturn(expect).anyTimes(); + PowerMock.replayAll(); + VnfEntity actual = Whitebox + .invokeMethod(DmaapService.class, "getVnfEntity", "tset", "test"); + PowerMock.verifyAll(); + + assertThat(actual.getVnfName(), equalTo("test")); + } + + @Test + public void testDmaapService_getVnfEntity_exception() throws Exception { + PowerMock.resetAll(); + PowerMock.expectPrivate(aaiQuery, "getAaiVnfData", anyObject(String.class), + anyObject(String.class)).andThrow(new CorrelationException("")).anyTimes(); + PowerMock.replayAll(); + VnfEntity actual = Whitebox.invokeMethod(DmaapService.class, "getVnfEntity", "tset", "test"); + PowerMock.verifyAll(); + + assertThat(actual == null, equalTo(true)); + } + + @Test + public void testDmaapService_getVmEntity_ok() throws Exception { + PowerMock.resetAll(); + VmEntity expect = new VmEntity(); + expect.setVserverId("11111"); + PowerMock.expectPrivate(aaiQuery, "getAaiVmData", anyObject(String.class), + anyObject(String.class)).andReturn(expect).anyTimes(); + PowerMock.replayAll(); + VmEntity actual = Whitebox + .invokeMethod(DmaapService.class, "getVmEntity", "tset", "test"); + PowerMock.verifyAll(); + + assertThat(actual.getVserverId(), equalTo("11111")); + } + + @Test + public void testDmaapService_getVmEntity_exception() throws Exception { + PowerMock.resetAll(); + PowerMock.expectPrivate(aaiQuery, "getAaiVmData", anyObject(String.class), + anyObject(String.class)).andThrow(new CorrelationException("")).anyTimes(); + PowerMock.replayAll(); + VnfEntity actual = Whitebox.invokeMethod(DmaapService.class, "getVmEntity", "tset", "test"); + PowerMock.verifyAll(); + + assertThat(actual == null, equalTo(true)); + } + + @Test + public void testDmaapService_getVserverInstanceId_ok() throws Exception { + PowerMock.resetAll(); + VnfEntity vnfEntity = new VnfEntity(); + Relationship relationship = new Relationship(); + relationship.setRelatedTo("service-instance"); + + List relationshipDataList = new ArrayList<>(); + + RelationshipData relationshipData = new RelationshipData(); + relationshipData.setRelationshipKey("service-instance.service-instance-id"); + relationshipData.setRelationshipValue("USUCP0PCOIL0110UJZZ01"); + relationshipDataList.add(relationshipData); + relationship.setRelationshipDataList(relationshipDataList); + + List relationships = new ArrayList<>(); + relationships.add(relationship); + vnfEntity.getRelationshipList().setRelationships(relationships); + + PowerMock.replayAll(); + String actual = Whitebox.invokeMethod(DmaapService.class, "getVserverInstanceId", vnfEntity); + PowerMock.verifyAll(); + + assertThat(actual, equalTo("USUCP0PCOIL0110UJZZ01")); + } + + @Test + public void testDmaapService_getVserverInstanceId_input_null() throws Exception { + PowerMock.resetAll(); + VnfEntity vnfEntity = null; + + PowerMock.replayAll(); + String actual = Whitebox.invokeMethod(DmaapService.class, "getVserverInstanceId", vnfEntity); + PowerMock.verifyAll(); + + assertThat(actual, equalTo("")); + } + + @Test + public void testDmaapService_getEnrichedPolicyMsg_ok() throws Exception { + PowerMock.resetAll(); + VmEntity vmEntity = new VmEntity(); + vmEntity.setInMaint(false); + vmEntity.setClosedLoopDisable(true); + vmEntity.setProvStatus("prov"); + vmEntity.setResourceVersion("kkkk"); + VesAlarm vesAlarm = new VesAlarm(); + vesAlarm.setEventId("11111"); + vesAlarm.setEventName("3333"); + + PowerMock.expectPrivate(DmaapService.class, "getVnfEntity", anyObject(String.class), + anyObject(String.class)).andReturn(null).anyTimes(); + + PowerMock.replayAll(); + PolicyMsg actual = Whitebox + .invokeMethod(DmaapService.class, "getEnrichedPolicyMsg", vmEntity, vesAlarm); + PowerMock.verifyAll(); + + assertThat(actual.getPolicyName(), equalTo("vLoadBalancer")); + assertThat(actual.getAai().get("vserver.prov-status"), equalTo("prov")); + assertThat(actual.getAai().get("vserver.vserver-name2") == null, equalTo(true)); + assertThat(actual.getAai().get("generic-vnf.service-instance-id"), equalTo("")); + } +} \ No newline at end of file -- 2.16.6