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