Merge "Fixed Sonar Blocker in StatisticsServlet"
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / GroupServletTest.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 org.apache.commons.lang3.reflect.FieldUtils;
26 import org.json.JSONObject;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 import org.mockito.Matchers;
31 import org.mockito.Mock;
32 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
33 import org.onap.dmaap.datarouter.authz.Authorizer;
34 import org.onap.dmaap.datarouter.provisioning.beans.Group;
35 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
36 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
37 import org.powermock.api.mockito.PowerMockito;
38 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
39 import org.powermock.modules.junit4.PowerMockRunner;
40
41 import javax.servlet.ServletInputStream;
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.Matchers.anyInt;
50 import static org.mockito.Matchers.argThat;
51 import static org.mockito.Matchers.eq;
52 import static org.mockito.Mockito.*;
53 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
54
55 @RunWith(PowerMockRunner.class)
56 @SuppressStaticInitializationFor("org.onap.dmaap.datarouter.provisioning.beans.Group")
57 public class GroupServletTest extends DrServletTestBase {
58
59     private GroupServlet groupServlet;
60
61     @Mock
62     private HttpServletRequest request;
63
64     @Mock
65     private HttpServletResponse response;
66
67     @Before
68     public void setUp() throws Exception {
69         super.setUp();
70         groupServlet = new GroupServlet();
71         setAuthoriserToReturnRequestIsAuthorized();
72         setPokerToNotCreateTimers();
73         setUpValidAuthorisedRequest();
74     }
75
76     @Test
77     public void Given_Request_Is_HTTP_GET_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
78         when(request.isSecure()).thenReturn(false);
79         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
80         groupServlet.doGet(request, response);
81         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
82     }
83
84     @Test
85     public void Given_Request_Is_HTTP_GET_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
86         setBehalfHeader(null);
87         groupServlet.doGet(request, response);
88         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
89     }
90
91     @Test
92     public void Given_Request_Is_HTTP_GET_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
93         when(request.getPathInfo()).thenReturn(null);
94         groupServlet.doGet(request, response);
95         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
96     }
97
98     @Test
99     public void Given_Request_Is_HTTP_GET_And_Request_Succeeds() throws Exception {
100         ServletOutputStream outStream = mock(ServletOutputStream.class);
101         when(response.getOutputStream()).thenReturn(outStream);
102         groupServlet.doGet(request, response);
103         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
104     }
105
106     @Test
107     public void Given_Request_Is_HTTP_PUT_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
108         when(request.isSecure()).thenReturn(false);
109         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
110         groupServlet.doPut(request, response);
111         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
112     }
113
114     @Test
115     public void Given_Request_Is_HTTP_PUT_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
116         setBehalfHeader(null);
117         groupServlet.doPut(request, response);
118         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
119     }
120
121     @Test
122     public void Given_Request_Is_HTTP_PUT_And_Path_Header_Is_Not_Set_In_Request_With_Valid_Path_Then_Bad_Request_Response_Is_Generated() throws Exception {
123         when(request.getPathInfo()).thenReturn(null);
124         groupServlet.doPut(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_PUT_And_Group_Id_Is_Invalid_Then_Not_Found_Response_Is_Generated() throws Exception {
130         setGroupToReturnInvalidGroupIdSupplied();
131         groupServlet.doPut(request, response);
132         verify(response).sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
133     }
134
135     @Test
136     public void Given_Request_Is_HTTP_PUT_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
137         when(request.getContentType()).thenReturn("stub_contentType");
138         groupServlet.doPut(request, response);
139         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
140     }
141
142     @Test
143     public void Given_Request_Is_HTTP_PUT_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
144         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
145         ServletInputStream inStream = mock(ServletInputStream.class);
146         when(request.getInputStream()).thenReturn(inStream);
147         groupServlet.doPut(request, response);
148         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
149     }
150
151     @Test
152     public void Given_Request_Is_HTTP_PUT_And_Group_Name_Is_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
153         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
154         GroupServlet groupServlet = overideGetJSONFromInputToReturnAnInvalidGroup(true);
155         groupServlet.doPut(request, response);
156         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
157     }
158
159     @Test
160     public void Given_Request_Is_HTTP_PUT_And_Group_Name_Matches_Group_In_Db_Then_Bad_Request_Response_Is_Generated() throws Exception {
161         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
162         GroupServlet groupServlet = overideGetJSONFromInputToReturnAValidGroup();
163         setGroupToReturnNonNullValueForGetGroupMatching();
164         groupServlet.doPut(request, response);
165         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
166     }
167
168     @Test
169     public void Given_Request_Is_HTTP_PUT_And_PUT_Fails_Then_Internal_Server_Error_Response_Is_Generated() throws Exception {
170         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
171         GroupServlet groupServlet = overideGetJSONFromInputToReturnAValidGroupWithFail();
172         groupServlet.doPut(request, response);
173         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
174     }
175
176     @Test
177     public void Given_Request_Is_HTTP_PUT_And_Request_Succeeds() throws Exception {
178         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
179         GroupServlet groupServlet = overideGetJSONFromInputToReturnAValidGroup();
180         ServletOutputStream outStream = mock(ServletOutputStream.class);
181         when(response.getOutputStream()).thenReturn(outStream);
182         groupServlet.doPut(request, response);
183         verify(response).setStatus(eq(HttpServletResponse.SC_OK));
184     }
185
186     @Test
187     public void Given_Request_Is_HTTP_POST_And_Is_Not_Secure_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated() throws Exception {
188         when(request.isSecure()).thenReturn(false);
189         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "isAddressAuthEnabled", "true", true);
190         groupServlet.doPost(request, response);
191         verify(response).sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
192     }
193
194     @Test
195     public void Given_Request_Is_HTTP_POST_And_BEHALF_HEADER_Is_Not_Set_In_Request_Then_Bad_Request_Response_Is_Generated() throws Exception {
196         setBehalfHeader(null);
197         groupServlet.doPost(request, response);
198         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
199     }
200
201     @Test
202     public void Given_Request_Is_HTTP_POST_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated() throws Exception {
203         when(request.getContentType()).thenReturn("stub_contentType");
204         groupServlet.doPost(request, response);
205         verify(response).sendError(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE), argThat(notNullValue(String.class)));
206     }
207
208     @Test
209     public void Given_Request_Is_HTTP_POST_And_Request_Contains_Badly_Formed_JSON_Then_Bad_Request_Response_Is_Generated() throws Exception {
210         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
211         ServletInputStream inStream = mock(ServletInputStream.class);
212         when(request.getInputStream()).thenReturn(inStream);
213         groupServlet.doPost(request, response);
214         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
215     }
216
217     @Test
218     public void Given_Request_Is_HTTP_POST_And_Group_Description_Is_Too_Long_Then_Bad_Request_Response_Is_Generated() throws Exception {
219         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
220         GroupServlet groupServlet = overideGetJSONFromInputToReturnAnInvalidGroup(false);
221         groupServlet.doPost(request, response);
222         verify(response).sendError(eq(HttpServletResponse.SC_BAD_REQUEST), argThat(notNullValue(String.class)));
223     }
224
225     @Test
226     public void Given_Request_Is_HTTP_POST_And_POST_Fails_Then_Internal_Server_Error_Response_Is_Generated() throws Exception {
227         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
228         GroupServlet groupServlet = overideGetJSONFromInputToReturnAValidGroupWithFail();
229         groupServlet.doPost(request, response);
230         verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), argThat(notNullValue(String.class)));
231     }
232
233     @Test
234     public void Given_Request_Is_HTTP_POST_And_Request_Succeeds() throws Exception {
235         when(request.getHeader("Content-Type")).thenReturn("application/vnd.att-dr.group; version=1.0");
236         GroupServlet groupServlet = overideGetJSONFromInputToReturnAValidGroup();
237         ServletOutputStream outStream = mock(ServletOutputStream.class);
238         when(response.getOutputStream()).thenReturn(outStream);
239         groupServlet.doPost(request, response);
240         verify(response).setStatus(eq(HttpServletResponse.SC_CREATED));
241     }
242
243     @Test
244     public void Given_Request_Is_HTTP_DELETE_SC_METHOD_NOT_ALLOWED_Response_Is_Generated() throws Exception {
245         groupServlet.doDelete(request, response);
246         verify(response).sendError(eq(HttpServletResponse.SC_METHOD_NOT_ALLOWED), argThat(notNullValue(String.class)));
247     }
248
249     private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
250         AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
251         Authorizer authorizer = mock(Authorizer.class);
252         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
253         when(authorizer.decide(request)).thenReturn(authResponse);
254         when(authResponse.isAuthorized()).thenReturn(true);
255     }
256
257     private void setPokerToNotCreateTimers() throws Exception {
258         Poker poker = mock(Poker.class);
259         FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
260     }
261
262     private void setUpValidAuthorisedRequest() throws Exception {
263         setUpValidSecurityOnHttpRequest();
264         setBehalfHeader("Stub_Value");
265         setValidPathInfoInHttpHeader();
266         setGroupToReturnValidGroupIdSupplied();
267     }
268
269     private void setUpValidSecurityOnHttpRequest() throws Exception {
270         when(request.isSecure()).thenReturn(true);
271         Set<String> authAddressesAndNetworks = new HashSet<String>();
272         authAddressesAndNetworks.add(("127.0.0.1"));
273         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authorizedAddressesAndNetworks", authAddressesAndNetworks, true);
274         FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
275     }
276
277     private void setBehalfHeader(String headerValue) {
278         when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
279     }
280
281     private void setValidPathInfoInHttpHeader() {
282         when(request.getPathInfo()).thenReturn("/123");
283     }
284
285     private void setGroupToReturnValidGroupIdSupplied() {
286         PowerMockito.mockStatic(Group.class);
287         Group group = mock(Group.class);
288         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
289         when(group.asJSONObject()).thenReturn(mock(JSONObject.class));
290     }
291
292     private void setGroupToReturnInvalidGroupIdSupplied() {
293         PowerMockito.mockStatic(Group.class);
294         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(null);
295     }
296
297     private GroupServlet overideGetJSONFromInputToReturnAnInvalidGroup(Boolean invalidName) {
298         GroupServlet groupServlet = new GroupServlet() {
299             protected JSONObject getJSONfromInput(HttpServletRequest req) {
300                 JSONObject invalidGroup = new JSONObject();
301                 String invalidEntry = "groupNameThatIsTooLongTooBeValidgroupNameThatIsTooLongTooBeValid";
302                 invalidEntry = invalidEntry + invalidEntry + invalidEntry + invalidEntry + invalidEntry;
303                 if (invalidName) {
304                     invalidGroup.put("name", invalidEntry);
305                     invalidGroup.put("description", "description");
306                 } else {
307                     invalidGroup.put("name", "groupName");
308                     invalidGroup.put("description", invalidEntry);
309                 }
310                 invalidGroup.put("groupid", 2);
311                 invalidGroup.put("authid", "User1");
312                 invalidGroup.put("classification", "class");
313                 invalidGroup.put("members", "stub_members");
314                 return invalidGroup;
315             }
316         };
317         return groupServlet;
318     }
319
320     private GroupServlet overideGetJSONFromInputToReturnAValidGroupWithFail() {
321         GroupServlet groupServlet = new GroupServlet() {
322             protected JSONObject getJSONfromInput(HttpServletRequest req) {
323                 JSONObject validGroup = new JSONObject();
324                 validGroup.put("name", "groupName");
325                 validGroup.put("groupid", 2);
326                 validGroup.put("description", "Group Description");
327                 validGroup.put("authid", "User1");
328                 validGroup.put("classification", "class");
329                 validGroup.put("members", "stub_members");
330                 return validGroup;
331             }
332
333             protected boolean doUpdate(Updateable bean) {
334                 return false;
335             }
336
337             protected boolean doInsert(Insertable bean) {
338                 return false;
339             }
340         };
341         return groupServlet;
342     }
343
344     private GroupServlet overideGetJSONFromInputToReturnAValidGroup() {
345         GroupServlet groupServlet = new GroupServlet() {
346             protected JSONObject getJSONfromInput(HttpServletRequest req) {
347                 JSONObject validGroup = new JSONObject();
348                 validGroup.put("name", "groupName");
349                 validGroup.put("groupid", 2);
350                 validGroup.put("description", "Group Description");
351                 validGroup.put("authid", "User1");
352                 validGroup.put("classification", "class");
353                 validGroup.put("members", "stub_members");
354                 return validGroup;
355             }
356
357             protected boolean doUpdate(Updateable bean) {
358                 return true;
359             }
360
361             protected boolean doInsert(Insertable bean) {
362                 return true;
363             }
364         };
365         return groupServlet;
366     }
367
368     private void setGroupToReturnNonNullValueForGetGroupMatching() {
369         PowerMockito.mockStatic(Group.class);
370         Group group = mock(Group.class);
371         PowerMockito.when(Group.getGroupById(anyInt())).thenReturn(group);
372         PowerMockito.when(Group.getGroupMatching(Matchers.any(Group.class), anyInt())).thenReturn(group);
373     }
374 }