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