2 * ============LICENSE_START===================================================
3 * Copyright (c) 2018 Amdocs
4 * ============================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 * ============LICENSE_END=====================================================
19 package org.onap.sdnc.apps.pomba.networkdiscovery.unittest.service;
21 import static com.github.tomakehurst.wiremock.client.WireMock.get;
22 import static com.github.tomakehurst.wiremock.client.WireMock.ok;
23 import static com.github.tomakehurst.wiremock.client.WireMock.okTextXml;
24 import static com.github.tomakehurst.wiremock.client.WireMock.post;
25 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertTrue;
29 import static org.junit.Assert.fail;
31 import com.fasterxml.jackson.databind.AnnotationIntrospector;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.fasterxml.jackson.databind.type.TypeFactory;
34 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
35 import com.github.tomakehurst.wiremock.junit.WireMockRule;
36 import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
37 import com.github.tomakehurst.wiremock.verification.LoggedRequest;
38 import java.net.URISyntaxException;
39 import java.text.MessageFormat;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.Base64;
43 import java.util.List;
44 import java.util.UUID;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.ws.rs.core.HttpHeaders;
47 import javax.ws.rs.core.Response;
48 import javax.ws.rs.core.Response.Status;
49 import org.junit.After;
50 import org.junit.Before;
51 import org.junit.Rule;
52 import org.junit.Test;
53 import org.junit.runner.RunWith;
54 import org.onap.logging.ref.slf4j.ONAPLogConstants;
55 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
56 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.DataQuality;
57 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
58 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryResponse;
59 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Resource;
60 import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
63 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
64 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
65 import org.springframework.boot.test.context.SpringBootTest;
66 import org.springframework.core.env.Environment;
67 import org.springframework.test.context.TestPropertySource;
68 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
69 import org.springframework.test.context.web.WebAppConfiguration;
71 @RunWith(SpringJUnit4ClassRunner.class)
72 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
75 @TestPropertySource(properties = {
76 "enricher.url=http://localhost:9505",
77 "basicAuth.username=admin",
78 "basicAuth.password=admin"
80 public class NetworkDiscoveryTest {
81 private static final String V1 = "v1";
82 private static final String APP = "junit";
84 private static final String RESOURCE_TYPE_VSERVER = "vserver";
85 private static final String CALLBACK_PATH = "/callback";
87 private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString("admin:admin".getBytes());
89 private Environment environment;
92 public WireMockRule enricherRule = new WireMockRule(wireMockConfig().port(9505));
95 public WireMockRule callbackRule = new WireMockRule(wireMockConfig().dynamicPort());
98 private RestService service;
100 private String transactionId = UUID.randomUUID().toString();
101 private String requestId = UUID.randomUUID().toString();
102 private HttpServletRequest httpRequest = new TestHttpServletRequest();
104 public NetworkDiscoveryTest() throws URISyntaxException {
109 public void setUp() throws Exception {
113 public void tearDown() throws Exception {
117 public void testNoAuthHeader() throws Exception {
118 // no Authorization header
119 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
120 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
121 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
122 assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
123 // should get WWW-Authenticate header in response
124 assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
128 public void testUnauthorized() throws Exception {
129 String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
130 // bad Authorization header
131 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
132 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP, this.transactionId,
133 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
134 assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
135 // should not get WWW-Authenticate header in response
136 assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
140 public void testVerifyAppId() throws Exception {
141 // no X-FromAppId header
142 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
143 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
144 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
145 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
146 assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
150 public void testVerifyRequestId() throws Exception {
151 // no X-FromAppId header
152 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
153 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
154 null, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
155 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
156 assertTrue(((String)response.getEntity()).contains("requestId"));
160 public void testVerifyNotificationUrl() throws Exception {
161 // no X-FromAppId header
162 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
163 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
164 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, null);
165 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
166 assertTrue(((String)response.getEntity()).contains("notificationURL"));
170 public void testVerifyResourceIds() throws Exception {
171 // no resourceIds list
173 List<String> resourceIds = null;
174 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
175 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
176 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
177 assertTrue(((String)response.getEntity()).contains("resourceIds"));
180 // empty resourceId list
182 List<String> resourceIds = new ArrayList<>();
183 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
184 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
185 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
186 assertTrue(((String)response.getEntity()).contains("resourceIds"));
192 public void testVerifyResourceType() throws Exception {
194 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
195 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
196 this.requestId, null, resourceIds, getCallbackUrl());
197 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
198 assertTrue(((String)response.getEntity()).contains("resourceType"));
202 public void testDiscoverVserver() throws Exception {
203 String vserverId = UUID.randomUUID().toString();
205 String resourcePath = MessageFormat.format(
206 this.environment.getProperty("enricher.type.vserver.url"),
207 new Object[] { vserverId });
209 String enricherPayload = String.format(
210 "<vserver xmlns=\"http://org.onap.aai.inventory/v11\">\r\n"
211 + " <vserver-id>%s</vserver-id>\r\n"
212 + " <power-state>1</power-state>\r\n"
213 + " <vm-state>active</vm-state>\r\n"
214 + " <status>ACTIVE</status>\r\n"
215 + " <host-status>UNKNOWN</host-status>\r\n"
216 + " <updated>2017-11-20T04:26:13Z</updated>\r\n"
217 + " <disk-allocation-gb>.010</disk-allocation-gb>\r\n"
218 + " <memory-usage-mb>null</memory-usage-mb>\r\n"
219 + " <cpu-util-percent>.043</cpu-util-percent>\r\n"
220 + " <retrieval-timestamp>2018-06-27 19:41:49 +0000</retrieval-timestamp>\r\n"
221 + "</vserver>", vserverId);
223 this.enricherRule.stubFor(get(resourcePath).willReturn(okTextXml(enricherPayload)));
225 this.callbackRule.stubFor(post(CALLBACK_PATH).willReturn(ok("Acknowledged")));
227 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
228 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId), getCallbackUrl());
230 assertEquals(Status.OK.getStatusCode(), response.getStatus());
231 NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
232 assertEquals(requestId, entity.getRequestId());
233 assertEquals(Status.ACCEPTED.getStatusCode(), entity.getCode().intValue());
234 assertEquals(Boolean.FALSE, entity.getAckFinalIndicator());
236 List<ServeEvent> events = waitForRequests(this.callbackRule, 1, 10);
237 LoggedRequest notificationRequest = events.get(0).getRequest();
238 assertEquals(AUTH, notificationRequest.getHeader(HttpHeaders.AUTHORIZATION));
239 String notificationJson = notificationRequest.getBodyAsString();
241 ObjectMapper mapper = new ObjectMapper();
242 AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
243 mapper.setAnnotationIntrospector(introspector);
244 NetworkDiscoveryNotification notification =
245 mapper.readValue(notificationJson, NetworkDiscoveryNotification.class);
247 assertEquals(requestId, notification.getRequestId());
248 assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
249 assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
251 assertEquals(1, notification.getResources().size());
252 Resource vserver = notification.getResources().get(0);
253 assertEquals(vserverId, vserver.getId());
254 assertEquals("vserver", vserver.getType());
255 assertEquals(DataQuality.Status.ok, vserver.getDataQuality().getStatus());
257 verifyAttribute(vserver.getAttributeList(), "power-state", "1");
258 verifyAttribute(vserver.getAttributeList(), "vm-state", "active");
259 verifyAttribute(vserver.getAttributeList(), "status", "ACTIVE");
260 verifyAttribute(vserver.getAttributeList(), "host-status", "UNKNOWN");
261 verifyAttribute(vserver.getAttributeList(), "updated", "2017-11-20T04:26:13Z");
262 verifyAttribute(vserver.getAttributeList(), "disk-allocation-gb", ".010");
263 verifyAttribute(vserver.getAttributeList(), "memory-usage-mb", "null");
264 verifyAttribute(vserver.getAttributeList(), "cpu-util-percent", ".043");
265 verifyAttribute(vserver.getAttributeList(), "retrieval-timestamp", "2018-06-27 19:41:49 +0000");
269 * Verify API returns a final response indicating no discovery possible.
272 public void testUnsupportedResourceType() throws Exception {
274 String resourceType = "unsupported";
275 List<String> resourceIds = Arrays.asList("dummyId");
276 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
277 this.requestId, resourceType, resourceIds, getCallbackUrl());
278 assertEquals(Status.OK.getStatusCode(), response.getStatus());
280 NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
281 assertEquals(Boolean.TRUE, entity.getAckFinalIndicator());
282 assertEquals(Status.NO_CONTENT.getStatusCode(), entity.getCode().intValue());
285 private void verifyAttribute(List<Attribute> attributeList, String attrName, String attrValue) {
286 for (Attribute attr : attributeList) {
287 if (attr.getName().equals(attrName)) {
288 assertEquals("Unexpected value for attribute " + attrName, attrValue, attr.getValue());
292 fail("Attribute " + attrName + " not found");
295 private List<ServeEvent> waitForRequests(WireMockRule service, int minRequests, long timeoutSeconds)
296 throws InterruptedException {
298 long remaining = timeoutSeconds * 1000L;
299 long retryInterval = Math.min(remaining / 5, 1000);
301 List<ServeEvent> events = service.getAllServeEvents();
302 if (events.size() >= minRequests) {
305 if (remaining <= 0) {
306 fail("Timeout waiting for " + minRequests + " requests");
308 Thread.sleep(retryInterval);
309 remaining -= retryInterval;
313 private String getCallbackUrl() {
314 return "http://localhost:" + this.callbackRule.port() + CALLBACK_PATH;