87390bc572350e90c2c0ca3302b1e5d050402da7
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / DRFeedsServletTest.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23 package org.onap.dmaap.datarouter.provisioning;
24
25 import static org.hamcrest.Matchers.notNullValue;
26 import static org.mockito.Mockito.anyInt;
27 import static org.mockito.Mockito.anyString;
28 import static org.mockito.Mockito.argThat;
29 import static org.mockito.Mockito.eq;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.verify;
32 import static org.mockito.Mockito.when;
33 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
34
35 import java.util.HashSet;
36 import java.util.Set;
37 import javax.servlet.ServletOutputStream;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40 import org.apache.commons.lang3.reflect.FieldUtils;
41 import org.jetbrains.annotations.NotNull;
42 import org.json.JSONArray;
43 import org.json.JSONObject;
44 import org.junit.Before;
45 import org.junit.Test;
46 import org.junit.runner.RunWith;
47 import org.mockito.Mock;
48 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
49 import org.onap.dmaap.datarouter.authz.Authorizer;
50 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
51 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
52 import org.powermock.api.mockito.PowerMockito;
53 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
54 import org.powermock.modules.junit4.PowerMockRunner;
55
56
57 @RunWith(PowerMockRunner.class)
58 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.provisioning.beans.Feed")
59 public class DRFeedsServletTest extends DrServletTestBase {
60
61     private static DRFeedsServlet drfeedsServlet;
62
63     @Mock
64     private HttpServletRequest request;
65     @Mock
66     private HttpServletResponse response;
67
68     @Before
69     public void setUp() throws Exception {
70         super.setUp();
71         drfeedsServlet = new DRFeedsServlet();
72         setAuthoriserToReturnRequestIsAuthorized();
73         setPokerToNotCreateTimersWhenDeleteFeedIsCalled();
74         setupValidAuthorisedRequest();
75         setUpValidSecurityOnHttpRequest();
76         setUpValidContentHeadersAndJSONOnHttpRequest();
77     }
78
79     @Test
80     public void Given_Request_Is_HTTP_DELETE_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
81         drfeedsServlet.doDelete(request, response);
82         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
83     }
84
85     @Test
86     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
87         throws Exception {
88         when(request.isSecure()).thenReturn(false);
89         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
90         drfeedsServlet.doGet(request, response);
91         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
92     }
93
94     @Test
95     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
96         throws Exception {
97         setBehalfHeader(null);
98         drfeedsServlet.doGet(request, response);
99         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
100     }
101
102
103     @Test
104     public void Given_Request_Is_HTTP_GET_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
105         throws Exception {
106         when(request.getRequestURI()).thenReturn("/123");
107         drfeedsServlet.doGet(request, response);
108         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
109     }
110
111
112     @Test
113     public void Given_Request_Is_HTTP_GET_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
114         throws Exception {
115         setAuthoriserToReturnRequestNotAuthorized();
116         drfeedsServlet.doGet(request, response);
117         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
118     }
119
120     @Test
121     public void Given_Request_Is_HTTP_GET_And_Request_Fails_With_Valid_Name_And_Version() throws Exception {
122         when(request.getParameter("name")).thenReturn("stub_name");
123         when(request.getParameter("version")).thenReturn("stub_version");
124         drfeedsServlet.doGet(request, response);
125         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
126     }
127
128     @Test
129     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds_With_Valid_Name_And_Version() throws Exception {
130         ServletOutputStream outStream = mock(ServletOutputStream.class);
131         when(response.getOutputStream()).thenReturn(outStream);
132         when(request.getParameter("name")).thenReturn("stub_name");
133         when(request.getParameter("version")).thenReturn("stub_version");
134         PowerMockito.mockStatic(Feed.class);
135         Feed feed = mock(Feed.class);
136         PowerMockito.when(Feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(feed);
137         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
138         drfeedsServlet.doGet(request, response);
139         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
140     }
141
142
143     @Test
144     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds_With_Invalid_Name_And_Version() throws Exception {
145         ServletOutputStream outStream = mock(ServletOutputStream.class);
146         when(response.getOutputStream()).thenReturn(outStream);
147         drfeedsServlet.doGet(request, response);
148         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
149     }
150
151
152     @Test
153     public void Given_Request_Is_HTTP_PUT_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
154         drfeedsServlet.doPut(request, response);
155         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
156     }
157
158
159     @Test
160     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
161         throws Exception {
162         when(request.isSecure()).thenReturn(false);
163         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
164         drfeedsServlet.doPost(request, response);
165         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
166     }
167
168     @Test
169     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated()
170         throws Exception {
171         setBehalfHeader(null);
172         drfeedsServlet.doPost(request, response);
173         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
174     }
175
176
177     @Test
178     public void Given_Request_Is_HTTP_POST_And_URL_Path_Not_Valid_Then_Bad_Request_Response_Is_Generated()
179         throws Exception {
180         when(request.getRequestURI()).thenReturn("/123");
181         drfeedsServlet.doPost(request, response);
182         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
183     }
184
185
186     @Test
187     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
188         throws Exception {
189         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.feed; version=1.1");
190         when(request.getContentType()).thenReturn("stub_contentType");
191         drfeedsServlet.doPost(request, response);
192         verify(response)
193             .sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
194     }
195
196     @Test
197     public void Given_Request_Is_HTTP_POST_And_Request_Is_Not_Authorized_Then_Forbidden_Response_Is_Generated()
198         throws Exception {
199         setAuthoriserToReturnRequestNotAuthorized();
200         drfeedsServlet.doPost(request, response);
201         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
202     }
203
204     @Test
205     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated()
206         throws Exception {
207         drfeedsServlet.doPost(request, response);
208         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
209     }
210
211     @Test
212     public void Given_Request_Is_HTTP_POST_And_Active_Feeds_Equals_Max_Feeds_Then_Bad_Request_Response_Is_Generated()
213         throws Exception {
214         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 0, true);
215         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
216             protected JSONObject getJSONfromInput(HttpServletRequest req) {
217                 return new JSONObject();
218             }
219         };
220         drfeedsServlet.doPost(request, response);
221         verify(response).sendError(eq(HttpServletResponse.SC_CONFLICT), argThat(notNullValue(String.class)));
222     }
223
224     @Test
225     public void Given_Request_Is_HTTP_POST_And_Feed_Is_Not_Valid_Object_Bad_Request_Response_Is_Generated()
226         throws Exception {
227         when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn(null);
228         JSONObject JSObject = buildRequestJsonObject();
229
230         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
231             protected JSONObject getJSONfromInput(HttpServletRequest req) {
232                 JSONObject jo = new JSONObject();
233                 return jo;
234             }
235         };
236
237         drfeedsServlet.doPost(request, response);
238         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
239     }
240
241     @Test
242     public void Given_Request_Is_HTTP_POST_And_Feed_Already_Exists_Bad_Request_Response_Is_Generated()
243         throws Exception {
244         setFeedToReturnInvalidFeedIdSupplied();
245         JSONObject JSObject = buildRequestJsonObject();
246         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
247             protected JSONObject getJSONfromInput(HttpServletRequest req) {
248                 JSONObject jo = new JSONObject();
249                 jo.put("name", "not_stub_name");
250                 jo.put("version", "1.0");
251                 jo.put("authorization", JSObject);
252                 return jo;
253             }
254         };
255         drfeedsServlet.doPost(request, response);
256         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
257     }
258
259     @Test
260     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Bad_Request_Response_Is_Generated() throws Exception {
261         JSONObject JSObject = buildRequestJsonObject();
262         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
263             protected JSONObject getJSONfromInput(HttpServletRequest req) {
264                 JSONObject jo = new JSONObject();
265                 jo.put("name", "stub_name");
266                 jo.put("version", "2.0");
267                 jo.put("authorization", JSObject);
268                 return jo;
269             }
270
271             @Override
272             protected boolean doInsert(Insertable bean) {
273                 return false;
274             }
275         };
276         drfeedsServlet.doPost(request, response);
277         verify(response)
278             .sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
279     }
280
281
282     @Test
283     public void Given_Request_Is_HTTP_POST_And_Change_On_Feeds_Succeeds_A_STATUS_OK_Response_Is_Generated()
284         throws Exception {
285         ServletOutputStream outStream = mock(ServletOutputStream.class);
286         when(response.getOutputStream()).thenReturn(outStream);
287         JSONObject JSObject = buildRequestJsonObject();
288         DRFeedsServlet drfeedsServlet = new DRFeedsServlet() {
289             protected JSONObject getJSONfromInput(HttpServletRequest req) {
290                 JSONObject jo = new JSONObject();
291                 jo.put("name", "stub_name");
292                 jo.put("version", "1.0");
293                 jo.put("authorization", JSObject);
294                 return jo;
295             }
296
297             @Override
298             protected boolean doInsert(Insertable bean) {
299                 return true;
300             }
301         };
302         drfeedsServlet.doPost(request, response);
303         verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
304     }
305
306     @NotNull
307     private JSONObject buildRequestJsonObject() {
308         JSONObject JSObject = new JSONObject();
309         JSONArray endpointIDs = new JSONArray();
310         JSONObject JOEndpointIDs = new JSONObject();
311         JOEndpointIDs.put("id", "stub_endpoint_id");
312         JOEndpointIDs.put("password", "stub_endpoint_password");
313         endpointIDs.put(JOEndpointIDs);
314
315         JSONArray endpointAddresses = new JSONArray();
316         endpointAddresses.put("127.0.0.1");
317
318         JSObject.put("classification", "stub_classification");
319         JSObject.put("endpoint_ids", endpointIDs);
320         JSObject.put("endpoint_addrs", endpointAddresses);
321         return JSObject;
322     }
323
324     private void setUpValidSecurityOnHttpRequest() throws Exception {
325         when(request.isSecure()).thenReturn(true);
326         Set<String> authAddressesAndNetworks = new HashSet<String>();
327         authAddressesAndNetworks.add(("127.0.0.1"));
328         FieldUtils
329             .writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks,
330                 true);
331         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
332         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "maxFeeds", 100, true);
333     }
334
335     private void setBehalfHeader(String headerValue) {
336         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
337     }
338
339     private void setValidPathInfoInHttpHeader() {
340         when(request.getPathInfo()).thenReturn("/123");
341     }
342
343     private void setFeedToReturnInvalidFeedIdSupplied() {
344         PowerMockito.mockStatic(Feed.class);
345         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(null);
346         when(Feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(mock(Feed.class));
347     }
348
349     private void setFeedToReturnValidFeedForSuppliedId() {
350         PowerMockito.mockStatic(Feed.class);
351         Feed feed = mock(Feed.class);
352         PowerMockito.when(Feed.getFeedById(anyInt())).thenReturn(feed);
353         when(feed.isDeleted()).thenReturn(false);
354         when(feed.asJSONObject(true)).thenReturn(mock(JSONObject.class));
355         when(feed.getPublisher()).thenReturn("Stub_Value");
356         when(feed.getName()).thenReturn("stub_name");
357         when(feed.getVersion()).thenReturn("1.0");
358         when(feed.asLimitedJSONObject()).thenReturn(mock(JSONObject.class));
359         PowerMockito.when(feed.getFeedByNameVersion(anyString(), anyString())).thenReturn(null);
360     }
361
362     private void setAuthoriserToReturnRequestNotAuthorized() throws IllegalAccessException {
363         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
364         Authorizer authorizer = mock(Authorizer.class);
365         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
366         when(authorizer.decide(request)).thenReturn(authResponse);
367         when(authResponse.isAuthorized()).thenReturn(false);
368     }
369
370     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
371         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
372         Authorizer authorizer = mock(Authorizer.class);
373         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
374         when(authorizer.decide(request)).thenReturn(authResponse);
375         when(authResponse.isAuthorized()).thenReturn(true);
376     }
377
378     private void setPokerToNotCreateTimersWhenDeleteFeedIsCalled() throws Exception {
379         Poker poker = mock(Poker.class);
380         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
381     }
382
383     private void setupValidAuthorisedRequest() throws Exception {
384         setUpValidSecurityOnHttpRequest();
385         setBehalfHeader("Stub_Value");
386         setValidPathInfoInHttpHeader();
387         setFeedToReturnValidFeedForSuppliedId();
388     }
389
390     private void setUpValidContentHeadersAndJSONOnHttpRequest() {
391         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.feed; version=1.0");
392         when(request.getHeader("X-ATT-DR-ON-BEHALF-OF-GROUP")).thenReturn("stub_subjectGroup");
393
394     }
395 }