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