Update aai-parent in babel to 1.13.3
[aai/babel.git] / src / test / java / org / onap / aai / babel / logging / TestApplicationLogger.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright (c) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright (c) 2017-2019 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.aai.babel.logging;
23
24 import static org.hamcrest.CoreMatchers.containsString;
25 import static org.hamcrest.CoreMatchers.is;
26 import static org.hamcrest.CoreMatchers.notNullValue;
27 import static org.hamcrest.MatcherAssert.assertThat;
28 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
29
30 import com.att.eelf.configuration.EELFLogger.Level;
31 import com.att.eelf.configuration.EELFManager;
32 import java.io.IOException;
33 import java.util.Arrays;
34 import javax.servlet.ServletRequest;
35 import javax.ws.rs.core.HttpHeaders;
36 import org.apache.commons.lang3.time.StopWatch;
37 import org.junit.jupiter.api.Assertions;
38 import org.junit.jupiter.api.BeforeAll;
39 import org.junit.jupiter.api.Disabled;
40 import org.junit.jupiter.api.Test;
41 import org.mockito.Mockito;
42 import org.onap.aai.babel.logging.LogHelper.MdcParameter;
43 import org.onap.aai.babel.logging.LogHelper.TriConsumer;
44 import org.onap.aai.cl.api.LogFields;
45 import org.onap.aai.cl.api.Logger;
46 import org.onap.aai.cl.mdc.MdcOverride;
47
48 /**
49  * Simple test to log each of the validation messages in turn.
50  *
51  * This version tests only the error logger at INFO level.
52  *
53  */
54 @Disabled("Test consistently fails in centos and is not critical")
55 public class TestApplicationLogger {
56
57     @BeforeAll
58     public static void setupClass() {
59         System.setProperty("APP_HOME", ".");
60     }
61
62     /**
63      * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
64      * resource (message format).
65      *
66      * @throws IOException
67      *             if the log files cannot be read
68      */
69     @Test
70     public void logAllMessages() throws IOException {
71         Logger logger = LogHelper.INSTANCE;
72         LogHelper.INSTANCE.clearContext();
73         LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
74         LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
75         String[] args = {"1", "2", "3", "4"};
76         for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
77             if (msg.name().endsWith("ERROR")) {
78                 logger.error(msg, args);
79                 validateLoggedMessage(msg, errorReader, "ERROR");
80
81                 logger.error(msg, new RuntimeException("fred"), args);
82                 validateLoggedMessage(msg, errorReader, "fred");
83             } else {
84                 logger.info(msg, args);
85                 validateLoggedMessage(msg, debugReader, "INFO");
86
87                 logger.warn(msg, args);
88                 validateLoggedMessage(msg, errorReader, "WARN");
89             }
90
91             logger.debug(msg, args);
92             validateLoggedMessage(msg, debugReader, "DEBUG");
93         }
94     }
95
96     /**
97      * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
98      * resource (message format).
99      *
100      * @throws IOException
101      *             if the log file cannot be read
102      */
103     @Test
104     public void logDebugMessages() throws IOException {
105         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
106         LogHelper.INSTANCE.debug("a message");
107         String str = reader.getNewLines();
108         assertThat(str, is(notNullValue()));
109     }
110
111     @Test
112     public void logTraceMessage() throws IOException {
113         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
114         EELFManager.getInstance().getDebugLogger().setLevel(Level.TRACE);
115         LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "a message");
116         String str = reader.getNewLines();
117         assertThat(str, is(notNullValue()));
118         EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
119         LogHelper.INSTANCE.trace(ApplicationMsgs.LOAD_PROPERTIES, "message not written");
120     }
121
122     /**
123      * Call logAuditError() for code coverage stats.
124      */
125     @Test
126     public void logAuditError() {
127         assertDoesNotThrow(() -> {
128             LogHelper.INSTANCE.logAuditError(new Exception("test"));
129             EELFManager.getInstance().getAuditLogger().setLevel(Level.OFF);
130             LogHelper.INSTANCE.logAuditError(new Exception("test"));
131             EELFManager.getInstance().getAuditLogger().setLevel(Level.INFO);
132         });
133     }
134
135     /**
136      * Check logAudit with HTTP headers.
137      *
138      * @throws IOException
139      *             if the log file cannot be read
140      */
141     @Test
142     public void logAuditMessage() throws IOException {
143         final LogHelper logger = LogHelper.INSTANCE;
144         final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
145
146         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
147         Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
148         Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id");
149
150         // Call logAudit without first calling startAudit
151         logger.logAuditSuccess("first call: bob");
152         String str = reader.getNewLines();
153         assertThat(str, is(notNullValue()));
154         assertThat("audit message log level", str, containsString("INFO"));
155         assertThat("audit message content", str, containsString("bob"));
156
157         // This time call the start method
158         logger.startAudit(headers, null);
159         logger.logAuditSuccess("second call: foo");
160         str = reader.getNewLines();
161         assertThat(str, is(notNullValue()));
162         assertThat("audit message log level", str, containsString("INFO"));
163         assertThat("audit message content", str, containsString("foo"));
164         assertThat("audit message content", str, containsString("ecomp-request-id"));
165         assertThat("audit message content", str, containsString("app-id"));
166     }
167
168     /**
169      * Check logAudit with no HTTP headers.
170      *
171      * @throws IOException
172      *             if the log file cannot be read
173      */
174     @Test
175     public void logAuditMessageWithoutHeaders() throws IOException {
176         LogHelper logger = LogHelper.INSTANCE;
177         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
178         logger.startAudit(null, null);
179         logger.logAuditSuccess("foo");
180         String str = reader.getNewLines();
181         assertThat(str, is(notNullValue()));
182         assertThat("audit message log level", str, containsString("INFO"));
183         assertThat("audit message content", str, containsString("foo"));
184     }
185
186     /**
187      * Check logAudit with mocked Servlet request.
188      *
189      * @throws IOException
190      *             if the log file cannot be read
191      */
192     @Test
193     public void logAuditMessageWithServletRequest() throws IOException {
194         ServletRequest servletRequest = Mockito.mock(ServletRequest.class);
195         LogHelper logger = LogHelper.INSTANCE;
196         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
197         logger.startAudit(null, servletRequest);
198         logger.logAuditSuccess("foo");
199         String str = reader.getNewLines();
200         assertThat(str, is(notNullValue()));
201         assertThat("audit message log level", str, containsString("INFO"));
202         assertThat("audit message content", str, containsString("foo"));
203     }
204
205     @Test
206     public void setDefaultContextValue() {
207         assertDoesNotThrow(() -> {
208             LogHelper logger = LogHelper.INSTANCE;
209             logger.setDefaultContextValue("key", "value");
210             logger.setDefaultContextValue(MdcParameter.USER, null);
211         });
212     }
213
214     /**
215      * Check logMetrics.
216      *
217      * @throws IOException
218      *             if the log file cannot be read
219      */
220     @Test
221     public void logMetricsMessage() throws IOException {
222         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
223         LogHelper logger = LogHelper.INSTANCE;
224         logger.logMetrics("metrics: fred");
225         String str = reader.getNewLines();
226         assertThat(str, is(notNullValue()));
227         assertThat("metrics message log level", str, containsString("INFO"));
228         assertThat("metrics message content", str, containsString("fred"));
229     }
230
231     @Test
232     public void logMetricsMessageWithStopwatch() throws IOException {
233         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
234         LogHelper logger = LogHelper.INSTANCE;
235         StopWatch stopWatch = new StopWatch();
236         stopWatch.start();
237         logger.logMetrics(stopWatch, "joe", "bloggs");
238         String logLine = reader.getNewLines();
239         assertThat(logLine, is(notNullValue()));
240         assertThat("metrics message log level", logLine, containsString("INFO"));
241         assertThat("metrics message content", logLine, containsString("joe"));
242     }
243
244     @Test
245     public void callUnsupportedMethods() throws IOException {
246         LogHelper logger = LogHelper.INSTANCE;
247         ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
248         callUnsupportedOperationMethod(logger::error, dummyMsg);
249         callUnsupportedOperationMethod(logger::info, dummyMsg);
250         callUnsupportedOperationMethod(logger::warn, dummyMsg);
251         callUnsupportedOperationMethod(logger::debug, dummyMsg);
252         callUnsupportedOperationMethod(logger::trace, dummyMsg);
253         try {
254             logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
255         } catch (UnsupportedOperationException e) {
256             // Expected to reach here
257         }
258         try {
259             logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
260         } catch (UnsupportedOperationException e) {
261             // Expected to reach here
262         }
263         try {
264             logger.formatMsg(dummyMsg, "");
265         } catch (UnsupportedOperationException e) {
266             // Expected to reach here
267         }
268     }
269
270     /**
271      * Call a logger method which is expected to throw an UnsupportedOperationException.
272      *
273      * @param logMethod
274      *            the logger method to invoke
275      * @param dummyMsg
276      *            any Application Message enumeration value
277      */
278     private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
279             ApplicationMsgs dummyMsg) {
280         logMethod.accept(dummyMsg, new LogFields(), new String[] {""});
281         Assertions.fail("method should have thrown execption"); // NOSONAR as code not reached
282     }
283
284     /**
285      * Assert that a log message was logged to the expected log file at the expected severity.
286      *
287      * @param msg
288      *            the Application Message enumeration value
289      * @param reader
290      *            the log reader for the message
291      * @param severity
292      *            log level
293      * @throws IOException
294      *             if the log file cannot be read
295      */
296     private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
297         String str = reader.getNewLines();
298         assertThat(str, is(notNullValue()));
299 //        assertThat(msg.toString() + " log level", str, containsString("BABEL"));
300     }
301 }