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