Merge "Test case fixes"
[dmaap/datarouter.git] / datarouter-prov / src / test / java / org / onap / dmaap / datarouter / provisioning / InternalServletTest.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.hamcrest.Matchers.notNullValue;
26 import static org.mockito.Matchers.anyString;
27 import static org.mockito.Matchers.argThat;
28 import static org.mockito.Matchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.verify;
31 import static org.mockito.Mockito.when;
32 import static org.onap.dmaap.datarouter.provisioning.BaseServlet.BEHALF_HEADER;
33
34 import java.net.InetAddress;
35 import java.util.HashMap;
36 import java.util.Map;
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.junit.Before;
43 import org.junit.Test;
44 import org.junit.runner.RunWith;
45 import org.mockito.Mock;
46 import org.onap.dmaap.datarouter.authz.AuthorizationResponse;
47 import org.onap.dmaap.datarouter.authz.Authorizer;
48 import org.onap.dmaap.datarouter.provisioning.beans.Deleteable;
49 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
50 import org.onap.dmaap.datarouter.provisioning.beans.Insertable;
51 import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
52 import org.onap.dmaap.datarouter.provisioning.beans.NodeClass;
53 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
54 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
55 import org.onap.dmaap.datarouter.provisioning.beans.Updateable;
56 import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
57 import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
58 import org.powermock.api.mockito.PowerMockito;
59 import org.powermock.core.classloader.annotations.PrepareForTest;
60 import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
61 import org.powermock.modules.junit4.PowerMockRunner;
62
63 @RunWith(PowerMockRunner.class)
64 @PrepareForTest(LogRecord.class)
65 @SuppressStaticInitializationFor({"org.onap.dmaap.datarouter.provisioning.beans.Feed",
66     "org.onap.dmaap.datarouter.provisioning.beans.Parameters",
67     "org.onap.dmaap.datarouter.provisioning.beans.NodeClass",
68     "org.onap.dmaap.datarouter.provisioning.beans.Subscription",
69     "org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader"})
70 public class InternalServletTest extends DrServletTestBase {
71
72   private InternalServlet internalServlet;
73
74   @Mock
75   private HttpServletRequest request;
76
77   @Mock
78   private HttpServletResponse response;
79
80   @Before
81   public void setUp() throws Exception {
82     super.setUp();
83     internalServlet = new InternalServlet();
84     setAuthoriserToReturnRequestIsAuthorized();
85     setUpValidAuthorisedRequest();
86   }
87
88   @Test
89   public void Given_Request_Is_HTTP_GET_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
90       throws Exception {
91     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
92     internalServlet.doGet(request, response);
93     verify(response)
94         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
95   }
96
97   @Test
98   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_But_Not_Sent_From_Localhost_Then_Forbidden_Response_Is_Generated()
99       throws Exception {
100     when(request.getPathInfo()).thenReturn("/halt");
101     when(request.isSecure()).thenReturn(false);
102     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
103     internalServlet.doGet(request, response);
104     verify(response).setStatus(eq(HttpServletResponse.SC_FORBIDDEN));
105   }
106
107   @Test
108   public void Given_Request_Is_HTTP_GET_With_Halt_In_Endpoint_Request_Succeeds() throws Exception {
109     when(request.getPathInfo()).thenReturn("/halt");
110     when(request.isSecure()).thenReturn(false);
111     when(request.getRemoteAddr()).thenReturn("127.0.0.1");
112     internalServlet.doGet(request, response);
113     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
114   }
115
116   @Test
117   public void Given_Request_Is_HTTP_GET_With_FetchProv_In_Endpoint_Request_Succeeds()
118       throws Exception {
119     when(request.getPathInfo()).thenReturn("/fetchProv");
120     when(request.isSecure()).thenReturn(false);
121     internalServlet.doGet(request, response);
122     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
123   }
124
125   @Test
126   public void Given_Request_Is_HTTP_GET_With_Prov_In_Endpoint_Request_Succeeds() throws Exception {
127     when(request.getPathInfo()).thenReturn("/prov");
128     when(request.getQueryString()).thenReturn(null);
129     setPokerToNotCreateTimers();
130     ServletOutputStream outStream = mock(ServletOutputStream.class);
131     when(response.getOutputStream()).thenReturn(outStream);
132     internalServlet.doGet(request, response);
133     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
134   }
135
136   @Test
137   public void Given_Request_Is_HTTP_GET_With_Logs_In_Endpoint_Request_Succeeds() throws Exception {
138     when(request.getPathInfo()).thenReturn("/logs/");
139     ServletOutputStream outStream = mock(ServletOutputStream.class);
140     when(response.getOutputStream()).thenReturn(outStream);
141     internalServlet.doGet(request, response);
142     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
143   }
144
145   @Test
146   public void Given_Request_Is_HTTP_GET_Starts_With_Logs_In_Endpoint_Request_Succeeds()
147       throws Exception {
148     when(request.getPathInfo()).thenReturn("/logs/TestFile");
149     internalServlet.doGet(request, response);
150     verify(response)
151         .sendError(eq(HttpServletResponse.SC_NO_CONTENT), argThat(notNullValue(String.class)));
152   }
153
154   @Test
155   public void Given_Request_Is_HTTP_GET_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
156     when(request.getPathInfo()).thenReturn("/api/Key");
157     setParametersToNotContactDb(false);
158     ServletOutputStream outStream = mock(ServletOutputStream.class);
159     when(response.getOutputStream()).thenReturn(outStream);
160     internalServlet.doGet(request, response);
161     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
162   }
163
164   @Test
165   public void Given_Request_Is_HTTP_GET_With_Drlogs_In_Endpoint_Request_Succeeds()
166       throws Exception {
167     when(request.getPathInfo()).thenReturn("/drlogs/");
168     PowerMockito.mockStatic(LogfileLoader.class);
169     LogfileLoader logfileLoader = mock(LogfileLoader.class);
170     when(logfileLoader.getBitSet()).thenReturn(new RLEBitSet());
171     PowerMockito.when(LogfileLoader.getLoader()).thenReturn(logfileLoader);
172     ServletOutputStream outStream = mock(ServletOutputStream.class);
173     when(response.getOutputStream()).thenReturn(outStream);
174     internalServlet.doGet(request, response);
175     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
176   }
177
178   @Test
179   public void Given_Request_Is_HTTP_GET_Incorrect_Endpoint_Then_No_Content_Response_Is_Generated()
180       throws Exception {
181     when(request.getPathInfo()).thenReturn("/incorrect/");
182     internalServlet.doGet(request, response);
183     verify(response)
184         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
185   }
186
187   @Test
188   public void Given_Request_Is_HTTP_PUT_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
189       throws Exception {
190     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
191     internalServlet.doPut(request, response);
192     verify(response)
193         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
194   }
195
196   @Test
197   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
198     when(request.getPathInfo()).thenReturn("/api/Key");
199     setParametersToNotContactDb(false);
200     String[] values = {"V", "a", "l", "u", "e", "s"};
201     when(request.getParameterValues(anyString())).thenReturn(values);
202     internalServlet = internalServerSuccess();
203     setPokerToNotCreateTimers();
204     mockProvisioningParametersChanged();
205     internalServlet.doPut(request, response);
206     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
207   }
208
209   @Test
210   public void Given_Request_Is_HTTP_PUT_With_Api_In_Endpoint_And_Update_Fails_Then_Internal_Server_Error_Is_Generated()
211       throws Exception {
212     when(request.getPathInfo()).thenReturn("/api/Key");
213     setParametersToNotContactDb(false);
214     String[] values = {"V", "a", "l", "u", "e", "s"};
215     when(request.getParameterValues(anyString())).thenReturn(values);
216     internalServlet = internalServerFailure();
217     internalServlet.doPut(request, response);
218     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
219         argThat(notNullValue(String.class)));
220   }
221
222   @Test
223   public void Given_Request_Is_HTTP_PUT_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
224       throws Exception {
225     when(request.getPathInfo()).thenReturn("/incorrect");
226     internalServlet.doPut(request, response);
227     verify(response)
228         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
229   }
230
231   @Test
232   public void Given_Request_Is_HTTP_DELETE_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
233       throws Exception {
234     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
235     internalServlet.doDelete(request, response);
236     verify(response)
237         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
238   }
239
240   @Test
241   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_Request_Succeeds()
242       throws Exception {
243     when(request.getPathInfo()).thenReturn("/api/Key");
244     setParametersToNotContactDb(false);
245     String[] values = {"V", "a", "l", "u", "e", "s"};
246     when(request.getParameterValues(anyString())).thenReturn(values);
247     internalServlet = internalServerSuccess();
248     setPokerToNotCreateTimers();
249     mockProvisioningParametersChanged();
250     internalServlet.doDelete(request, response);
251     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
252   }
253
254   @Test
255   public void Given_Request_Is_HTTP_DELETE_With_Api_In_Endpoint_And_Delete_Fails_Then_Internal_Server_Error_Is_Generated()
256       throws Exception {
257     when(request.getPathInfo()).thenReturn("/api/Key");
258     setParametersToNotContactDb(false);
259     String[] values = {"V", "a", "l", "u", "e", "s"};
260     when(request.getParameterValues(anyString())).thenReturn(values);
261     internalServlet = internalServerFailure();
262     internalServlet.doDelete(request, response);
263     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
264         argThat(notNullValue(String.class)));
265   }
266
267   @Test
268   public void Given_Request_Is_HTTP_DELETE_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
269       throws Exception {
270     when(request.getPathInfo()).thenReturn("/incorrect");
271     internalServlet.doDelete(request, response);
272     verify(response)
273         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
274   }
275
276   @Test
277   public void Given_Request_Is_HTTP_POST_And_Address_Not_Authorized_When_HTTPS_Is_Required_Then_Forbidden_Response_Is_Generated()
278       throws Exception {
279     when(request.getRemoteAddr()).thenReturn("127.100.0.3");
280     internalServlet.doPost(request, response);
281     verify(response)
282         .sendError(eq(HttpServletResponse.SC_FORBIDDEN), argThat(notNullValue(String.class)));
283   }
284
285   @Test
286   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_Request_Succeeds() throws Exception {
287     when(request.getPathInfo()).thenReturn("/api/Key");
288     setParametersToNotContactDb(true);
289     String[] values = {"V", "a", "l", "u", "e", "s"};
290     when(request.getParameterValues(anyString())).thenReturn(values);
291     internalServlet = internalServerSuccess();
292     setPokerToNotCreateTimers();
293     mockProvisioningParametersChanged();
294     internalServlet.doPost(request, response);
295     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
296   }
297
298   @Test
299   public void Given_Request_Is_HTTP_POST_With_Api_In_Endpoint_And_Insert_Fails_Then_Internal_Server_Error_Is_Generated()
300       throws Exception {
301     when(request.getPathInfo()).thenReturn("/api/Key");
302     setParametersToNotContactDb(true);
303     String[] values = {"V", "a", "l", "u", "e", "s"};
304     when(request.getParameterValues(anyString())).thenReturn(values);
305     internalServlet = internalServerFailure();
306     internalServlet.doPost(request, response);
307     verify(response).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
308         argThat(notNullValue(String.class)));
309   }
310
311   @Test
312   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Header_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
313       throws Exception {
314     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
315     when(request.getPathInfo()).thenReturn("/logs/");
316     internalServlet.doPost(request, response);
317     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
318   }
319
320   @Test
321   public void Given_Request_Is_HTTP_POST_To_Logs_And_Content_Encoding_Is_Not_Supported_Type_Then_Unsupported_Media_Type_Response_Is_Generated()
322       throws Exception {
323     when(request.getHeader("Content-Encoding")).thenReturn("not-supported");
324     when(request.getPathInfo()).thenReturn("/logs/");
325     internalServlet.doPost(request, response);
326     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
327   }
328
329   @Test
330   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Then_Unsupported_Media_Type_Response_Is_Generated()
331       throws Exception {
332     when(request.getHeader("Content-Type")).thenReturn("stub_contentType");
333     when(request.getPathInfo()).thenReturn("/drlogs/");
334     internalServlet.doPost(request, response);
335     verify(response).setStatus(eq(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE));
336   }
337
338   @Test
339   public void Given_Request_Is_HTTP_POST_To_Drlogs_And_Request_Succeeds() throws Exception {
340     when(request.getPathInfo()).thenReturn("/drlogs/");
341     ServletInputStream inStream = mock(ServletInputStream.class);
342     when(inStream.read()).thenReturn(1, -1);
343     when(request.getInputStream()).thenReturn(inStream);
344     PowerMockito.mockStatic(LogRecord.class);
345     internalServlet.doPost(request, response);
346     verify(response).setStatus(eq(HttpServletResponse.SC_OK));
347   }
348
349   @Test
350   public void Given_Request_Is_HTTP_POST_With_Incorrect_Endpoint_Then_Not_Found_Error_Is_Generated()
351       throws Exception {
352     when(request.getPathInfo()).thenReturn("/incorrect/");
353     internalServlet.doPost(request, response);
354     verify(response)
355         .sendError(eq(HttpServletResponse.SC_NOT_FOUND), argThat(notNullValue(String.class)));
356   }
357
358   private void setAuthoriserToReturnRequestIsAuthorized() throws IllegalAccessException {
359     AuthorizationResponse authResponse = mock(AuthorizationResponse.class);
360     Authorizer authorizer = mock(Authorizer.class);
361     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "authz", authorizer, true);
362     when(authorizer.decide(request)).thenReturn(authResponse);
363     when(authResponse.isAuthorized()).thenReturn(true);
364   }
365
366   private void setUpValidAuthorisedRequest() throws Exception {
367     setUpValidSecurityOnHttpRequest();
368     setBehalfHeader("Stub_Value");
369     setValidPathInfoInHttpHeader();
370     when(request.getHeader("Content-Type")).thenReturn("text/plain");
371     when(request.getHeader("Content-Encoding")).thenReturn("gzip");
372   }
373
374   private void setUpValidSecurityOnHttpRequest() throws Exception {
375     when(request.isSecure()).thenReturn(true);
376     when(request.getRemoteAddr()).thenReturn(InetAddress.getLocalHost().getHostAddress());
377     InetAddress[] nodeAddresses = new InetAddress[1];
378     nodeAddresses[0] = InetAddress.getLocalHost();
379     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "nodeAddresses", nodeAddresses, true);
380     FieldUtils.writeDeclaredStaticField(BaseServlet.class, "requireCert", false, true);
381   }
382
383   private void setBehalfHeader(String headerValue) {
384     when(request.getHeader(BEHALF_HEADER)).thenReturn(headerValue);
385   }
386
387   private void setValidPathInfoInHttpHeader() {
388     when(request.getPathInfo()).thenReturn("/123");
389   }
390
391   private void setPokerToNotCreateTimers() throws Exception {
392     Poker poker = mock(Poker.class);
393     FieldUtils.writeDeclaredStaticField(Poker.class, "poker", poker, true);
394   }
395
396   private void setParametersToNotContactDb(boolean isPost) {
397     PowerMockito.mockStatic(Parameters.class);
398     Parameters parameters = mock(Parameters.class);
399     if (isPost) {
400       PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(null);
401     } else {
402       PowerMockito.when(Parameters.getParameter(anyString())).thenReturn(parameters);
403     }
404   }
405
406   private InternalServlet internalServerSuccess() {
407     InternalServlet internalServlet = new InternalServlet() {
408
409       protected boolean doUpdate(Updateable bean) {
410         return true;
411       }
412
413       protected boolean doDelete(Deleteable bean) {
414         return true;
415       }
416
417       protected boolean doInsert(Insertable bean) {
418         return true;
419       }
420     };
421     return internalServlet;
422   }
423
424   private InternalServlet internalServerFailure() {
425     InternalServlet internalServlet = new InternalServlet() {
426
427       protected boolean doUpdate(Updateable bean) {
428         return false;
429       }
430
431       protected boolean doDelete(Deleteable bean) {
432         return false;
433       }
434
435       protected boolean doInsert(Insertable bean) {
436         return false;
437       }
438     };
439     return internalServlet;
440   }
441
442   private void mockProvisioningParametersChanged() throws IllegalAccessException {
443     PowerMockito.mockStatic(Feed.class);
444     PowerMockito.mockStatic(Subscription.class);
445     PowerMockito.when(Feed.countActiveFeeds()).thenReturn(0);
446     PowerMockito.when(Subscription.countActiveSubscriptions()).thenReturn(0);
447     Map<String, Integer> map = new HashMap<>();
448     FieldUtils.writeDeclaredStaticField(NodeClass.class, "map", map, true);
449   }
450 }