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.okJson;
23 import static com.github.tomakehurst.wiremock.client.WireMock.post;
24 import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
30 import com.bazaarvoice.jolt.JsonUtils;
31 import com.github.tomakehurst.wiremock.client.WireMock;
32 import com.github.tomakehurst.wiremock.junit.WireMockRule;
34 import java.net.URISyntaxException;
35 import java.text.MessageFormat;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Base64;
39 import java.util.List;
40 import java.util.UUID;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.ws.rs.core.HttpHeaders;
44 import javax.ws.rs.core.Response;
45 import javax.ws.rs.core.Response.Status;
47 import org.eclipse.jetty.util.security.Password;
48 import org.junit.After;
49 import org.junit.Before;
50 import org.junit.Rule;
51 import org.junit.Test;
52 import org.junit.runner.RunWith;
53 import org.mockito.Mockito;
54 import org.onap.logging.ref.slf4j.ONAPLogConstants;
55 import org.onap.pomba.common.datatypes.DataQuality;
56 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
57 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
58 import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Resource;
59 import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
62 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
63 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
64 import org.springframework.boot.test.context.SpringBootTest;
65 import org.springframework.test.context.TestPropertySource;
66 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
67 import org.springframework.test.context.web.WebAppConfiguration;
69 @RunWith(SpringJUnit4ClassRunner.class)
70 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
73 @TestPropertySource(properties = { "openstack.type.vserver.url=http://localhost:8774/v2.1/servers/{0}",
74 "openstack.identity.url=http://localhost:5000/v3/auth/tokens",
75 "enricher.keyStorePath=src/test/resources/client-cert-onap.p12",
76 "enricher.keyStorePassword=OBF:1y0q1uvc1uum1uvg1pil1pjl1uuq1uvk1uuu1y10",
77 "basicAuth.username=admin",
78 "basicAuth.password=OBF:1u2a1toa1w8v1tok1u30" })
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";
86 private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString((
87 "admin:" + Password.deobfuscate("OBF:1u2a1toa1w8v1tok1u30")).getBytes());
90 public WireMockRule identityRule = new WireMockRule(wireMockConfig().port(5000));
93 public WireMockRule openstackRule = new WireMockRule(wireMockConfig().port(8774));
96 public WireMockRule callbackRule = new WireMockRule(wireMockConfig().dynamicPort());
99 private RestService service;
101 private String transactionId = UUID.randomUUID().toString();
102 private String requestId = UUID.randomUUID().toString();
103 private HttpServletRequest httpRequest = Mockito.mock(HttpServletRequest.class);
105 private static final String TEST_RESOURCES = "src/test/resources/jolt/";
108 public NetworkDiscoveryTest() throws URISyntaxException {
113 public void setUp() throws Exception {
117 public void tearDown() throws Exception {
121 public void testNoAuthHeader() throws Exception {
122 // no Authorization header
123 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
124 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
125 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
126 assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
127 // should get WWW-Authenticate header in response
128 assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
132 public void testUnauthorized() throws Exception {
133 String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
134 // bad Authorization header
135 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
136 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP,
137 this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
138 assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
139 // should not get WWW-Authenticate header in response
140 assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
144 public void testNoVersion() throws Exception {
145 // no Authorization header
146 String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
147 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
148 Response response = this.service.findbyResourceIdAndType(this.httpRequest, null, authorization, APP,
149 this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
150 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
151 // should get WWW-Authenticate header in response
152 assertTrue(((String) response.getEntity()).contains("version"));
156 public void testVerifyAppId() throws Exception {
157 // no X-FromAppId header
158 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
159 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
160 this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
161 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
162 assertTrue(((String) response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
166 public void testVerifyRequestId() throws Exception {
167 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
168 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
169 null, RESOURCE_TYPE_VSERVER, resourceIds);
170 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
171 assertTrue(((String) response.getEntity()).contains("requestId"));
175 public void testVerifyResourceIds() throws Exception {
176 // no resourceIds list
178 List<String> resourceIds = null;
179 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
180 this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
181 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
182 assertTrue(((String) response.getEntity()).contains("resourceIds"));
185 // empty resourceId list
187 List<String> resourceIds = new ArrayList<>();
188 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
189 this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
190 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
191 assertTrue(((String) response.getEntity()).contains("resourceIds"));
196 public void testVerifyResourceType() throws Exception {
198 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
199 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
200 this.requestId, null, resourceIds);
201 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
202 assertTrue(((String) response.getEntity()).contains("resourceType"));
206 public void testVerifyInternalError() throws Exception {
208 List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
209 Response response = this.service.findbyResourceIdAndType(null, V1, AUTH, APP, this.transactionId,
210 this.requestId, null, resourceIds);
211 assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
215 public void testDiscoverVserver() throws Exception {
216 String vserverId = "2c311eae-f542-4173-8a01-582922abd495";
218 String resourcePath = MessageFormat.format("/v2.1/servers/{0}",
219 new Object[] { vserverId });
221 String identityPath = "/v3/auth/tokens";
223 Object sourceObject = JsonUtils.filepathToObject(TEST_RESOURCES + "vserver-input.json");
225 String openstackApiResponse = JsonUtils.toJsonString(sourceObject);
227 this.openstackRule.stubFor(get(resourcePath).willReturn(okJson(openstackApiResponse)));
229 this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
231 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
232 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
234 assertEquals(Status.OK.getStatusCode(), response.getStatus());
235 NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
237 assertEquals(requestId, notification.getRequestId());
238 assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
239 assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
241 assertEquals(1, notification.getResources().size());
242 Resource vserver = notification.getResources().get(0);
243 assertEquals(vserverId, vserver.getId());
244 assertEquals("vserver", vserver.getType());
245 assertEquals(DataQuality.Status.ok, vserver.getDataQuality().getStatus());
247 verifyAttribute(vserver.getAttributeList(), "status", "ACTIVE");
248 verifyAttribute(vserver.getAttributeList(), "inMaintenance", "true");
249 verifyAttribute(vserver.getAttributeList(), "hostname", "norm-bouygues");
250 verifyAttribute(vserver.getAttributeList(), "vmState", "active");
254 public void testDiscoverVserverFailureNotFound() throws Exception {
255 String vserverId = UUID.randomUUID().toString();
257 String resourcePath = MessageFormat.format("/v2.1/servers/{0}",
258 new Object[] { vserverId });
260 String identityPath = "/v3/auth/tokens";
262 this.openstackRule.stubFor(get(resourcePath).willReturn(WireMock.notFound()));
264 this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
266 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
267 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
269 assertEquals(Status.OK.getStatusCode(), response.getStatus());
270 NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
271 assertEquals(requestId, notification.getRequestId());
272 assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
273 assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
275 assertEquals(1, notification.getResources().size());
276 Resource vserver = notification.getResources().get(0);
277 assertEquals(vserverId, vserver.getId());
278 assertEquals("vserver", vserver.getType());
279 assertEquals(DataQuality.Status.error, vserver.getDataQuality().getStatus());
280 assertNull(vserver.getAttributeList());
284 * Verify API returns a final response indicating no discovery possible.
287 public void testUnsupportedResourceType() throws Exception {
289 String resourceType = "unsupported";
290 List<String> resourceIds = Arrays.asList("dummyId");
291 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
292 this.requestId, resourceType, resourceIds);
293 assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
297 public void testLoginFailure() throws Exception {
298 String vserverId = UUID.randomUUID().toString();
300 String identityPath = "/v3/auth/tokens";
302 this.identityRule.stubFor(post(identityPath).willReturn(WireMock.unauthorized()));
304 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
305 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
307 assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
311 public void testLoginFailureMissingToken() throws Exception {
312 String vserverId = UUID.randomUUID().toString();
313 String identityPath = "/v3/auth/tokens";
315 this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}")));
317 Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
318 RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
320 assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
323 private void verifyAttribute(List<Attribute> attributeList, String attrName, String attrValue) {
324 for (Attribute attr : attributeList) {
325 if (attr.getName().equals(attrName)) {
326 assertEquals("Unexpected value for attribute " + attrName, attrValue, attr.getValue());
330 fail("Attribute " + attrName + " not found");