ba20a889745ec3f553a9e077884df2b5cdd231b1
[sdnc/apps.git] /
1 /*
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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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=====================================================
17  */
18
19 package org.onap.sdnc.apps.pomba.servicedecomposition.test;
20
21 import static com.github.tomakehurst.wiremock.client.WireMock.get;
22 import static com.github.tomakehurst.wiremock.client.WireMock.notFound;
23 import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
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;
29
30 import com.github.tomakehurst.wiremock.junit.WireMockRule;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.util.Base64;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.ws.rs.core.HttpHeaders;
37 import javax.ws.rs.core.Response;
38 import javax.ws.rs.core.Response.Status;
39 import org.json.JSONArray;
40 import org.json.JSONObject;
41 import org.junit.Rule;
42 import org.junit.Test;
43 import org.junit.runner.RunWith;
44 import org.onap.logging.ref.slf4j.ONAPLogConstants;
45 import org.onap.sdnc.apps.pomba.servicedecomposition.service.rs.RestService;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
48 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
49 import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
50 import org.springframework.boot.test.context.SpringBootTest;
51 import org.springframework.test.context.TestPropertySource;
52 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
53 import org.springframework.test.context.web.WebAppConfiguration;
54
55 @RunWith(SpringJUnit4ClassRunner.class)
56 @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
57 @WebAppConfiguration
58 @SpringBootTest
59 @TestPropertySource(properties = {
60         "aai.httpProtocol=http",
61         "aai.host=localhost",
62         "aai.port=8081",
63         "basicAuth.username=admin",
64         "basicAuth.password=admin"
65     })
66 public class ServiceDecompositionTest {
67
68     private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString("admin:admin".getBytes());
69
70     // TODO missing code coverage for VNFC resources
71
72     @Rule
73     public WireMockRule aai = new WireMockRule(wireMockConfig().port(8081));
74
75     @Autowired
76     private RestService service;
77
78     /**
79      * Simulation of the firewall demo service, using json captured from real A&AI queries.
80      * The resource relationship looks something like.
81      * <pre>
82      * service instance
83      * +- generic-vnf 1
84      * |  +- vserver
85      * +- generic-vnf 2
86      *    +- network 1
87      *    +- network 2
88      * </pre>
89      */
90     @Test
91     public void testDemoFirewallService() throws Exception {
92         // setup A&AI responses
93         addResponse(
94                 "/aai/v13/nodes/service-instance/c6456519-6acf-4adb-997c-3c363dd4caaf",
95                 "junit/aai-service-instance.json");
96         addResponse(
97                 "/aai/v13/network/generic-vnfs/generic-vnf/6700c313-fbb7-4cf9-ac70-0293ec56df68?depth=2",
98                 "junit/aai-generic-vnf1.json");
99         addResponse(
100                 "/aai/v13/network/generic-vnfs/generic-vnf/8a9ddb25-2e79-449c-a40d-5011bac0da39?depth=2",
101                 "junit/aai-generic-vnf2.json");
102         addResponse(
103                 "/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/CloudOwner/RegionOne/tenants/tenant"
104                         + "/b49b830686654191bb1e952a74b014ad/vservers/vserver/b494cd6e-b9f3-45e0-afe7-e1d1a5f5d74a",
105                 "junit/aai-vserver.json");
106         addResponse(
107                 "/aai/v13/network/l3-networks/l3-network/HNP1d77c-1094-41ec-b7f3-94bb30951870",
108                 "junit/aai-l3-network1.json");
109         addResponse(
110                 "/aai/v13/network/l3-networks/l3-network/HNP1d77c-1094-41ec-b7f3-94bb30951872",
111                 "junit/aai-l3-network2.json");
112
113         final String serviceInstanceId = "c6456519-6acf-4adb-997c-3c363dd4caaf";
114         final String vnfId1 = "6700c313-fbb7-4cf9-ac70-0293ec56df68";
115         final String vnfId2 = "8a9ddb25-2e79-449c-a40d-5011bac0da39";
116         final String vserverId = "b494cd6e-b9f3-45e0-afe7-e1d1a5f5d74a";
117         final String networkId1 = "HNP1d77c-1094-41ec-b7f3-94bb30951870";
118         final String networkId2 = "HNP1d77c-1094-41ec-b7f3-94bb30951872";
119
120         HttpServletRequest httpRequest = new TestHttpServletRequest();
121         Response response = this.service.getContext(httpRequest, AUTH, "network-discovery-context-builder", null,
122                 serviceInstanceId);
123         assertEquals(200, response.getStatus());
124
125         JSONObject serviceInstance = new JSONObject((String)response.getEntity());
126
127         // verify two generic-vnfs added to service instance data
128         verifyResource(serviceInstance, "generic-vnfs", "vnf-id", vnfId1);
129         verifyResource(serviceInstance, "generic-vnfs", "vnf-id", vnfId2);
130
131         JSONArray vnfs = serviceInstance.getJSONArray("generic-vnfs");
132         for (int i = 0; i < vnfs.length(); i++) {
133             JSONObject vnf = vnfs.getJSONObject(i);
134             String vnfId = vnf.getString("vnf-id");
135             switch (vnfId) {
136                 case vnfId1:
137                     // verify vserver resource
138                     verifyResource(vnf, "vservers", "vserver-id", vserverId);
139                     break;
140                 case vnfId2:
141                     // verify network resources
142                     verifyResource(vnf, "l3-networks", "network-id", networkId1);
143                     verifyResource(vnf, "l3-networks", "network-id", networkId2);
144                     break;
145                 default:
146                     fail("Unexpected generic-vnf " + vnfId);
147             }
148         }
149     }
150
151     @Test
152     public void testNoAuthHeader() throws Exception {
153         String fromAppId = "junit";
154         String transactionId = null;
155         String serviceInstanceId = "aServiceInstanceId";
156         // no Authorization header
157         Response response = this.service.getContext(new TestHttpServletRequest(), null, fromAppId, transactionId,
158                 serviceInstanceId);
159         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
160         // should get WWW-Authenticate header in response
161         assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
162     }
163
164     @Test
165     public void testUnauthorized() throws Exception {
166         // bad credentials
167         String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
168         String fromAppId = "junit";
169         String transactionId = null;
170         String serviceInstanceId = "aServiceInstanceId";
171
172         Response response = this.service.getContext(new TestHttpServletRequest(), authorization, fromAppId,
173                 transactionId, serviceInstanceId);
174         assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
175         // should not get WWW-Authenticate header in response
176         assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
177     }
178
179     /** Fail if calling app name is missing. */
180     @Test
181     public void verifyFromAppId() throws Exception {
182         String fromAppId = null;
183         String transactionId = null;
184         String serviceInstanceId = "someValue";
185
186         Response response = this.service.getContext(new TestHttpServletRequest(), AUTH, fromAppId, transactionId,
187                 serviceInstanceId);
188         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
189         assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
190     }
191
192     /** Fail if service instance id is missing. */
193     @Test
194     public void verifyServiceInstanceId() throws Exception {
195         String fromAppId = "junit";
196         String transactionId = null;
197         String serviceInstanceId = null;
198
199         Response response = this.service.getContext(new TestHttpServletRequest(), AUTH, fromAppId, transactionId,
200                 serviceInstanceId);
201         assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
202         assertTrue(((String)response.getEntity()).contains("service-instance-id"));
203     }
204
205     /** Unknown service-instance-id return HTTP 404. */
206     @Test
207     public void testInvalidServiceId() throws Exception {
208         aai.stubFor(get("/aai/v13/nodes/service-instance/noSuchServiceId").willReturn(notFound()));
209
210         Response response =
211                 this.service.getContext(new TestHttpServletRequest(), AUTH, "junit", null, "noSuchServiceId");
212
213         assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
214     }
215
216     private void verifyResource(JSONObject parent, String arrayName, String field, String value) {
217         JSONArray array = parent.getJSONArray(arrayName);
218         for (int i = 0; i < array.length(); i++) {
219             JSONObject item = array.getJSONObject(i);
220             if (value.equals(item.getString(field))) {
221                 return;
222             }
223         }
224         fail("Did not find " + field + "=" + value + " in " + arrayName + " array");
225     }
226
227
228     private void addResponse(String path, String classpathResource) throws IOException {
229         String payload = readFully(ClassLoader.getSystemResourceAsStream(classpathResource));
230         aai.stubFor(get(path).willReturn(okJson(payload)));
231     }
232
233
234     private String readFully(InputStream in) throws IOException {
235         char[] cbuf = new char[1024];
236         StringBuilder content = new StringBuilder();
237         try (InputStreamReader reader = new InputStreamReader(in, "UTF-8")) {
238             int count;
239             while ((count = reader.read(cbuf)) >= 0) {
240                 content.append(cbuf, 0, count);
241             }
242         }
243         return content.toString();
244     }
245 }