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