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