Merge "logging of HttpResponse use raw body"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / utils / LoggingUtilsTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.onap.vid.utils;
22
23 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
24 import static org.hamcrest.MatcherAssert.assertThat;
25 import static org.hamcrest.Matchers.matchesPattern;
26 import static org.mockito.ArgumentMatchers.contains;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.verify;
29 import static org.onap.vid.testUtils.RegExMatcher.matchesRegEx;
30 import static org.testng.AssertJUnit.assertEquals;
31
32 import com.att.eelf.configuration.EELFLogger;
33 import com.fasterxml.jackson.core.JsonLocation;
34 import com.fasterxml.jackson.core.JsonParseException;
35 import com.fasterxml.jackson.databind.JsonMappingException;
36 import io.joshworks.restclient.http.HttpResponse;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import java.nio.charset.StandardCharsets;
40 import java.security.UnrecoverableKeyException;
41 import java.security.cert.CertificateException;
42 import javax.crypto.BadPaddingException;
43 import javax.net.ssl.SSLHandshakeException;
44 import javax.ws.rs.ProcessingException;
45 import org.apache.commons.io.IOUtils;
46 import org.mockito.ArgumentCaptor;
47 import org.onap.vid.exceptions.GenericUncheckedException;
48 import org.onap.vid.testUtils.TestUtils;
49 import org.springframework.http.HttpMethod;
50 import org.testng.annotations.BeforeMethod;
51 import org.testng.annotations.DataProvider;
52 import org.testng.annotations.Test;
53 import sun.security.provider.certpath.SunCertPathBuilderException;
54 import sun.security.validator.ValidatorException;
55
56 public class LoggingUtilsTest {
57
58     private static final String TEST_OBJECT_JSON = "{\"key\":\"myNumber\",\"value\":42}";
59
60     public static class TestModel {
61         public String key;
62         public int value;
63
64         public TestModel(String key, int value) {
65             this.key = key;
66             this.value = value;
67         }
68
69         public TestModel() {}
70     }
71
72     private EELFLogger loggerMock;
73
74     private Logging logginService = new Logging();
75     private String url = "someUrl";
76     private final TestModel testObject = new TestModel("myNumber", 42);
77
78
79     @BeforeMethod
80     public void setUp() {
81         loggerMock = mock(EELFLogger.class);
82     }
83
84     @Test
85     public void whenLogRequest_thenLoggedInDebug() {
86         //when
87         logginService.logRequest(loggerMock, HttpMethod.GET, url);
88
89         //then
90         ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
91         verify(loggerMock).debug(contains("Sending"), argumentCaptor.capture());
92         assertEquals("GET", argumentCaptor.getAllValues().get(0));
93         assertEquals(url, argumentCaptor.getAllValues().get(1));
94     }
95
96
97
98     @Test
99     public void whenLogResponseOfHttpResponse_thenLoggedInDebug() throws Exception {
100         HttpResponse<TestModel> response = TestUtils.createTestHttpResponse(200, testObject, TestModel.class);
101         logginService.logResponse(loggerMock, HttpMethod.POST, url, response);
102
103         ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
104         ArgumentCaptor<String> messageCaptur = ArgumentCaptor.forClass(String.class);
105         verify(loggerMock).debug(messageCaptur.capture(), argumentCaptor.capture());
106
107         assertThat(messageCaptur.getValue(), matchesPattern("Received.*Status.*Body.*"));
108         assertEquals("POST", argumentCaptor.getAllValues().get(0));
109         assertEquals(url, argumentCaptor.getAllValues().get(1));
110         assertEquals(200, argumentCaptor.getAllValues().get(2));
111         assertEquals(TEST_OBJECT_JSON, argumentCaptor.getAllValues().get(3));
112     }
113
114     @Test
115     public void whenLogResponseOfHttpResponse_thenCanReadEntityAfterwards() throws Exception {
116         HttpResponse<TestModel> response = TestUtils.createTestHttpResponse(200, testObject, TestModel.class);
117         logginService.logResponse(loggerMock, HttpMethod.POST, url, response);
118         assertThat(response.getBody(), jsonEquals(TEST_OBJECT_JSON));
119     }
120
121     @Test
122     public void whenLogResponseOfHttpResponse_thenCanReadRawEntityAfterwards() throws Exception {
123         HttpResponse<TestModel> response = TestUtils.createTestHttpResponse(200, testObject, TestModel.class);
124         logginService.logResponse(loggerMock, HttpMethod.POST, url, response);
125         assertThat(IOUtils.toString(response.getRawBody(), StandardCharsets.UTF_8), jsonEquals(TEST_OBJECT_JSON));
126     }
127
128     @DataProvider
129     public static Object[][] exceptions() {
130         Exception e0 = new CertificateException("No X509TrustManager implementation available");
131         Exception noTrustMngrImplException = new SSLHandshakeException(e0.toString());
132         noTrustMngrImplException.initCause(e0);
133
134         Exception e1 = new BadPaddingException("Given final block not properly padded");
135         Exception incorrectPasswordException = new IOException("keystore password was incorrect",
136                 new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e1));
137         String incorrectPasswordExceptionDescription = "" +
138                 "java.io.IOException: keystore password was incorrect: " +
139                 "java.security.UnrecoverableKeyException: failed to decrypt safe contents entry: " +
140                 "javax.crypto.BadPaddingException: Given final block not properly padded";
141
142         Exception e2 = new SunCertPathBuilderException("unable to find valid certification path to requested target");
143         Exception noValidCert = new ProcessingException(new ValidatorException("PKIX path building failed: " + e2.toString(), e2));
144         String noValidCertDescription = "" +
145                 "javax.ws.rs.ProcessingException: " +
146                 "sun.security.validator.ValidatorException: PKIX path building failed: " +
147                 "sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target";
148
149         RuntimeException codehausParseException = new RuntimeException(new JsonParseException("Unexpected character ('<' (code 60)):" +
150                 " expected a valid value (number, String, array, object, 'true', 'false' or 'null')",
151                 new JsonLocation("<html>i'm an error</html>", 25, 1, 1)));
152         String codehausParseDescription = "" +
153                 "com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)):" +
154                 " expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n" +
155                 " at [Source: (String)\"<html>i'm an error</html>\"; line: 1, column: 1]";
156
157         RuntimeException fasterxmlMappingException = new RuntimeException(new JsonMappingException("Can not deserialize instance of java.lang.String out of START_ARRAY token",
158                 new com.fasterxml.jackson.core.JsonLocation("{ example json }", 15, 1, 20)));
159         String fasterxmlMappingDescription = "" +
160                 "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token\n" +
161                 " at [Source: (String)\"{ example json }\"; line: 1, column: 20]";
162
163         return new Object[][]{
164                 {"javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No X509TrustManager implementation available",
165                         noTrustMngrImplException},
166                 {"java.lang.StringIndexOutOfBoundsException: String index out of range: 4",
167                         new StringIndexOutOfBoundsException(4)},
168                 {"java.io.FileNotFoundException: vid/WEB-INF/cert/aai-client-cert.p12",
169                         new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12")},
170                 {"NullPointerException at LoggingUtilsTest.java:[0-9]+",
171                         new NullPointerException("null")},
172                 {incorrectPasswordExceptionDescription,
173                         incorrectPasswordException},
174                 {incorrectPasswordExceptionDescription,
175                         new GenericUncheckedException(incorrectPasswordException)},
176                 {"javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_expired",
177                         new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))},
178                 {noValidCertDescription,
179                         noValidCert},
180                 {escapeBrackets(codehausParseDescription),
181                         codehausParseException},
182                 {escapeBrackets(fasterxmlMappingDescription),
183                         fasterxmlMappingException},
184                 {"org.onap.vid.exceptions.GenericUncheckedException: top message: org.onap.vid.exceptions.GenericUncheckedException: root message",
185                         new GenericUncheckedException("top message", new IOException("sandwich message", new GenericUncheckedException("root message")))},
186                 {"org.onap.vid.exceptions.GenericUncheckedException: basa",
187                         new GenericUncheckedException("basa")}
188         };
189
190     }
191
192     @Test(dataProvider = "exceptions")
193     public void testExceptionToDescription(String expectedDescription, Exception exceptionToDescribe) {
194         String expectedButDotsEscaped = expectedDescription.replace(".", "\\.");
195
196         assertThat(Logging.exceptionToDescription(exceptionToDescribe), matchesRegEx(expectedButDotsEscaped));
197     }
198
199     private static String escapeBrackets(String in) {
200         return in.replaceAll("[\\(\\[\\{\\)]", "\\\\$0");
201     }
202 }