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