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