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