Added oparent to sdc main
[sdc.git] / common-app-api / src / test / java / org / openecomp / sdc / common / log / wrappers / LoggerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019 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
21 package org.openecomp.sdc.common.log.wrappers;
22
23 import org.junit.Before;
24 import org.junit.Test;
25 import org.junit.runner.RunWith;
26 import org.mockito.ArgumentCaptor;
27 import org.mockito.Captor;
28 import org.mockito.InjectMocks;
29 import org.mockito.Mock;
30 import org.mockito.junit.MockitoJUnitRunner;
31 import org.openecomp.sdc.common.log.api.ILogConfiguration;
32 import org.openecomp.sdc.common.log.elements.LoggerError;
33 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
34 import org.openecomp.sdc.common.log.enums.LogLevel;
35 import org.openecomp.sdc.common.log.enums.Severity;
36 import org.openecomp.sdc.common.util.ThreadLocalsHolder;
37 import org.slf4j.MDC;
38 import org.slf4j.Marker;
39
40 import javax.ws.rs.container.ContainerRequestContext;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43 import java.net.URI;
44 import java.net.URISyntaxException;
45
46 import static org.junit.Assert.assertEquals;
47 import static org.junit.Assert.assertNull;
48 import static org.mockito.ArgumentMatchers.any;
49 import static org.mockito.ArgumentMatchers.anyString;
50 import static org.mockito.ArgumentMatchers.contains;
51 import static org.mockito.ArgumentMatchers.eq;
52 import static org.mockito.Mockito.*;
53 import static org.openecomp.sdc.common.log.api.ILogConfiguration.*;
54
55 @RunWith(MockitoJUnitRunner.class)
56 public class LoggerTest {
57
58     private final static String targetEntity = "DCEA";
59     private final static String serviceName = "testService";
60     private final static String message = "Logger message";
61     private final static String exceptionMsg= "Exception testing";
62     private final static String missingFieldsMessageFragment = "mandatory parameters for ECOMP logging";
63
64     @Mock
65     private org.slf4j.Logger logger;
66     @Mock
67     private ContainerRequestContext requestContext;
68     @Mock
69     private UriInfo uriInfo;
70     @Mock
71     private Response.StatusType statusType;
72
73     @InjectMocks
74     private Logger commonLogger;
75
76     @Captor
77     private ArgumentCaptor<String> captor;
78
79     @Before
80     public void setUp() {
81         MDC.clear();
82     }
83
84     @Test
85     public void validateErrorLogWhenErrorSettingsProvided() {
86         when(logger.isErrorEnabled()).thenReturn(true);
87         commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message);
88
89         verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class));
90         assertEquals(message, captor.getValue());
91         assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE));
92         assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY));
93         assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY));
94         assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
95     }
96
97     @Test
98     public void validateWarnMessageIsLoggedWhenAllErrorSettingsProvided() {
99         when(logger.isErrorEnabled()).thenReturn(true);
100         commonLogger.error(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, serviceName, targetEntity, message);
101
102         verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class));
103         assertEquals(message, captor.getValue());
104         assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE));
105         assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY));
106         assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY));
107         assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
108     }
109
110     @Test
111     public void validateFatalMessageIsLoggedWhenAllErrorSettingsProvided() {
112         when(logger.isErrorEnabled()).thenReturn(true);
113         commonLogger.fatal(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message);
114
115         verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class));
116         assertEquals(message, captor.getValue());
117         assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE));
118         assertEquals(LogLevel.FATAL.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY));
119         assertEquals(targetEntity, MDC.get(ILogConfiguration.MDC_TARGET_ENTITY));
120         assertEquals(serviceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
121     }
122
123     @Test
124     public void validateErrorMessageIsNotLoggedWhenErrorLevelIsDisabledEvenIfErrorSettingsProvided() {
125         commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message);
126         verify(logger, never()).error(any(Marker.class), any(String.class));
127     }
128
129     @Test
130     public void validateErrorLogWhenErrorSettingsProvidedPartially() {
131         when(logger.isErrorEnabled()).thenReturn(true);
132         commonLogger.error(message);
133
134         verify(logger).error(any(Marker.class), eq(message), any(Object[].class));
135         assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE));
136         assertEquals(LogLevel.ERROR.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY));
137         assertNull(MDC.get(ILogConfiguration.MDC_TARGET_ENTITY));
138         assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
139     }
140
141     @Test
142     public void errorMessageIsNotLoggedWhenErrorLevelIsDisabled() {
143         commonLogger.error(message);
144         verify(logger, times(0)).error(any(Marker.class), anyString());
145     }
146
147     @Test
148     public void traceMessageWithExceptionIsNotLoggedWhenTraceLevelIsDisabled() {
149         commonLogger.trace(message, new UnsupportedOperationException());
150         verify(logger, times(0)).trace(any(Marker.class), anyString());
151     }
152
153     @Test
154     public void verifyInfoMessage() {
155         when(logger.isInfoEnabled()).thenReturn(true);
156         commonLogger.info("Text");
157         assertEquals(LogLevel.INFO.name(), MDC.get(MDC_ERROR_CATEGORY));
158         assertEquals(String.valueOf(EcompLoggerErrorCode.SUCCESS.getErrorCode()), MDC.get(MDC_ERROR_CODE));
159         assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
160     }
161
162     @Test
163     public void verifyWarnMessage() {
164         when(logger.isWarnEnabled()).thenReturn(true);
165         commonLogger.warn("Text");
166         assertEquals(LogLevel.WARN.name(), MDC.get(MDC_ERROR_CATEGORY));
167         assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE));
168         assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
169     }
170
171     @Test
172     public void validateErrorLogWithExceptionWhenErrorSettingsProvidedPartially() {
173         ThreadLocalsHolder.setUuid("uuid");
174         final String logFieldsNotProvidedMsg = "mandatory parameters for ECOMP logging, missing fields: ServiceName PartnerName";
175         when(logger.isWarnEnabled()).thenReturn(true);
176         commonLogger.warn(message, new NullPointerException(exceptionMsg));
177
178         //the expected warn message
179         verify(logger).warn(any(Marker.class), contains(message), any(Object[].class));
180         assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(ILogConfiguration.MDC_ERROR_CODE));
181         assertEquals(LogLevel.WARN.name(), MDC.get(ILogConfiguration.MDC_ERROR_CATEGORY));
182         assertEquals("uuid", MDC.get(ILogConfiguration.MDC_KEY_REQUEST_ID));
183         assertNull(MDC.get(ILogConfiguration.MDC_TARGET_ENTITY));
184         assertEquals(LoggerError.defaultServiceName, MDC.get(ILogConfiguration.MDC_SERVICE_NAME));
185     }
186
187
188     @Test
189     public void validateDebugLogWithException() {
190         final String msg = "Debug message";
191         ThreadLocalsHolder.setUuid("uuid");
192         when(logger.isDebugEnabled()).thenReturn(true);
193         commonLogger.debug(msg, new RuntimeException());
194
195         verify(logger).debug(any(Marker.class), eq(msg), any(RuntimeException.class));
196     }
197
198     @Test
199     public void validateTraceLogWithExceptionAndPartialParamsAndDebugLevelDisabled() {
200         final String msg = "Debug message";
201         when(logger.isTraceEnabled()).thenReturn(true);
202         commonLogger.trace(msg, new RuntimeException());
203
204         verify(logger).trace(any(Marker.class), eq(msg), any(RuntimeException.class));
205     }
206
207     @Test
208     public void warnMessageWithParameterIsNotLoggedIfWarnLevelIsDisabled() {
209         commonLogger.warn("msg", "param");
210         verify(logger, times(0)).warn(any(Marker.class),
211                                     anyString(), any(Object.class));
212     }
213
214     @Test
215     public void verifyMdcValuesAreStoredWhenAuditAndErrorLoggersAreInvokedSequentially() throws URISyntaxException {
216         final String uuid = "12345";
217         final String message = "message";
218         when(requestContext.getHeaderString(anyString())).thenReturn("ab2222");
219         when(requestContext.getUriInfo()).thenReturn(uriInfo);
220         when(logger.isErrorEnabled()).thenReturn(true);
221
222         URI uri = new URI("http:/abc.com/getId");
223         when(uriInfo.getRequestUri()).thenReturn(uri);
224         when(uriInfo.getBaseUri()).thenReturn(uri);
225         when(statusType.getStatusCode()).thenReturn(200);
226         when(statusType.getReasonPhrase()).thenReturn("OK");
227         LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass());
228         ThreadLocalsHolder.setUuid(uuid);
229         audit.startLog(requestContext);
230         audit.log("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, message);
231
232         commonLogger.error(message);
233         verify(logger).error(any(Marker.class), eq(message), any(Object[].class));
234         assertEquals(uuid, MDC.get(MDC_KEY_REQUEST_ID));
235         assertEquals("/", MDC.get(MDC_SERVICE_NAME));
236         assertEquals(LogLevel.ERROR.name(), MDC.get(MDC_ERROR_CATEGORY));
237         assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE));
238     }
239
240     @Test
241     public void verifyLoggerDoesNothingWhenTheLevelIsNotSet() {
242         if (commonLogger.isDebugEnabled()) {
243             commonLogger.debug("text");
244         }
245         verify(logger, times(0)).debug(any(Marker.class), anyString(), eq((Object[])null));
246     }
247
248     @Test
249     public void verifyLoggerTraceMethodIsCalledWhenTheLevelIsSet() {
250         ThreadLocalsHolder.setUuid("1234");
251         when(logger.isTraceEnabled()).thenReturn(true);
252         if (commonLogger.isTraceEnabled()) {
253             commonLogger.trace("text");
254         }
255         verify(logger, times(1)).trace(any(Marker.class), anyString(), eq((Object[])null));
256     }
257
258
259     @Test
260     public void verifyMdcValuesAreStoredWhenTraceLoggerIsInvokedAfterAuditStart() throws URISyntaxException {
261         final String uuid = "12345";
262         final String message = "message";
263         when(requestContext.getHeaderString(anyString())).thenReturn("ab2222");
264         when(requestContext.getUriInfo()).thenReturn(uriInfo);
265         when(logger.isTraceEnabled()).thenReturn(true);
266
267         URI uri = new URI("http:/abc.com/getId");
268         when(uriInfo.getRequestUri()).thenReturn(uri);
269         when(uriInfo.getBaseUri()).thenReturn(uri);
270         LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass());
271         ThreadLocalsHolder.setUuid(uuid);
272         audit.startLog(requestContext);
273
274         commonLogger.trace(message);
275         verify(logger).trace(any(Marker.class), captor.capture(), eq((Object[])null));
276         assertEquals(message, captor.getValue());
277         assertEquals(uuid, MDC.get(MDC_KEY_REQUEST_ID));
278     }
279
280
281 }