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