diff options
Diffstat (limited to 'common-app-logging/src/test')
8 files changed, 1253 insertions, 0 deletions
diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java new file mode 100644 index 0000000000..1634115b06 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LogFieldsMdcHandlerTest.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import static org.junit.Assert.*; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; + +public class LogFieldsMdcHandlerTest { + + private LogFieldsMdcHandler ecompMdcWrapper; + + @Before + public void init(){ + ecompMdcWrapper = new LogFieldsMdcHandler(); + ecompMdcWrapper.clear(); + MDC.clear(); + } + + @Test + public void isMDCParamEmpty_shouldReturnTrue_onNonNullValueInMDC(){ + MDC.put("Key","value1"); + assertFalse(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + @Test + public void isMDCParamEmpty_shouldReturnFalse_onEmptyStringInMDC(){ + MDC.put("Key",""); + assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + + @Test + public void isMDCParamEmpty_shouldReturnFalse_onNullValueInMDC(){ + MDC.put("Key",null); + assertTrue(ecompMdcWrapper.isMDCParamEmpty("Key")); + } + + @Test + public void startTimer_shouldFilecompMdcWrappereginTimestampField(){ + ecompMdcWrapper.startMetricTimer(); + assertFalse(ecompMdcWrapper.isMDCParamEmpty(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Test + public void stopTimer_shouldFillEndTimestampField_ifStartTimerWasCalledPreviously(){ + ecompMdcWrapper.startAuditTimer(); + ecompMdcWrapper.stopAuditTimer(); + assertFalse(ecompMdcWrapper.isMDCParamEmpty(MDC_END_TIMESTAMP)); + } + + @Test + public void clear_shouldRemoveAllMandatoryAndOptionalFields_And_OnlyThem(){ + ecompMdcWrapper.setClassName("class1"); + ecompMdcWrapper.setPartnerName("partner1"); + ecompMdcWrapper.setOptCustomField1("of1"); + ecompMdcWrapper.clear(); + assertNull(MDC.get(MDC_CLASS_NAME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertNull(MDC.get(MDC_OPT_FIELD1)); + } + + @Test + public void clear_shouldNotThrowAnException_WhenNoFieldWasAssignedAsMandatoryOrOptional(){ + ecompMdcWrapper.setClassName("class1"); + ecompMdcWrapper.setPartnerName("partner1"); + ecompMdcWrapper.setOptCustomField1("of1"); + Exception exp = null; + try { + ecompMdcWrapper.clear(); + } + catch (Exception e) + { + exp =e; + } + assertNull(exp); + } + +} + diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java new file mode 100644 index 0000000000..4b0533ae24 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAsdcUtilTest.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; +import org.openecomp.sdc.common.log.wrappers.LoggerSdcUtilBase; +import org.slf4j.MarkerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.UriInfo; +import java.net.URI; +import java.net.URISyntaxException; + +import static java.net.HttpURLConnection.*; +import static org.junit.Assert.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerAsdcUtilTest { + + private static final String chromeUserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"; + private static final String firefoxUserAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.13) Gecko/20080313 Firefox"; + private static final String explorerUserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)"; + + private static final String testUserId = "ml007"; + private static final String urlWithUserName = "/api/v1/user/" + testUserId; + private static final String xOnapPartnerName = "ml007"; + + class SdcEelfAuditTest extends LoggerSdcAudit { + + SdcEelfAuditTest(Class<?> clazz) { + super(clazz); + } + + public String getPartnerName(String userAgent, String userID, String url, String xOnapPartnerName) { + return super.getPartnerName(userAgent, userID, url, xOnapPartnerName); + } + } + + @Mock + private ContainerRequestContext requestContext; + @Mock + UriInfo uriInfo; + + private SdcEelfAuditTest asdcEelfAudit; + + @Before + public void Init () throws URISyntaxException { + asdcEelfAudit = new SdcEelfAuditTest(LoggerAsdcUtilTest.class); + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + + } + + @Test + public void extract_user_id_from_userAgentTest() { + + String userIdChrome = asdcEelfAudit.getPartnerName(chromeUserAgent, "", "", ""); + assertEquals(userIdChrome.toLowerCase(), "chrome_FE".toLowerCase()); + + String userIdFireFox = asdcEelfAudit.getPartnerName(firefoxUserAgent, "", "", ""); + assertEquals(userIdFireFox.toLowerCase(), "firefox_FE".toLowerCase()); + + String userIdIE = asdcEelfAudit.getPartnerName(explorerUserAgent, "", "", ""); + assertEquals(userIdIE.toLowerCase(), "explorer_FE".toLowerCase()); + } + + @Test + public void extract_user_id_from_urlTest() { + + String userId = asdcEelfAudit.getPartnerName("", "", urlWithUserName, ""); + assertEquals(testUserId, userId); + } + + @Test + public void extract_user_id_from_paramTest() { + + String userId = asdcEelfAudit.getPartnerName("", testUserId, "", ""); + assertEquals(userId, testUserId); + } + + @Test + public void extract_user_id_from_xOnapPartnerNameTest() { + + String userId = asdcEelfAudit.getPartnerName("", "", "", xOnapPartnerName); + assertEquals(userId, testUserId); + } + + @Test + public void extract_user_id_priorityTest() { + + String userId = asdcEelfAudit.getPartnerName(chromeUserAgent, testUserId, urlWithUserName, xOnapPartnerName); + assertEquals(userId, testUserId); + + String userIdUrl = asdcEelfAudit.getPartnerName(chromeUserAgent, "", urlWithUserName, ""); + assertEquals(userIdUrl, testUserId); + + String userIdUserAgent = asdcEelfAudit.getPartnerName(chromeUserAgent, "", "", ""); + assertEquals(userIdUserAgent.toLowerCase(), "chrome_FE".toLowerCase()); + } + + @Test + public void check_http_error_convert_to_eelf_code() { + class LoggerSdcUtilBaseTest extends LoggerSdcUtilBase { + public EcompLoggerErrorCode convertHttpCodeToErrorCode(int httpResponseCode) { + return super.convertHttpCodeToErrorCode(httpResponseCode); + } + } + + LoggerSdcUtilBaseTest utilBase = new LoggerSdcUtilBaseTest(); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_REQUEST), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAUTHORIZED), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_FOUND), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CLIENT_TIMEOUT), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GONE), EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PAYMENT_REQUIRED), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_FORBIDDEN), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_METHOD), EcompLoggerErrorCode.PERMISSION_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PROXY_AUTH), EcompLoggerErrorCode.PERMISSION_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_ACCEPTABLE), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_LENGTH_REQUIRED), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_PRECON_FAILED), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_REQ_TOO_LONG), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_ENTITY_TOO_LARGE), EcompLoggerErrorCode.DATA_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNSUPPORTED_TYPE), EcompLoggerErrorCode.DATA_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_CONFLICT), EcompLoggerErrorCode.SCHEMA_ERROR); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_OK), EcompLoggerErrorCode.SUCCESS); + + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_INTERNAL_ERROR), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_NOT_IMPLEMENTED), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_BAD_GATEWAY), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_UNAVAILABLE), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_GATEWAY_TIMEOUT), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + Assert.assertEquals(utilBase.convertHttpCodeToErrorCode(HTTP_VERSION), EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR); + + } + + @Test + public void takenCareOf_shouldBeTrue_ifStartedLogWasCalled(){ + asdcEelfAudit.startLog(requestContext); + assertTrue(asdcEelfAudit.isFlowBeingTakenCare()); + } + + @Test + public void takenCareOf_shouldBeFalse_ifStartedLogWasNoCalled(){ + assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); + } + + @Test + public void takenCareOf_shouldBeFalse_ifStartedLogWasCalleAndLogWasCalledToo(){ + asdcEelfAudit.startLog(requestContext); + + asdcEelfAudit.logExit(null,null,null, LogLevel.INFO, Severity.OK, + "message", MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); + assertFalse(asdcEelfAudit.isFlowBeingTakenCare()); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java new file mode 100644 index 0000000000..7ca1cf16cc --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerAuditTest.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; +import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.DATA_ERROR; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerAuditTest { + @Mock + private Logger logger; + + private LoggerAudit auditLog; + + @Before + public void init() { + auditLog = new LoggerAudit(LogFieldsMdcHandler.getInstance(), logger); + } + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void whenNoAuditFieldsArePopulated_ShouldReturnAssertTrue_onMdcMap() { + auditLog.clear() + .log(LogLevel.INFO, "some error code"); + Assert.assertNotNull(MDC.get(SERVER_FQDN)); + Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); + } + + @Test + public void whenAllAuditFieldsArePopulated_ShouldReturnAssertTrue_onEachMACField() throws UnknownHostException { + + String uuid = UUID.randomUUID().toString(); + String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); + String hostAddress = InetAddress.getLocalHost().getHostAddress(); + + auditLog.clear() + .startTimer() + .stopTimer() + .setKeyRequestId(uuid) + .setInstanceUUID(INSTANCE_UUID) + .setRemoteHost(MDC_REMOTE_HOST) + .setServiceName(SERVICE_NAME) + .setResponseCode(DATA_ERROR) + .setStatusCodeByResponseCode("201") + .setResponseDesc(RESPONSE_DESCRIPTION) + .setPartnerName(PARTNER_NAME) + + .setOptClassName(LoggerAuditTest.class.toString()) + .setOptAlertSeverity(Severity.CRITICAL) + .setOptProcessKey(MDC_PROCESS_KEY) + .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) + .log(LogLevel.DEBUG, ""); + + + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(ENTRY_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + + Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS), hostAddress); + Assert.assertEquals(MDC.get(SERVER_FQDN), hostName); + Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); + Assert.assertEquals(MDC.get(RESPONSE_STATUS_CODE), ONAPLogConstants.ResponseStatus.COMPLETE.name()); + + Assert.assertEquals(MDC.get(REQUEST_ID), uuid); + Assert.assertEquals(MDC.get(SERVICE_NAME), SERVICE_NAME); + Assert.assertEquals(MDC.get(PARTNER_NAME), PARTNER_NAME); + Assert.assertEquals(MDC.get(RESPONSE_CODE), String.valueOf(DATA_ERROR.getErrorCode())); + Assert.assertEquals(MDC.get(RESPONSE_DESCRIPTION), RESPONSE_DESCRIPTION); + Assert.assertEquals(MDC.get(INSTANCE_UUID), INSTANCE_UUID); + Assert.assertEquals(MDC.get(MDC_CLASS_NAME), LoggerAuditTest.class.toString()); + + Assert.assertEquals(MDC.get(RESPONSE_SEVERITY), String.valueOf(Severity.CRITICAL.getSeverityType())); + Assert.assertEquals(MDC.get(MDC_PROCESS_KEY), MDC_PROCESS_KEY); + Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID), MDC_SERVICE_INSTANCE_ID); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java new file mode 100644 index 0000000000..91e1aab267 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerBaseTest.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.ConstantsLogging; + +import javax.servlet.http.HttpServletRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerBaseTest { + + @Mock + HttpServletRequest httpServletRequest; + + private static final String ONAP_REQ_ID_VALUE = "onapReqId"; + private static final String REQ_ID_VALUE = "reqId"; + private static final String TRANSACTION_RE_IQ_VALUE = "transactionReqId"; + private static final String ECOMP_REQ_ID_VALUE = "ecompReqId"; + private static final String USER_ID_VALUE = "userId"; + private static final String ONAP_PARTNER_NAME_VALUE = "partnerName"; + private static final String USER_UGENT = "userAgent"; + + @Test + public void testGetRequestIfFromOnapHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(ONAP_REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(ONAP_REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromReqIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(REQ_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromTransactionIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(TRANSACTION_RE_IQ_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(TRANSACTION_RE_IQ_VALUE); + } + + @Test + public void testGetRequestIfFromEcompIdHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(ECOMP_REQ_ID_VALUE); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isEqualTo(ECOMP_REQ_ID_VALUE); + } + + @Test + public void testGetRequestIfFromRandonHeader() { + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_REQUEST_ID)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_TRANSACTION_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(null); + + String requestId = LoggerBase.getRequestId(httpServletRequest); + assertThat(requestId).isNotEmpty(); + } + + @Test + public void testPartnerNameFromUserHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(USER_ID_VALUE); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(USER_UGENT); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(ONAP_PARTNER_NAME_VALUE); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(USER_ID_VALUE); + } + + @Test + public void testPartnerNameFromOnapPartnerNameHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(ONAP_PARTNER_NAME_VALUE); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(ONAP_PARTNER_NAME_VALUE); + } + + @Test + public void testPartnerNameFromReqUriHeader() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(USER_UGENT); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(USER_UGENT); + } + + @Test + public void testPartnerNameUnknown() { + when(httpServletRequest.getHeader(ConstantsLogging.USER_ID_HEADER)).thenReturn(null); + when(httpServletRequest.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)).thenReturn(null); + when(httpServletRequest.getHeader(ConstantsLogging.USER_AGENT_HEADER)).thenReturn(null); + + String partnerName = LoggerBase.getPartnerName(httpServletRequest); + assertThat(partnerName).isEqualTo(ConstantsLogging.PartnerName_Unknown); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java new file mode 100644 index 0000000000..020b55cba6 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerDebugTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerDebugTest { + + @Mock + private Logger logger; + + private LoggerDebug debugLog; + + @Before + public void init() { + debugLog = new LoggerDebug(LogFieldsMdcHandler.getInstance(), logger); + LoggingThreadLocalsHolder.setUuid(null); + MDC.clear(); + } + + @Test + public void whenNoFieldsIsPopulated_RequestedMdcFieldsAreEmpty() { + debugLog.clear() + .log(LogLevel.DEBUG, "some error code"); + assertNull(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + } + + @Test + public void debugLogCheckValidationValidFieldsTest() { + debugLog.clear() + .startTimer() + .setKeyRequestId("uuid") + .log(LogLevel.DEBUG, "some error code"); + + assertEquals(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID), "uuid"); + } + + @Test + public void whenOnlyDebugUUIDFieldsIsPopulated_ShouldReturnAssertTrue_onUUIDFieldCheck() { + debugLog.clear() + .setKeyRequestId("uuid") + .log(LogLevel.DEBUG, "some error code"); + + assertEquals("uuid", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + } + + @Test + public void whenAllDebugFieldsArePopulated_ShouldReturnAssertTrue_onEachMACFieldCheck() throws UnknownHostException { + debugLog.clear() + .startTimer() + .setKeyRequestId(ONAPLogConstants.MDCs.REQUEST_ID) + .log(LogLevel.DEBUG, "some message"); + + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + Assert.assertTrue(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(RESPONSE_STATUS_CODE)); + } + + + @Test + public void validateMandatoryFields(){ + assertEquals(ONAPLogConstants.MDCs.REQUEST_ID, debugLog.checkMandatoryFieldsExistInMDC().trim()); + } + + @Test + public void validateMandatoryFieldsWhenFieldIsSet(){ + debugLog.clear() + .setKeyRequestId("1234"); + assertEquals("", debugLog.checkMandatoryFieldsExistInMDC()); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java new file mode 100644 index 0000000000..06376ed48f --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerErrorTest.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.EcompLogErrorCode; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerErrorTest { + private LoggerError errorLog; + + @Mock + private Logger logger; + @Before + public void init() { + errorLog = LoggerFactory.getMdcLogger(LoggerError.class, logger); + MDC.clear(); + } + + @Test + public void allFieldsArePresentTest() { + LoggingThreadLocalsHolder.setUuid("uuid"); + errorLog.log(LogLevel.ERROR, EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, "service", "entity", "server error"); + + assertEquals(MDC.get(MDC_ERROR_CODE), String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode())); + assertEquals("uuid", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("entity", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("service", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + } + + @Test + public void missingFieldsTest() { + errorLog.clear() + .log(LogLevel.ERROR,"some message"); + } + + @Test + public void convertEcompErrorForLogging_correctName() { + assertEquals(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, EcompLoggerErrorCode.getByValue(EcompLogErrorCode.E_210.name())); + } + + @Test + public void convertEcompErrorForLogging_correctName_2() { + assertEquals(EcompLoggerErrorCode.DATA_ERROR, EcompLoggerErrorCode.getByValue(EcompLogErrorCode.E_399.name())); + } + + @Test + public void convertEcompErrorForLogging_NotConvertable() { + assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("ABC")); + } + + @Test + public void convertEcompErrorForLogging_NotConvertable_2() { + assertEquals(EcompLoggerErrorCode.UNKNOWN_ERROR, EcompLoggerErrorCode.getByValue("E_ABC")); + } + + @Test + public void convertEcompErrorForLogging_Success() { + assertEquals(EcompLoggerErrorCode.SUCCESS, EcompLoggerErrorCode.getByValue("E_0")); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java new file mode 100644 index 0000000000..3bd1afcce9 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/elements/LoggerMetricTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.elements; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.MDC; + +import javax.ws.rs.core.Response; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.UUID; + +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.*; +import static org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler.hostAddress; + +/** + * Created by dd4296 on 12/31/2017. + */ +@RunWith(MockitoJUnitRunner.class) +public class LoggerMetricTest { + @Mock + private Logger logger; + + @Mock + Response.StatusType statusType; + + private LoggerMetric metricLog; + + @Before + public void init() { + metricLog = new LoggerMetric(LogFieldsMdcHandler.getInstance(), logger); + } + + @After + public void tearDown() { + MDC.clear(); + LoggingThreadLocalsHolder.setUuid(null); + } + + @Test + public void whenNoMetricFieldsArePopulated_ShouldReturnassertEquals_onMdcMap() { + metricLog.clear() + .log(LogLevel.DEBUG, "some error code"); + Assert.assertNotNull(MDC.get(SERVER_FQDN)); + Assert.assertNotNull(MDC.get(MDC_SERVER_IP_ADDRESS)); + } + + @Test + public void whenAllMetricFieldsArePopulated_ShouldReturnassertEquals_onEachMACField() throws UnknownHostException { + String uuid = UUID.randomUUID().toString(); + LoggingThreadLocalsHolder.setUuid(uuid); + + String hostName = InetAddress.getByName(hostAddress).getCanonicalHostName(); + String hostAddress = InetAddress.getLocalHost().getHostAddress(); + + metricLog.clear() + .startTimer() + .stopTimer() + .setInstanceUUID(INSTANCE_UUID) + .setRemoteHost(MDC_REMOTE_HOST) + .setServiceName(SERVICE_NAME) + .setResponseCode(500) + .setStatusCode(COMPLETE.name()) + .setResponseDesc(RESPONSE_DESCRIPTION) + .setPartnerName(PARTNER_NAME) + .setOptClassName(LoggerMetricTest.class.toString()) + .setOptServiceInstanceId(MDC_SERVICE_INSTANCE_ID) + .setTargetEntity(TARGET_ENTITY) + .setTargetServiceName(TARGET_SERVICE_NAME) + .setTargetVirtualEntity(MDC_TARGET_VIRTUAL_ENTITY) + .log(LogLevel.DEBUG, ""); + + + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(INVOKE_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_END_TIMESTAMP)); + Assert.assertFalse(LogFieldsMdcHandler.getInstance().isMDCParamEmpty(MDC_ELAPSED_TIME)); + Assert.assertEquals(MDC.get(MDC_SERVER_IP_ADDRESS),hostAddress); + Assert.assertEquals(MDC.get(SERVER_FQDN), hostName); + Assert.assertEquals(MDC.get(MDC_REMOTE_HOST), MDC_REMOTE_HOST); + Assert.assertEquals(MDC.get(RESPONSE_STATUS_CODE) , "COMPLETE"); + Assert.assertEquals(MDC.get(REQUEST_ID), uuid); + Assert.assertEquals(MDC.get(SERVICE_NAME) , SERVICE_NAME); + Assert.assertEquals(MDC.get(PARTNER_NAME) , PARTNER_NAME); + Assert.assertEquals(MDC.get(RESPONSE_CODE) ,"500"); + Assert.assertEquals(MDC.get(RESPONSE_DESCRIPTION) , RESPONSE_DESCRIPTION); + Assert.assertEquals(MDC.get(INSTANCE_UUID) , INSTANCE_UUID); + Assert.assertEquals(MDC.get(MDC_CLASS_NAME) ,LoggerMetricTest.class.toString()); + Assert.assertEquals(MDC.get(MDC_SERVICE_INSTANCE_ID) ,MDC_SERVICE_INSTANCE_ID); + Assert.assertEquals(MDC.get(TARGET_ENTITY) , TARGET_ENTITY); + Assert.assertEquals(MDC.get(TARGET_SERVICE_NAME) , TARGET_SERVICE_NAME); + Assert.assertEquals(MDC.get(MDC_TARGET_VIRTUAL_ENTITY) ,MDC_TARGET_VIRTUAL_ENTITY); + } +} diff --git a/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java new file mode 100644 index 0000000000..fd66efffc7 --- /dev/null +++ b/common-app-logging/src/test/java/org/openecomp/sdc/common/log/wrappers/LoggerTest.java @@ -0,0 +1,378 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.log.wrappers; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.common.log.api.LogConfigurationConstants; +import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData; +import org.openecomp.sdc.common.log.elements.LoggerError; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.enums.Severity; +import org.openecomp.sdc.common.log.utils.LoggingThreadLocalsHolder; +import org.slf4j.MDC; +import org.slf4j.Marker; +import org.slf4j.MarkerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.net.URI; +import java.net.URISyntaxException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.REQUEST_ID; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CATEGORY; +import static org.openecomp.sdc.common.log.api.LogConfigurationConstants.MDC_ERROR_CODE; + +@RunWith(MockitoJUnitRunner.class) +public class LoggerTest { + + private final static String targetEntity = "DCEA"; + private final static String targetServiceName = "test target name"; + private final static String serviceName = "testService"; + private final static String message = "Logger message"; + private final static String exceptionMsg= "Exception testing"; + + @Mock + private org.slf4j.Logger logger; + @Mock + private ContainerRequestContext requestContext; + @Mock + private UriInfo uriInfo; + @Mock + private Response.StatusType statusType; + + @InjectMocks + private Logger commonLogger; + + @Captor + private ArgumentCaptor<String> captor; + + @Before + public void setUp() { + MDC.clear(); + } + + @Test + public void validateErrorLogWhenErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateWarnMessageIsLoggedWhenAllErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.AVAILABILITY_TIMEOUTS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateFatalMessageIsLoggedWhenAllErrorSettingsProvided() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.fatal(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.PERMISSION_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.FATAL.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_AllErrorElements() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity) + .targetServiceName(targetServiceName).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_emptyTargetEntity() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetServiceName(targetServiceName).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateWarnMessage_emptyTargetServiceName() { + when(logger.isWarnEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity).build(); + commonLogger.warn(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).warn(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + + @Test + public void validateErrorMessage_AllErrorElements() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity) + .targetServiceName(targetServiceName).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateErrorMessage_emptyTargetEntity() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetServiceName(targetServiceName).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(targetServiceName, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + @Test + public void validateErrorMessage_emptyTargetServiceName() { + when(logger.isErrorEnabled()).thenReturn(true); + ErrorLogOptionalData errorLogOptionalData = ErrorLogOptionalData.newBuilder() + .targetEntity(targetEntity).build(); + commonLogger.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, serviceName,errorLogOptionalData, message); + verify(logger).error(any(Marker.class), captor.capture(), any(Object[].class)); + assertEquals(message, captor.getValue()); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals(targetEntity, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(serviceName, MDC.get(SERVICE_NAME)); + assertEquals(null, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + } + + + + @Test + public void validateErrorMessageIsNotLoggedWhenErrorLevelIsDisabledEvenIfErrorSettingsProvided() { + commonLogger.error(EcompLoggerErrorCode.PERMISSION_ERROR, serviceName, targetEntity, message); + verify(logger, never()).error(any(Marker.class), any(String.class)); + } + + @Test + public void validateErrorLogWhenErrorSettingsProvidedPartially() { + when(logger.isErrorEnabled()).thenReturn(true); + commonLogger.error(message); + + verify(logger).error(any(Marker.class), eq(message), any(Object[].class)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.ERROR.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void errorMessageIsNotLoggedWhenErrorLevelIsDisabled() { + commonLogger.error(message); + verify(logger, times(0)).error(any(Marker.class), anyString()); + } + + @Test + public void traceMessageWithExceptionIsNotLoggedWhenTraceLevelIsDisabled() { + commonLogger.trace(message, new UnsupportedOperationException()); + verify(logger, times(0)).trace(any(Marker.class), anyString()); + } + + @Test + public void verifyInfoMessage() { + final String msg = "Info message"; + when(logger.isInfoEnabled()).thenReturn(true); + commonLogger.info(msg, new RuntimeException()); + verify(logger).info(any(Marker.class), anyString()); + } + + @Test + public void verifyWarnMessage() { + when(logger.isWarnEnabled()).thenReturn(true); + commonLogger.warn("Text"); + assertEquals(LogLevel.WARN.name(), MDC.get(MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + @Test + public void validateErrorLogWithExceptionWhenErrorSettingsProvidedPartially() { + LoggingThreadLocalsHolder.setUuid("uuid"); + when(logger.isWarnEnabled()).thenReturn(true); + commonLogger.warn(message, new NullPointerException(exceptionMsg)); + + //the expected warn message + verify(logger).warn(any(Marker.class), contains(message), any(Object[].class)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(LogConfigurationConstants.MDC_ERROR_CODE)); + assertEquals(LogLevel.WARN.name(), MDC.get(LogConfigurationConstants.MDC_ERROR_CATEGORY)); + assertEquals("uuid", MDC.get(REQUEST_ID)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals(LoggerError.defaultServiceName, MDC.get(SERVICE_NAME)); + } + + + @Test + public void validateDebugLogWithException() { + final String msg = "Debug message"; + LoggingThreadLocalsHolder.setUuid("uuid"); + when(logger.isDebugEnabled()).thenReturn(true); + commonLogger.debug(msg, new RuntimeException()); + + verify(logger).debug(any(Marker.class), eq(msg), any(RuntimeException.class)); + } + + @Test + public void validateTraceLogWithExceptionAndPartialParamsAndDebugLevelDisabled() { + final String msg = "Debug message"; + when(logger.isTraceEnabled()).thenReturn(true); + commonLogger.trace(msg, new RuntimeException()); + + verify(logger).trace(any(Marker.class), eq(msg), any(RuntimeException.class)); + } + + @Test + public void warnMessageWithParameterIsNotLoggedIfWarnLevelIsDisabled() { + commonLogger.warn("msg", "param"); + verify(logger, times(0)).warn(any(Marker.class), + anyString(), any(Object.class)); + } + + @Test + public void verifyMdcValuesAreStoredWhenAuditAndErrorLoggersAreInvokedSequentially() throws URISyntaxException { + final String uuid = "12345"; + final String messageInt = "message"; + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(logger.isErrorEnabled()).thenReturn(true); + + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + when(statusType.getStatusCode()).thenReturn(200); + when(statusType.getReasonPhrase()).thenReturn("OK"); + LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); + LoggingThreadLocalsHolder.setUuid(uuid); + audit.startLog(requestContext); + audit.logExit("abc.log.com", requestContext, statusType, LogLevel.INFO, Severity.OK, messageInt, + MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); + + commonLogger.error(messageInt); + verify(logger).error(any(Marker.class), eq(messageInt), any(Object[].class)); + assertEquals(uuid, MDC.get(REQUEST_ID)); + assertEquals("/", MDC.get(SERVICE_NAME)); + assertEquals(LogLevel.ERROR.name(), MDC.get(MDC_ERROR_CATEGORY)); + assertEquals(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode()), MDC.get(MDC_ERROR_CODE)); + } + + @Test + public void verifyLoggerDoesNothingWhenTheLevelIsNotSet() { + if (commonLogger.isDebugEnabled()) { + commonLogger.debug("text"); + } + verify(logger, times(0)).debug(any(Marker.class), anyString(), eq((Object[])null)); + } + + @Test + public void verifyLoggerTraceMethodIsCalledWhenTheLevelIsSet() { + LoggingThreadLocalsHolder.setUuid("1234"); + when(logger.isTraceEnabled()).thenReturn(true); + if (commonLogger.isTraceEnabled()) { + commonLogger.trace("text"); + } + verify(logger, times(1)).trace(any(Marker.class), anyString(), eq((Object[])null)); + } + + + @Test + public void verifyMdcValuesAreStoredWhenTraceLoggerIsInvokedAfterAuditStart() throws URISyntaxException { + final String uuid = "12345"; + final String messageInt = "message"; + when(requestContext.getHeaderString(anyString())).thenReturn("ab2222"); + when(requestContext.getUriInfo()).thenReturn(uriInfo); + when(logger.isTraceEnabled()).thenReturn(true); + + URI uri = new URI("http:/abc.com/getId"); + when(uriInfo.getRequestUri()).thenReturn(uri); + when(uriInfo.getBaseUri()).thenReturn(uri); + LoggerSdcAudit audit = new LoggerSdcAudit(this.getClass()); + LoggingThreadLocalsHolder.setUuid(uuid); + audit.startLog(requestContext); + + commonLogger.trace(messageInt); + verify(logger).trace(any(Marker.class), captor.capture(), eq((Object[])null)); + assertEquals(messageInt, captor.getValue()); + assertEquals(uuid, MDC.get(REQUEST_ID)); + } + + +} |