27193155c1c6f0b8f40e6a881a87b862f69a55cc
[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 if the log files cannot be read
59      */
60     @Test
61     public void logAllMessages() throws IOException {
62         Logger logger = LogHelper.INSTANCE;
63         LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error");
64         LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug");
65         String[] args = { "1", "2", "3", "4" };
66         for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) {
67             if (msg.name().endsWith("ERROR")) {
68                 logger.error(msg, args);
69                 validateLoggedMessage(msg, errorReader, "ERROR");
70
71                 logger.error(msg, new RuntimeException("fred"), args);
72                 validateLoggedMessage(msg, errorReader, "fred");
73             } else {
74                 logger.info(msg, args);
75                 validateLoggedMessage(msg, errorReader, "INFO");
76
77                 logger.warn(msg, args);
78                 validateLoggedMessage(msg, errorReader, "WARN");
79             }
80
81             logger.debug(msg, args);
82             validateLoggedMessage(msg, debugReader, "DEBUG");
83
84             // The trace level is not enabled
85             logger.trace(msg, args);
86         }
87     }
88
89     /**
90      * Check that each message can be logged and that (by implication of successful logging) there is a corresponding
91      * resource (message format).
92      *
93      * @throws IOException if the log file cannot be read
94      */
95     @Test
96     public void logDebugMessages() throws IOException {
97         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "debug");
98         LogHelper.INSTANCE.debug("a message");
99         String str = reader.getNewLines();
100         assertThat(str, is(notNullValue()));
101     }
102
103     /**
104      * Check logAudit with HTTP headers.
105      *
106      * @throws IOException if the log file cannot be read
107      */
108     @Test
109     public void logAuditMessage() throws IOException {
110         final LogHelper logger = LogHelper.INSTANCE;
111         final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
112
113         HttpHeaders headers = Mockito.mock(HttpHeaders.class);
114         Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id");
115         Mockito.when(headers.getHeaderString("X-FromAppId")).thenReturn("app-id");
116
117         // Call logAudit without first calling startAudit
118         logger.logAuditSuccess("first call: bob");
119         String str = reader.getNewLines();
120         assertThat(str, is(notNullValue()));
121         assertThat("audit message log level", str, containsString("INFO"));
122         assertThat("audit message content", str, containsString("bob"));
123
124         // This time call the start method
125         logger.startAudit(headers, null);
126         logger.logAuditSuccess("second call: foo");
127         str = reader.getNewLines();
128         assertThat(str, is(notNullValue()));
129         assertThat("audit message log level", str, containsString("INFO"));
130         assertThat("audit message content", str, containsString("foo"));
131         assertThat("audit message content", str, containsString("ecomp-request-id"));
132         assertThat("audit message content", str, containsString("app-id"));
133     }
134
135     /**
136      * Check logAudit with no HTTP headers.
137      *
138      * @throws IOException if the log file cannot be read
139      */
140     @Test
141     public void logAuditMessageWithoutHeaders() throws IOException {
142         LogHelper logger = LogHelper.INSTANCE;
143         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit");
144         logger.startAudit(null, null);
145         logger.logAuditSuccess("foo");
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("foo"));
150     }
151
152     /**
153      * Check logMetrics.
154      *
155      * @throws IOException if the log file cannot be read
156      */
157     @Test
158     public void logMetricsMessage() throws IOException {
159         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
160         LogHelper logger = LogHelper.INSTANCE;
161         logger.logMetrics("metrics: fred");
162         String str = reader.getNewLines();
163         assertThat(str, is(notNullValue()));
164         assertThat("metrics message log level", str, containsString("INFO"));
165         assertThat("metrics message content", str, containsString("fred"));
166     }
167
168     @Test
169     public void logMetricsMessageWithStopwatch() throws IOException {
170         LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics");
171         LogHelper logger = LogHelper.INSTANCE;
172         StopWatch stopWatch = new StopWatch();
173         stopWatch.start();
174         logger.logMetrics(stopWatch, "joe", "bloggs");
175         String logLine = reader.getNewLines();
176         assertThat(logLine, is(notNullValue()));
177         assertThat("metrics message log level", logLine, containsString("INFO"));
178         assertThat("metrics message content", logLine, containsString("joe"));
179     }
180
181     @Test
182     public void callUnsupportedMethods() throws IOException {
183         LogHelper logger = LogHelper.INSTANCE;
184         ApplicationMsgs dummyMsg = ApplicationMsgs.LOAD_PROPERTIES;
185         callUnsupportedOperationMethod(logger::error, dummyMsg);
186         callUnsupportedOperationMethod(logger::info, dummyMsg);
187         callUnsupportedOperationMethod(logger::warn, dummyMsg);
188         callUnsupportedOperationMethod(logger::debug, dummyMsg);
189         callUnsupportedOperationMethod(logger::trace, dummyMsg);
190         try {
191             logger.error(dummyMsg, new LogFields(), new RuntimeException("test"), "");
192         } catch (UnsupportedOperationException e) {
193             // Expected to reach here
194         }
195         try {
196             logger.info(dummyMsg, new LogFields(), new MdcOverride(), "");
197         } catch (UnsupportedOperationException e) {
198             // Expected to reach here
199         }
200         try {
201             logger.formatMsg(dummyMsg, "");
202         } catch (UnsupportedOperationException e) {
203             // Expected to reach here
204         }
205     }
206
207     /**
208      * Call a logger method which is expected to throw an UnsupportedOperationException.
209      *
210      * @param logMethod the logger method to invoke
211      * @param dummyMsg any Application Message enumeration value
212      */
213     private void callUnsupportedOperationMethod(TriConsumer<Enum<?>, LogFields, String[]> logMethod,
214             ApplicationMsgs dummyMsg) {
215         try {
216             logMethod.accept(dummyMsg, new LogFields(), new String[] { "" });
217             org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached
218         } catch (UnsupportedOperationException e) {
219             // Expected to reach here
220         }
221     }
222
223     /**
224      * Assert that a log message was logged to the expected log file at the expected severity.
225      *
226      * @param msg the Application Message enumeration value
227      * @param reader the log reader for the message
228      * @param severity log level
229      * @throws IOException if the log file cannot be read
230      */
231     private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException {
232         String str = reader.getNewLines();
233         assertThat(str, is(notNullValue()));
234         assertThat(msg.toString() + " log level", str, containsString(severity));
235     }
236 }