AT&T 1712 and 1802 release code
[so.git] / common / src / test / java / org / openecomp / mso / adapter_utils / tests / MsoLoggerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.adapter_utils.tests;
22
23 import org.openecomp.mso.entity.MsoRequest;
24 import org.openecomp.mso.logger.MessageEnum;
25 import org.openecomp.mso.logger.MsoLogger;
26 import org.openecomp.mso.logger.MsoLogger.ErrorCode;
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.BeforeClass;
30 import org.junit.Ignore;
31 import org.junit.Test;
32 import org.slf4j.MDC;
33
34 import java.io.File;
35 import java.io.FileNotFoundException;
36 import java.io.IOException;
37 import java.io.PrintWriter;
38 import java.lang.reflect.InvocationTargetException;
39 import java.lang.reflect.Method;
40 import java.net.URL;
41 import java.nio.charset.Charset;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.util.List;
45
46 /**
47  * This class implements all test methods of the MsoLogger features.
48  *
49  *
50  */
51 public class MsoLoggerTest {
52
53         static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
54
55         /**
56          * This method is called before any test occurs. It creates a fake tree from
57          * scratch
58          */
59         @BeforeClass
60         public static final void prepare() {
61
62         }
63
64         @Before
65         public final void cleanErrorLogFile() throws FileNotFoundException {
66                 URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
67                 String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
68                                 + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log";
69                 PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
70                 asdcConfigFileWriter.print("");
71                 asdcConfigFileWriter.flush();
72                 asdcConfigFileWriter.close();
73         }
74
75         @Before
76         public final void cleanMetricLogFile() throws FileNotFoundException {
77                 URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
78                 String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
79                                 + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log";
80                 PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
81                 asdcConfigFileWriter.print("");
82                 asdcConfigFileWriter.flush();
83                 asdcConfigFileWriter.close();
84         }
85
86         @Before
87         public final void cleanAuditLogFile() throws FileNotFoundException {
88                 URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
89                 String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
90                                 + "/MSO/Test/auditjbo                                                                                                                           ss.server.name_IS_UNDEFINED.log";
91                 PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
92                 asdcConfigFileWriter.print("");
93                 asdcConfigFileWriter.flush();
94                 asdcConfigFileWriter.close();
95         }
96
97         /**
98          * This method implements a test of getSeverifyLevel method.
99          */
100         @Test
101         public final void testGetSeverityLevel() {
102
103                 try {
104                         String levelInfo = (String) invokePriveMethod("getSeverityLevel", "INFO");
105                         Assert.assertEquals(levelInfo, "0");
106
107                         String levelWarn = (String) invokePriveMethod("getSeverityLevel", "WARN");
108                         Assert.assertEquals(levelWarn, "1");
109
110                         String levelERROR = (String) invokePriveMethod("getSeverityLevel", "ERROR");
111                         Assert.assertEquals(levelERROR, "2");
112
113                         String levelDEBUG = (String) invokePriveMethod("getSeverityLevel", "DEBUG");
114                         Assert.assertEquals(levelDEBUG, "0");
115
116                         String levelFATAL = (String) invokePriveMethod("getSeverityLevel", "FATAL");
117                         Assert.assertEquals(levelFATAL, "3");
118                 } catch (Exception e) {
119                         // TODO Auto-generated catch block
120                         e.printStackTrace();
121                 }
122         }
123
124         /**
125          * This method implements a test of getFinalServiceName method.
126          */
127         @Test
128         public final void testGetFinalServiceName() {
129                 try {
130                         String serviceName1 = (String) invokePriveMethod("getFinalServiceName", "testServiceName1");
131                         Assert.assertEquals(serviceName1, "testServiceName1");
132
133                         MsoLogger.setServiceName("testServiceName2");
134                         String serviceName2 = (String) invokePriveMethod("getFinalServiceName", "testServiceName1");
135                         Assert.assertEquals(serviceName2, "testServiceName1");
136
137                         String msgNull = null;
138                         String serviceName3 = (String) invokePriveMethod("getFinalServiceName", msgNull);
139                         Assert.assertEquals(serviceName3, "testServiceName2");
140
141                         MsoLogger.resetServiceName();
142                         String serviceName4 = (String) invokePriveMethod("getFinalServiceName", msgNull);
143                         Assert.assertEquals(serviceName4, "invoke0");
144                 } catch (Exception e) {
145                         // TODO Auto-generated catch block
146                         e.printStackTrace();
147                 }
148         }
149
150         @Test
151         public final void testPrepareMsg() {
152                 try {
153                         String msgNull = null;
154                         MDC.clear();
155                         invokePrepareMsg("INFO", null, null);
156
157                         Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("trace-#")
158                                         && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("trace-#")
159                                         && MDC.get(MsoLogger.SERVICE_NAME).equals("invoke0") && MDC.get(MsoLogger.TIMER) == null
160                                         && MDC.get(MsoLogger.ALERT_SEVERITY).equals("0"));
161
162                         MsoLogger.setLoggerParameters("testRemoteIp", "testUser");
163                         MsoLogger.setLogContext("testReqId", "testSvcId");
164                         invokePrepareMsg("ERROR", "testServiceName3", null);
165                         Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("testReqId")
166                                         && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId")
167                                         && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName3") && MDC.get(MsoLogger.TIMER) == null
168                                         && MDC.get(MsoLogger.ALERT_SEVERITY).equals("2"));
169
170                         MsoLogger.setServiceName("testServiceName2");
171                         invokePrepareMsg("WARN", msgNull, msgNull);
172                         Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("testReqId")
173                                         && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId")
174                                         && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName2") && MDC.get(MsoLogger.TIMER) == null
175                                         && MDC.get(MsoLogger.ALERT_SEVERITY).equals("1"));
176
177                         MDC.clear();
178                         MsoRequest msoRequest = new MsoRequest();
179                         msoRequest.setRequestId("reqId2");
180                         msoRequest.setServiceInstanceId("servId2");
181                         MsoLogger.setLogContext(msoRequest);
182                         invokePrepareMsg("FATAL", null, "123");
183                         Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("reqId2")
184                                         && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("servId2")
185                                         && MDC.get(MsoLogger.TIMER).equals("123") && MDC.get(MsoLogger.ALERT_SEVERITY).equals("3"));
186
187                 } catch (Exception e) {
188                         // TODO Auto-generated catch block
189                         e.printStackTrace();
190                 }
191         }
192
193         /**
194          * This method implements a test of log methods
195          */
196         @Test
197         @Ignore
198         public final void testLogMethods() {
199                 try {
200                         MDC.clear();
201                         MsoLogger.setLogContext("reqId2", "servId2");
202                         MsoLogger.setServiceName("MSO.testServiceName");
203                         msoLogger.info(MessageEnum.LOGGER_UPDATE_SUC, "testLogger", "INFO", "DEBUG", "target entity",
204                                         "target service");
205                         msoLogger.warn(MessageEnum.GENERAL_WARNING, "warning test", "", "", MsoLogger.ErrorCode.UnknownError,
206                                         "warning test");
207                         msoLogger.error(MessageEnum.GENERAL_EXCEPTION, "target entity", "target service",
208                                         MsoLogger.ErrorCode.UnknownError, "error test");
209
210                         // Fetch from the error log
211                         URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
212                         String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
213                                         + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log";
214
215                         Path filePath = new File(logFile).toPath();
216                         Charset charset = Charset.defaultCharset();
217                         List<String> stringList = Files.readAllLines(filePath, charset);
218                         String[] stringArray = stringList.toArray(new String[] {});
219                         int size = stringArray.length;
220
221                         Assert.assertTrue(stringArray[size - 3]
222                                         .contains("|reqId2|main|MSO.testServiceName||target entity|target service|INFO|null||")
223                                         && stringArray[size - 3].contains(
224                                                         "||MSO-GENERAL-5408I Successfully update Logger: testLogger from level INFO to level DEBUG"));
225                         Assert.assertTrue(stringArray[size - 2]
226                                         .contains("|reqId2|main|MSO.testServiceName||||WARN|UnknownError|warning test|")
227                                         && stringArray[size - 2].contains("|MSO-GENERAL-5401W WARNING: warning test"));
228                         Assert.assertTrue(stringArray[size - 1].contains(
229                                         "|reqId2|main|MSO.testServiceName||target entity|target service|ERROR|UnknownError|error test|")
230                                         && stringArray[size - 1].contains("|MSO-GENERAL-9401E Exception encountered"));
231
232                 } catch (Exception e) {
233                         // TODO Auto-generated catch block
234                         e.printStackTrace();
235                 }
236         }
237
238         /**
239          * This method implements a test of recordMetricEvent method.
240          * 
241          * @throws IOException
242          */
243         @Test
244         @Ignore
245         public final void testRecordMetricEvent() throws IOException {
246                 MDC.clear();
247                 MsoLogger.setLogContext("reqId", "servId");
248                 msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful",
249                                 "VNF", "createVNF", null);
250                 MDC.put(MsoLogger.REMOTE_HOST, "127.0.0.1");
251                 MDC.put(MsoLogger.PARTNERNAME, "testUser");
252                 msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable,
253                                 "Exception", "SDNC", "removeSDNC", "testVNF");
254
255                 // Fetch from the metric log
256                 URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
257                 String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
258                                 + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log";
259
260                 Path filePath = new File(logFile).toPath();
261                 Charset charset = Charset.defaultCharset();
262                 List<String> stringList = Files.readAllLines(filePath, charset);
263                 String[] stringArray = stringList.toArray(new String[] {});
264                 msoLogger.error(MessageEnum.GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.UnknownError, "test error msg");
265
266                 Assert.assertTrue(stringArray[0]
267                                 .contains("|reqId|servId|main||testRecordMetricEvent||VNF|createVNF|COMPLETE|0|Successful|"));
268                 // count the occurance of symbol "|"
269                 Assert.assertTrue((stringArray[0].length() - stringArray[0].replace("|", "").length()) == 28);
270                 Assert.assertTrue(stringArray[1]
271                                 .contains("|reqId|servId|main||testRecordMetricEvent|testUser|SDNC|removeSDNC|ERROR|501|Exception|")
272                                 && stringArray[1].contains("|127.0.0.1||||testVNF|||||"));
273                 Assert.assertTrue((stringArray[1].length() - stringArray[1].replace("|", "").length()) == 28);
274         }
275
276         /**
277          * This method implements a test of testRecordAuditEvent method.
278          */
279
280         // User reflection to invoke to avoid change the publicity of the method
281         private static String invokePrepareMsg(String arg1, String arg2, String arg3) {
282                 Method method;
283                 try {
284                         method = MsoLogger.class.getDeclaredMethod("prepareMsg", String.class, String.class, String.class);
285                         method.setAccessible(true);
286                         return (String) method.invoke(msoLogger, arg1, arg2, arg3);
287                 } catch (NoSuchMethodException e) {
288                         // TODO Auto-generated catch block
289                         e.printStackTrace();
290                 } catch (SecurityException e) {
291                         // TODO Auto-generated catch block
292                         e.printStackTrace();
293                 } catch (IllegalAccessException e) {
294                         // TODO Auto-generated catch block
295                         e.printStackTrace();
296                 } catch (IllegalArgumentException e) {
297                         // TODO Auto-generated catch block
298                         e.printStackTrace();
299                 } catch (InvocationTargetException e) {
300                         // TODO Auto-generated catch block
301                         e.printStackTrace();
302                 }
303                 return null;
304         }
305
306         // User reflection to invoke to avoid change the publicity of the method
307         private static Object invokePriveMethod(String methodName, String arg) {
308                 Method method;
309                 try {
310                         method = MsoLogger.class.getDeclaredMethod(methodName, String.class);
311                         method.setAccessible(true);
312                         return method.invoke(msoLogger, arg);
313                 } catch (NoSuchMethodException e) {
314                         // TODO Auto-generated catch block
315                         e.printStackTrace();
316                 } catch (SecurityException e) {
317                         // TODO Auto-generated catch block
318                         e.printStackTrace();
319                 } catch (IllegalAccessException e) {
320                         // TODO Auto-generated catch block
321                         e.printStackTrace();
322                 } catch (IllegalArgumentException e) {
323                         // TODO Auto-generated catch block
324                         e.printStackTrace();
325                 } catch (InvocationTargetException e) {
326                         // TODO Auto-generated catch block
327                         e.printStackTrace();
328                 }
329                 return null;
330         }
331 }