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