diff options
author | O'Connor, Lina (lo8949) <lo8949@us.att.com> | 2020-03-11 13:36:42 -0600 |
---|---|---|
committer | O'Connor, Lina (lo8949) <lo8949@us.att.com> | 2020-03-11 13:39:55 -0600 |
commit | e062d90200373473b21b42b8b5f0d8ae18155494 (patch) | |
tree | 1b7cee491f06c44c9d91420c40e271b99403c0cb /aai-els-onap-logging/src/test/java | |
parent | ed992e01c17d5677dfa0e1d0a76a7f9bc12c2a90 (diff) |
Increase code coverage on aai-common: aai-els-onap-logging library
Added Junits
Issue-ID: AAI-2832
Change-Id: I68e11f67b4c16660707bc12de3c14df15145b2b7
Signed-off-by: O'Connor, Lina (lo8949) <lo8949@us.att.com>
Diffstat (limited to 'aai-els-onap-logging/src/test/java')
32 files changed, 3033 insertions, 0 deletions
diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java new file mode 100644 index 00000000..5f23e668 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/AaiAuditLogContainerFilterTest.java @@ -0,0 +1,85 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.aailog.filter; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class AaiAuditLogContainerFilterTest { + @Mock + private ContainerRequestContext containerRequest; + + @Mock + private ContainerResponseContext containerResponse; + + @Mock + private UriInfo uriInfo; + + @Spy + @InjectMocks + private AaiAuditLogContainerFilter aaiAuditFilter; + + @After + public void tearDown() { + MDC.clear(); + } + @Test + public void partnerAndServiceNameValueTest() throws java.net.URISyntaxException { + + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(Constants.HttpHeaders.HEADER_FROM_APP_ID, "FROM_APP_ID_TEST"); + when(containerRequest.getHeaders()).thenReturn(headerMap); + + URI uri = null; + try { + uri = new URI("https://localhost:9999/onap/aai/network/logical-link"); + } + catch (java.net.URISyntaxException e) { + throw e; + } + when(uriInfo.getAbsolutePath()).thenReturn(uri); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + + aaiAuditFilter.filter(containerRequest); + assertEquals("FROM_APP_ID_TEST", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertEquals("/onap/aai/network/logical-link", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + } + +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java new file mode 100644 index 00000000..601a13be --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestClientLoggingInterceptorTest.java @@ -0,0 +1,106 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.aailog.filter; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRequest; + +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class RestClientLoggingInterceptorTest { + + @Mock + private HttpRequest httpRequest; + + @Spy + @InjectMocks + private RestClientLoggingInterceptor restClientLoggingInterceptor; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() { + String transId="37b3ab2a-e57e-4fe8-8d8f-eee3019efce6"; + HttpHeaders headers = new HttpHeaders(); + headers.add(Constants.HttpHeaders.TRANSACTION_ID, transId); + restClientLoggingInterceptor.setupHeaders(httpRequest, headers); + + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + assertEquals(transId, headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + } + + @Test + public void getServiceNameTest() throws URISyntaxException { + URI uri = null; + try { + uri = new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"); + } catch (URISyntaxException e) { + throw e; + } + doReturn(uri).when(httpRequest).getURI(); + String serviceName = restClientLoggingInterceptor.getServiceName(httpRequest); + + assertEquals("/aai/v1/cloud-infrastructure/complexes", serviceName); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + URI uri = new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"); + doReturn(uri).when(httpRequest).getURI(); + HttpHeaders headers = new HttpHeaders(); + restClientLoggingInterceptor.pre(httpRequest, headers); + assertEquals("/aai/v1/cloud-infrastructure/complexes", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME) ); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + String serverFQDN = ""; + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.getCanonicalHostName(); + + } catch (UnknownHostException e) { + serverFQDN = ""; + } + assertEquals(serverFQDN, MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + assertNotNull(headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java new file mode 100644 index 00000000..48cb3efc --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/aailog/filter/RestControllerClientLoggingInterceptorTest.java @@ -0,0 +1,107 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.aailog.filter; + +import com.sun.jersey.api.client.ClientRequest; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.net.InetAddress; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; + +@RunWith(MockitoJUnitRunner.class) +public class RestControllerClientLoggingInterceptorTest { + + private ClientRequest clientRequest; + + @Spy + @InjectMocks + private RestControllerClientLoggingInterceptor restControllerClientLoggingInterceptor; + + @Before + public void init() throws URISyntaxException { + System.setProperty("javax.ws.rs.ext.RuntimeDelegate", "com.sun.ws.rs.ext.RuntimeDelegateImpl"); + clientRequest = ClientRequest.create().build(new URI("https://localhost:9999/aai/v1/cloud-infrastructure/complexes/complex/complex-1"), + "GET"); + } + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() throws java.net.URISyntaxException { + + String transId="37b3ab2a-e57e-4fe8-8d8f-eee3019efce6"; + MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<String, Object>(); + requestHeaders.add(Constants.HttpHeaders.TRANSACTION_ID, transId); + clientRequest.getHeaders().putAll(requestHeaders); + restControllerClientLoggingInterceptor.pre(clientRequest); + MultivaluedMap<String, Object> headers = clientRequest.getHeaders(); + + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + assertEquals(transId, headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals(transId, headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + assertNotNull(headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID)); + } + + @Test + public void getServiceNameTest() { + String serviceName = restControllerClientLoggingInterceptor.getServiceName(clientRequest); + assertEquals("/aai/v1/cloud-infrastructure/complexes", serviceName); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + restControllerClientLoggingInterceptor.pre(clientRequest); + assertEquals("/aai/v1/cloud-infrastructure/complexes", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME) ); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + String serverFQDN = ""; + InetAddress addr = null; + try { + addr = InetAddress.getLocalHost(); + serverFQDN = addr.getCanonicalHostName(); + + } catch (UnknownHostException e) { + serverFQDN = ""; + } + assertEquals(serverFQDN, MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java new file mode 100644 index 00000000..1d19e5bf --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/InfoTest.java @@ -0,0 +1,66 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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========================================================= + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.10.28 at 05:53:17 PM EDT +// + +package org.onap.aai.domain.restResponseInfo; + +import org.junit.Test; + +import java.util.List; + +import static org.junit.Assert.assertTrue; + +public class InfoTest { + private Info info = new Info(); + + @Test + public void infoTest() { + Info.ResponseMessages responseMessages = info.getResponseMessages(); + if (responseMessages == null) responseMessages = new Info.ResponseMessages(); + + List<Info.ResponseMessages.ResponseMessage> list = responseMessages.getResponseMessage(); + Info.ResponseMessages.ResponseMessage respMsg = new Info.ResponseMessages.ResponseMessage(); + + respMsg.setMessageId("1"); + respMsg.setText("textValue"); + + Info.ResponseMessages.ResponseMessage.Variables vars = new Info.ResponseMessages.ResponseMessage.Variables(); + vars.getVariable().add("var1"); + vars.getVariable().add("var2"); + + respMsg.setVariables(vars); + list.add(respMsg); + info.setResponseMessages(responseMessages); + + Info.ResponseMessages responseMessages1 = info.getResponseMessages(); + List<Info.ResponseMessages.ResponseMessage> list1 = responseMessages1.getResponseMessage(); + Info.ResponseMessages.ResponseMessage respMsg1 = list1.get(0); + assertTrue(respMsg1.getMessageId().equals("1")); + assertTrue(respMsg1.getText().equals("textValue")); + assertTrue(respMsg1.getVariables().getVariable().contains("var1")); + assertTrue(respMsg1.getVariables().getVariable().contains("var2")); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java new file mode 100644 index 00000000..55205794 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/domain/restResponseInfo/ObjectFactoryTest.java @@ -0,0 +1,49 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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========================================================= + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.10.28 at 05:53:17 PM EDT +// + +package org.onap.aai.domain.restResponseInfo; + +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; + +public class ObjectFactoryTest { + private ObjectFactory objectFactory = new ObjectFactory(); + + @Test + public void objectFactoryTest() { + Info.ResponseMessages.ResponseMessage.Variables variables = objectFactory.createInfoResponseMessagesResponseMessageVariables(); + Info.ResponseMessages.ResponseMessage responseMessage = objectFactory.createInfoResponseMessagesResponseMessage(); + Info.ResponseMessages responseMessages = objectFactory.createInfoResponseMessages(); + Info info = objectFactory.createInfo(); + + assertNotNull(variables); + assertNotNull(responseMessage); + assertNotNull(responseMessages); + assertNotNull(info); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java new file mode 100644 index 00000000..4f08607f --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionTest.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.exceptions; + +import org.junit.Test; +import org.onap.aai.logging.AaiElsErrorCode; +import org.onap.aai.logging.ErrorObject; + +import javax.ws.rs.core.Response; +import java.io.IOException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class AAIExceptionTest { + private AAIException aaiException; + + @Test + public void defaultAAIExceptionTest() { + //AAI_4000=5:4:ERROR:4000:500:3002:Internal Error:900 + aaiException = new AAIException(); + assertEquals(AAIException.DEFAULT_EXCEPTION_CODE, aaiException.getCode()); + + ErrorObject errorObject = aaiException.getErrorObject(); + assertEquals(errorObject.getCategory(), "4"); + assertEquals(errorObject.getDisposition(), "5"); + assertEquals(errorObject.getSeverity(), "ERROR"); + assertEquals(errorObject.getHTTPResponseCode(), Response.Status.INTERNAL_SERVER_ERROR); + assertEquals(errorObject.getRESTErrorCode(), "3002"); + assertEquals(errorObject.getErrorCode(), "4000"); + assertEquals(errorObject.getAaiElsErrorCode(), AaiElsErrorCode.UNKNOWN_ERROR); + assertEquals(errorObject.getErrorText(), "Internal Error"); + + } + + @Test + public void aaiExceptionTest() { + //5:1:WARN:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry:500 + aaiException = new AAIException("AAI_3303"); + assertEquals("AAI_3303", aaiException.getCode()); + + ErrorObject errorObject = aaiException.getErrorObject(); + assertEquals(errorObject.getCategory(), "1"); + assertEquals(errorObject.getDisposition(), "5"); + assertEquals(errorObject.getSeverity(), "WARN"); + assertEquals(errorObject.getHTTPResponseCode(), Response.Status.FORBIDDEN); + assertEquals(errorObject.getRESTErrorCode(), "3300"); + assertEquals(errorObject.getErrorCode(), "3303"); + assertEquals(errorObject.getAaiElsErrorCode(), AaiElsErrorCode.BUSINESS_PROCESS_ERROR); + assertEquals(errorObject.getErrorText(), "Too many objects would be returned by this request, please refine your request and retry"); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithDetails() { + //5:1:WARN:3303:403:3300:Too many objects would be returned by this request, please refine your request and retry:500 + final String testDetails = "Test details"; + aaiException = new AAIException("AAI_3303", testDetails); + assertEquals(testDetails, aaiException.getMessage()); + assertEquals(testDetails, aaiException.getErrorObject().getDetails()); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithCause() { + aaiException = new AAIException("AAI_3303", new IOException("File not found")); + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + assertNotNull(aaiException.getTemplateVars()); + } + + @Test + public void aaiExceptionTestWithCauseDetails() { + final String testFileName = "TestFileName"; + aaiException = new AAIException("AAI_3303", new IOException("File not found"), testFileName); + + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + assertEquals(testFileName, aaiException.getMessage()); + assertNotNull(aaiException.getTemplateVars()); + } +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java new file mode 100644 index 00000000..dbfe60d5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/exceptions/AAIExceptionWithInfoTest.java @@ -0,0 +1,79 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.exceptions; + +import org.junit.Test; + +import java.io.IOException; +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +public class AAIExceptionWithInfoTest { + + private AAIExceptionWithInfo aaiException; + private static final String testInfo = "Test Info"; + private static final String testDetails = "Test Details"; + + @Test + public void aaiExceptionWithInfoTest() { + + aaiException = new AAIExceptionWithInfo(new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeInfoTest() { + aaiException = new AAIExceptionWithInfo("AAI_3300", new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeDetailsInfoTest() { + + aaiException = new AAIExceptionWithInfo("AAI_3300", testDetails, new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertEquals(testDetails, aaiException.getMessage()); + assertNotNull(aaiException.getInfoHash()); + } + + @Test + public void aaiExceptionWithCodeThrowableDetailsInfoTest() { + + aaiException = new AAIExceptionWithInfo("AAI_3300", new IOException("File not found"), testDetails, new HashMap<String, Object>(), testInfo ); + + assertEquals(testInfo, aaiException.getInfo()); + assertEquals("AAI_3300", aaiException.getCode()); + assertEquals(testDetails, aaiException.getMessage()); + assertNotNull(aaiException.getInfoHash()); + Throwable t = aaiException.getCause(); + assertEquals("java.io.IOException: File not found", t.toString()); + } + +} + diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java new file mode 100644 index 00000000..01b7bda1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CNNameTest.java @@ -0,0 +1,108 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.mock.web.MockHttpServletRequest; + +import javax.security.auth.x500.X500Principal; +import java.security.cert.X509Certificate; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class CNNameTest { + @Mock + X509Certificate cert; + + @Mock + IAccessEvent accessEvent; + + @Spy + @InjectMocks + private CNName cnName; + + @Before + public void setup() { + when(cnName.isStarted()).thenReturn(true); + } + @Test + public void basicAuthTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("user", cnName.convert(accessEvent)); + + } + @Test + public void incorrectHeaderBasicAuthTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.addHeader("Authorization", "dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("-", cnName.convert(accessEvent)); + + } + @Test + public void noCipherSuiteTest(){ + + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.addHeader("Authorization", "Basic dXNlcjpwYXNzd29yZA=="); + https.setAttribute("javax.servlet.request.cipher_suite", null); + https.setAttribute("javax.servlet.request.X509Certificate", null); + + when(accessEvent.getRequest()).thenReturn(https); + assertEquals("-", cnName.convert(accessEvent)); + + } + @Test + public void certificateTest(){ + String testSubject = "CN=TestName, OU=TestOU, O=TestOrg, C=Country"; + X509Certificate[] certChain = { cert }; + MockHttpServletRequest https = new MockHttpServletRequest(); + + https.setAttribute("javax.servlet.request.cipher_suite", ""); + https.setAttribute("javax.servlet.request.X509Certificate", certChain ); + + when(accessEvent.getRequest()).thenReturn(https); + when(cert.getSubjectX500Principal()).thenReturn(new X500Principal(testSubject) ); + + assertEquals(testSubject, cnName.convert(accessEvent)); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java new file mode 100644 index 00000000..71a07aa1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java @@ -0,0 +1,38 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CustomLogPatternLayoutTest { + + private CustomLogPatternLayout customLogPatternLayout = new CustomLogPatternLayout(); + + @Test + public void defaultConverterTest(){ + + assertEquals(customLogPatternLayout.getDefaultConverterMap().get("z"), CNName.class.getName()); + assertEquals(customLogPatternLayout.getDefaultConverterMap().get("y"), DME2RestFlag.class.getName()); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java new file mode 100644 index 00000000..737cb624 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java @@ -0,0 +1,67 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class DME2RestFlagTest { + + @Mock + IAccessEvent accessEvent; + + @Spy + @InjectMocks + private DME2RestFlag dme2RestFlag; + + @Before + public void setup() { + when(dme2RestFlag.isStarted()).thenReturn(true); + } + @Test + public void dme2Test(){ + String[] contextArray = {"a", "b", "c"}; + String[] routeOfferArray = {"d", "e", "f"}; + String[] versionArray = {"1", "2", "3"}; + when(accessEvent.getRequestParameter("envContext")).thenReturn(contextArray); + when(accessEvent.getRequestParameter("routeOffer")).thenReturn(routeOfferArray); + when(accessEvent.getRequestParameter("version")).thenReturn(versionArray); + assertEquals("DME2", dme2RestFlag.convert(accessEvent)); + } + @Test + public void restTest(){ + String[] contextArray = {""}; + String[] routeOfferArray = {""}; + String[] versionArray = {""}; + when(accessEvent.getRequestParameter("envContext")).thenReturn(contextArray); + assertEquals("REST", dme2RestFlag.convert(accessEvent)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java new file mode 100644 index 00000000..ae174691 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorLogHelperTest.java @@ -0,0 +1,151 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.domain.restPolicyException.PolicyException; +import org.onap.aai.domain.restPolicyException.RESTResponse; +import org.onap.aai.domain.restPolicyException.RequestError; +import org.onap.aai.domain.restServiceException.ServiceException; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.util.LogFile; +import org.onap.aai.util.MapperUtil; +import org.slf4j.MDC; + +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static java.lang.Thread.sleep; +import static org.junit.Assert.*; + +public class ErrorLogHelperTest { + + private static final String ErrorLogFileName = "error.log"; + + @Before + public void init() { + System.setProperty("AJSC_HOME", "."); + + } + @After + public void cleanup() throws IOException{ + MDC.clear(); + LogFile.deleteContents(ErrorLogFileName); + } + @Test + public void logErrorTest() throws IOException, InterruptedException { + //||main|UNKNOWN||||ERROR|500|Node cannot be deleted:3100:Bad Request:|ERR.5.4.6110 + ErrorLogHelper.logError("AAI_6110"); + sleep(5000); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertEquals ("ERROR", logContentParts[7]); + assertEquals (AaiElsErrorCode.BUSINESS_PROCESS_ERROR, logContentParts[8]); + assertTrue (logContentParts[10].startsWith("ERR.5.4.6110")); + } + + @Test + public void logErrorWithMessageTest() throws IOException, InterruptedException { + //||main|UNKNOWN||||ERROR|500|Node cannot be deleted:3100:Bad Request:|ERR.5.4.6110 message + String errorMessage = "Object is referenced by additional objects"; + ErrorLogHelper.logError("AAI_6110", errorMessage); + sleep(5000); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertTrue (logContentParts[9].contains(errorMessage)); + assertTrue (logContentParts[10].startsWith("ERR.5.4.6110")); + } + + @Test + public void getRESTAPIPolicyErrorResponseTest() throws AAIException{ + //AAI_3002=5:1:WARN:3002:400:3002:Error writing output performing %1 on %2:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(Arrays.asList("PUT", "resource")); + + AAIException aaie = new AAIException("AAI_3002"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponse(headers, aaie, args); + assertNotNull(errorResponse); + + RESTResponse resp = MapperUtil.readAsObjectOf(RESTResponse.class, errorResponse); + RequestError requestError = resp.getRequestError(); + assertNotNull(requestError); + PolicyException policyException = requestError.getPolicyException(); + assertNotNull(policyException); + assertEquals("POL3002", policyException.getMessageId()); + + List<String> vars = policyException.getVariables(); + assertTrue(vars.contains("PUT")); + assertTrue(vars.contains("resource")); + } + @Test + public void getRESTAPIServiceErrorResponseTest() throws AAIException{ + //AAI_3009=5:6:WARN:3009:400:3009:Malformed URL:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(); + + AAIException aaie = new AAIException("AAI_3009"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponse(headers, aaie, args); + assertNotNull(errorResponse); + + org.onap.aai.domain.restServiceException.RESTResponse resp = MapperUtil.readAsObjectOf(org.onap.aai.domain.restServiceException.RESTResponse.class, errorResponse); + org.onap.aai.domain.restServiceException.RequestError requestError = resp.getRequestError(); + assertNotNull(requestError); + ServiceException serviceException = requestError.getServiceException(); + assertNotNull(serviceException); + assertEquals("SVC3009", serviceException.getMessageId()); + + } + @Test + public void getRESTAPIServiceErrorResponseWithLoggingTest() throws IOException, InterruptedException{ + //AAI_3009=5:6:WARN:3009:400:3009:Malformed URL:300 + ArrayList<MediaType> headers = new ArrayList<MediaType>(Arrays.asList(MediaType.APPLICATION_JSON_TYPE)); + ArrayList<String> args = new ArrayList<String>(); + + AAIException aaie = new AAIException("AAI_3009"); + String errorResponse = ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers, aaie, args); + sleep(5000); + assertNotNull(errorResponse); + String logContents = LogFile.getContents(ErrorLogFileName); + + assertNotNull(logContents); + String logContentParts[] = logContents.split("\\|"); + + assertTrue(logContentParts.length >= 11 ); + assertTrue (logContentParts[10].startsWith("ERR.5.6.3009")); + + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java new file mode 100644 index 00000000..a5a8e496 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectFormatExceptionTest.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class ErrorObjectFormatExceptionTest { + + @Test + public void errorObjectFormatExceptionTest() { + ErrorObjectFormatException e = new ErrorObjectFormatException(); + assertTrue(e instanceof Exception); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java new file mode 100644 index 00000000..8bffe4ff --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectNotFoundExceptionTest.java @@ -0,0 +1,100 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.*; + +public class ErrorObjectNotFoundExceptionTest { + + @Test + public void defaultExceptionTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException(); + assertTrue(e instanceof Exception); + } + @Test + public void errorObjectNotFoundExceptionWithMessageTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message"); + assertTrue(e instanceof Exception); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void errorObjectNotFoundExceptionWithCauseTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException(new ArithmeticException()); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + } + @Test + public void errorObjectNotFoundExceptionWithMsgCauseTest() { + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message", new ArithmeticException()); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void errorObjectNotFoundExceptionTest() { + + ErrorObjectNotFoundException e = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, true); + assertTrue(e instanceof Exception); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + e.addSuppressed(new IOException("Test IO Exception")); + assertTrue((e.getSuppressed())[0] instanceof IOException); + assertEquals("Test IO Exception", (e.getSuppressed())[0].getMessage()); + + ErrorObjectNotFoundException e1 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), false, true); + e1.addSuppressed(new IOException("Test IO Exception")); + assertTrue((e1.getSuppressed() == null) || e1.getSuppressed().length == 0); + + } + + @Test + public void errorObjectNotFoundExceptionStackTraceTest() { + + ErrorObjectNotFoundException e1 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, true); + try { + throw e1; + } + catch (ErrorObjectNotFoundException e) { + StackTraceElement[] stackTrace = e.getStackTrace(); + assertNotNull(stackTrace); + assertTrue(stackTrace.length > 0); + } + + ErrorObjectNotFoundException e2 = new ErrorObjectNotFoundException("Error Message", new ArithmeticException(), true, false); + try { + throw e2; + } + catch (ErrorObjectNotFoundException e) { + StackTraceElement[] stackTrace = e.getStackTrace(); + assertTrue(stackTrace == null || stackTrace.length == 0); + } + + } + /*public ErrorObjectNotFoundException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + // TODO Auto-generated constructor stub + }*/ +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java new file mode 100644 index 00000000..ff20105c --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/ErrorObjectTest.java @@ -0,0 +1,95 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; + +import javax.ws.rs.core.Response; + +import static org.junit.Assert.assertEquals; + +public class ErrorObjectTest { + private ErrorObject errorObject; + private static final String ERROR_DISPOSITION = "5"; + private static final String ERROR_SEVERITY = "ERROR"; + private static final String ERROR_CATEGORY = "4"; + private static final Integer ERROR_HTTP_RESPONSE_CODE = new Integer(401); + private static final String ERROR_REST_CODE = "3300"; + private static final String ERROR_CODE = "4000"; + private static final String ERROR_TEXT = "Test data error"; + private static final String ERROR_PATTERN = "ERR.5.4.4000"; + private static final String ERROR_SEVERITY_CODE = "2"; + @Test + public void errorObjectDefaultConstructorTest() { + errorObject = new ErrorObject(); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(Response.Status.fromStatusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), errorObject.getHTTPResponseCode()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + @Test + public void errorObjectConstructor7Test() { + errorObject = new ErrorObject(ERROR_DISPOSITION, ERROR_CATEGORY, ERROR_SEVERITY, ERROR_HTTP_RESPONSE_CODE, + ERROR_REST_CODE, ERROR_CODE, ERROR_TEXT); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(ERROR_HTTP_RESPONSE_CODE), errorObject.getHTTPResponseCode()); + assertEquals(ERROR_REST_CODE, errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + + @Test + public void errorObjectConstructor5Test() { + errorObject = new ErrorObject(ERROR_SEVERITY, ERROR_CODE, ERROR_TEXT, ERROR_DISPOSITION, ERROR_CATEGORY); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()), errorObject.getHTTPResponseCode()); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR,errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_PATTERN, errorObject.getErrorCodeString()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + } + + @Test + public void errorObjectConstructor6Test() { + errorObject = new ErrorObject(ERROR_SEVERITY, ERROR_HTTP_RESPONSE_CODE, ERROR_CODE, ERROR_TEXT, ERROR_DISPOSITION, ERROR_CATEGORY); + assertEquals(ERROR_DISPOSITION, errorObject.getDisposition()); + assertEquals(ERROR_SEVERITY, errorObject.getSeverity()); + assertEquals(ERROR_CATEGORY, errorObject.getCategory()); + assertEquals(Response.Status.fromStatusCode(ERROR_HTTP_RESPONSE_CODE), errorObject.getHTTPResponseCode()); + assertEquals("3002", errorObject.getRESTErrorCode()); + assertEquals(ERROR_CODE, errorObject.getErrorCode()); + assertEquals(ERROR_TEXT, errorObject.getErrorText()); + assertEquals(AaiElsErrorCode.UNKNOWN_ERROR, errorObject.getAaiElsErrorCode()); + assertEquals(ERROR_PATTERN, errorObject.getErrorCodeString()); + assertEquals(ERROR_SEVERITY_CODE, errorObject.getSeverityCode(ERROR_SEVERITY)); + + } + + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java new file mode 100644 index 00000000..695d7c08 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LogFormatToolsTest.java @@ -0,0 +1,39 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class LogFormatToolsTest { + + @Test + public void testLogFormatStackTrace() { + AAIException aaiException = new AAIException("AAI_4009", new ArithmeticException()); + + String stackTrace = LogFormatTools.getStackTop(aaiException); + assertTrue(stackTrace.startsWith("root cause=java.lang.ArithmeticException")); + assertFalse(stackTrace.contains("\\n")); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java new file mode 100644 index 00000000..245840bc --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/LoggingContextTest.java @@ -0,0 +1,78 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.MDC; + +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class LoggingContextTest { + + @After + public void cleanup(){ + MDC.clear(); + } + @Test + public void elapsedTimeTest() { + LoggingContext.elapsedTime(300, TimeUnit.MILLISECONDS); + assertEquals(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()), "300"); + LoggingContext.init(); + assertTrue(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()) == null); + } + @Test + public void stopWatchTest() { + LoggingContext.init(); + assertFalse(LoggingContext.isStopWatchStarted()); + + LoggingContext.stopWatchStart(); + assertTrue(LoggingContext.isStopWatchStarted()); + + double elapsedTime = LoggingContext.stopWatchStop(); + assertFalse(LoggingContext.isStopWatchStarted()); + assertTrue(elapsedTime > 0); + } + @Test + public void putClearTest() { + String testServiceName = "TEST-SVC-NAME"; + LoggingContext.put(LoggingContext.LoggingField.SERVICE_NAME.toString(), testServiceName); + assertEquals(testServiceName, MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString())); + + LoggingContext.clear(); + assertTrue(MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString()) == null); + + } + + @Test + public void removeTest() { + String testServiceName = "TEST-SVC-NAME"; + LoggingContext.put(LoggingContext.LoggingField.SERVICE_NAME.toString(), testServiceName); + assertEquals(testServiceName, MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString())); + + LoggingContext.remove(LoggingContext.LoggingField.SERVICE_NAME.toString()); + assertTrue(MDC.get(LoggingContext.LoggingField.SERVICE_NAME.toString()) == null); + + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java new file mode 100644 index 00000000..8a4123f0 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchNotStartedExceptionTest.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class StopWatchNotStartedExceptionTest { + + + @Test + public void stopWatchNotStartedExceptionTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException(); + assertTrue(e instanceof RuntimeException); + } + @Test + public void stopWatchNotStartedExceptionWithMessageTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException("Error Message"); + assertTrue(e instanceof RuntimeException); + assertEquals("Error Message", e.getMessage()); + } + @Test + public void stopWatchNotStartedExceptionWithCauseTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException(new ArithmeticException()); + assertTrue(e instanceof RuntimeException); + assertTrue(e.getCause() instanceof ArithmeticException); + } + @Test + public void stopWatchNotStartedExceptionWithMsgCauseTest() { + StopWatchNotStartedException e = new StopWatchNotStartedException("Error Message", new ArithmeticException()); + assertTrue(e instanceof RuntimeException); + assertTrue(e.getCause() instanceof ArithmeticException); + assertEquals("Error Message", e.getMessage()); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java new file mode 100644 index 00000000..50a2d053 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/logging/StopWatchTest.java @@ -0,0 +1,93 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.logging; + +import org.junit.After; +import org.junit.Test; +import org.slf4j.MDC; + +import static java.lang.Thread.sleep; +import static org.junit.Assert.*; + +public class StopWatchTest { + + @After + public void cleanup() { + MDC.clear(); + } + @Test + public void elapsedTimeTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + assertTrue(Long.parseLong(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())) >= 1000L); + } + @Test + public void elapsedTimeConditionalTest() throws InterruptedException { + StopWatch.conditionalStart(); + sleep(1010); + StopWatch.stopIfStarted(); + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime = Long.parseLong(elapsedTimeStr); + assertTrue(elapsedTime >= 1000L); + } + @Test + public void clearTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + assertNotNull( MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())); + + StopWatch.clear(); + assertNull(MDC.get(LoggingContext.LoggingField.STOP_WATCH_START.toString())); + assertNull(MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString())); + + } + + @Test + public void stopTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.stop(); + + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime1 = Long.parseLong(elapsedTimeStr); + + StopWatch.stopIfStarted(); + elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime2 = Long.parseLong(elapsedTimeStr); + assertTrue(elapsedTime1 == elapsedTime2); + } + + @Test + public void startTest() throws InterruptedException { + StopWatch.start(); + sleep(1010); + StopWatch.conditionalStart(); + StopWatch.stop(); + + String elapsedTimeStr = MDC.get(LoggingContext.LoggingField.ELAPSED_TIME.toString()); + long elapsedTime = Long.parseLong(elapsedTimeStr); + + assertTrue(elapsedTime >= 1000L); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java new file mode 100644 index 00000000..24efee3d --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIApplicationConfigTest.java @@ -0,0 +1,75 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * 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.onap.aai.util; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class AAIApplicationConfigTest { + + @Before + public void setup() { + AAIApplicationConfig.init(); + } + + @Test + public void truststoreTest() throws AAIException { + assertEquals("truststore.jks", AAIApplicationConfig.getTruststore()); + } + @Test + public void keystoreTest() throws AAIException { + assertEquals("keystore.jks", AAIApplicationConfig.getKeystore()); + } + + @Test + public void getKeystorePkcs12Test() throws AAIException { + assertEquals("keystore.pkcs12", AAIApplicationConfig.getKeystorePkcs12()); + } + + @Test + public void getValueWithDefaultTest() throws AAIException { + assertEquals("default-value", AAIApplicationConfig.get("non-existing-key", "default-value")); + } + + @Test + public void getValueTest() throws AAIException { + assertEquals("certificates", AAIApplicationConfig.get("server.certs.location")); + } + @Test + public void getIntValueTest() throws AAIException { + assertTrue(8446 == AAIApplicationConfig.getInt("server.port")); + } + + @Test + public void getIntValueWithDefaultTest() throws AAIException { + assertTrue(9999 == AAIApplicationConfig.getInt("non-existing-key", "9999")); + } + + @Test + public void getValueWithReplacementTest() throws AAIException { + assertEquals("/opt/app/aai/etc/auth/aai-client-cert.p12", AAIApplicationConfig.get("schema.service.ssl.key-store")); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java new file mode 100644 index 00000000..86d6c202 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/AAIConfigTest.java @@ -0,0 +1,74 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * 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.onap.aai.util; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.*; + +public class AAIConfigTest { + + @Before + public void setup() throws AAIException { + AAIConfig.init(); + } + + @Test + public void getValueWithDefaultTest() throws AAIException { + assertEquals("default-value", AAIConfig.get("non-existing-key", "default-value")); + } + + @Test + public void getValueTest() throws AAIException { + assertEquals("10", AAIConfig.get("aai.logging.maxStackTraceEntries")); + } + @Test + public void getIntValueTest() throws AAIException { + assertTrue(10 == AAIConfig.getInt("aai.logging.maxStackTraceEntries")); + } + + @Test + public void getIntValueWithDefaultTest() throws AAIException { + assertTrue(9999 == AAIConfig.getInt("non-existing-key", "9999")); + } + + @Test + public void getNodeNameTest() throws AAIException { + assertNotNull(AAIConfig.getNodeName()); + } + + @Test + public void notEmptyTest() throws AAIException { + String value = "test"; + assertFalse(AAIConfig.isEmpty(value)); + } + + @Test + public void emptyTest() throws AAIException { + String value = null; + assertTrue(AAIConfig.isEmpty(value)); + value = ""; + assertTrue(AAIConfig.isEmpty(value)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java new file mode 100644 index 00000000..38ac5de5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/FormatDateTest.java @@ -0,0 +1,40 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright © 2018 IBM. + * ================================================================================ + * 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.onap.aai.util; + +import org.junit.Test; +import org.onap.aai.exceptions.AAIException; + +import static org.junit.Assert.assertNotNull; + +public class FormatDateTest { + private FormatDate formatDate = null; + + @Test + public void formatDateTest() throws AAIException { + formatDate = new FormatDate("yyyy-MM-dd HH:mm:ss.SSS"); + String dateTime = formatDate.getDateTime(); + assertNotNull(dateTime); + dateTime.matches("^\\d\\d\\d\\d-[0-1][0-9]-[0-2][0-9] [0-5][0-9]:[0-5][0-9]:[0-5][0-9].\\d\\d\\d$"); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java b/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java new file mode 100644 index 00000000..682f667b --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/aai/util/LogFile.java @@ -0,0 +1,51 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 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.onap.aai.util; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.Charset; + +/** + * Utility class to read/delete contents of log file + */ +public class LogFile { + + public static String getContents(String fileName) throws IOException { + + FileInputStream fileInputStream = null; + String contents = null; + try { + fileInputStream = new FileInputStream("logs/" + fileName); + contents = IOUtils.toString(fileInputStream, "UTF-8"); + } + finally { + if (fileInputStream != null) fileInputStream.close(); + } + return contents; + } + public static void deleteContents(String fileName) throws IOException { + FileUtils.write(new File("logs/" + fileName), "", Charset.defaultCharset()); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java new file mode 100644 index 00000000..119bdf1e --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogContainerFilterTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class AuditLogContainerFilterTest { + protected static final Logger logger = LoggerFactory.getLogger(AbstractMetricLogFilter.class); + + @Mock + private ContainerRequestContext containerRequest; + + @Mock + private ContainerResponseContext containerResponse; + + @Mock + private UriInfo uriInfo; + + @Spy + @InjectMocks + private AuditLogContainerFilter auditLogContainerFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + + @Test + public void filterTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.REQUEST_ID, "e3b08fa3-535f-4c1b-8228-91318d2bb4ee"); + when(containerRequest.getHeaders()).thenReturn(headerMap); + when(uriInfo.getPath()).thenReturn("onap/so/serviceInstances"); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + auditLogContainerFilter.filter(containerRequest); + + assertEquals("e3b08fa3-535f-4c1b-8228-91318d2bb4ee", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void getResponseCodeTest() { + when(containerResponse.getStatus()).thenReturn(200); + int responseCode = auditLogContainerFilter.getResponseCode(containerResponse); + + assertEquals(200, responseCode); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java new file mode 100644 index 00000000..d3f0f9f5 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/AuditLogServletFilterTest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class AuditLogServletFilterTest { + + @Mock + private ServletRequest request; + + @Mock + private ServletResponse response; + + @Mock + private HttpServletRequest servletRequest; + + @Mock + private HttpServletResponse servletResponse; + + @Spy + @InjectMocks + private AuditLogServletFilter auditLogServletFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void preTest() { + when(servletRequest.getRequestURI()).thenReturn("onap/so/serviceInstances"); + auditLogServletFilter.pre(servletRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + + } + + @Test + public void getResponseCodeTest() { + when(servletResponse.getStatus()).thenReturn(200); + int responseCode = auditLogServletFilter.getResponseCode(servletResponse); + + assertEquals(200, responseCode); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java new file mode 100644 index 00000000..4d1f102a --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/LoggingContainerFilterTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; + +public class LoggingContainerFilterTest { + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + + @Test + public void convertMultivaluedMapToHashMap() { + MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); + headers.add(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + SimpleMap result = new SimpleJaxrsHeadersMap(headers); + assertEquals(invocationId, result.get(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java new file mode 100644 index 00000000..9c89da5a --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MDCSetupTest.java @@ -0,0 +1,279 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; +import java.util.HashMap; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.After; +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.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class MDCSetupTest extends MDCSetup { + + @Mock + private HttpServletRequest httpServletRequest; + + private String requestId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9a"; + + @After + public void tearDown() { + MDC.clear(); + System.clearProperty("partnerName"); + } + + @Test + public void setElapsedTimeTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTime(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setElapsedTimeInvokeTimestampTest() { + String expected = "318"; + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.LOG_TIMESTAMP, "2019-06-18T02:09:06.342Z"); + + setElapsedTimeInvokeTimestamp(); + assertEquals(expected, MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setRequestIdTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdRequestIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.HEADER_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdTransactionIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.TRANSACTION_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setRequestIdEcompRequestIdHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(Constants.HttpHeaders.ECOMP_REQUEST_ID, requestId); + String fetchedRequestId = getRequestId(new SimpleHashMap(headers)); + assertEquals(requestId, fetchedRequestId); + } + + @Test + public void setInvocationIdTest() { + HashMap<String, String> headers = new HashMap<>(); + headers.put(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + setInvocationId(new SimpleHashMap(headers)); + assertEquals(invocationId, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setInvocationIdNoHeaderTest() { + HashMap<String, String> headers = new HashMap<>(); + setInvocationId(new SimpleHashMap(headers)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID)); + } + + @Test + public void setResponseStatusCodeTest() { + setResponseStatusCode(200); + assertEquals("COMPLETE", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void setResponseStatusCodeErrorTest() { + setResponseStatusCode(400); + assertEquals("ERROR", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertEquals("400", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertEquals("Bad Request", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + } + + @Test + public void clearClientMDCsTest() { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, "Bad Gateway"); + MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, "502"); + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, "SDNC"); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + + clearClientMDCs(); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ERROR_DESC)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertNull(MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP)); + } + + @Test + public void setTargetEntityTest() { + setTargetEntity(ONAPComponents.SO); + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + } + + @Test + public void setResponseDescriptionTest() { + setResponseDescription(502); + assertEquals("Bad Gateway", MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION)); + } + + @Test + public void setMDCPartnerNameBearerToken() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + String value = "Bearer some-compex-token"; + headerMap.putSingle(HttpHeaders.AUTHORIZATION, value); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals(Constants.DefaultValues.UNKNOWN, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(ONAPLogConstants.Headers.PARTNER_NAME, "SO"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameUserAgentHeaderTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + headerMap.putSingle(HttpHeaders.USER_AGENT, "Apache-HttpClient/4.5.8 (Java/1.8.0_191)"); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("Apache-HttpClient/4.5.8 (Java/1.8.0_191)", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setMDCPartnerNameNoHeaderTest() { + MultivaluedMap<String, String> headerMap = new MultivaluedHashMap<>(); + SimpleMap headers = new SimpleJaxrsHeadersMap(headerMap); + + setMDCPartnerName(headers); + + assertEquals("UNKNOWN", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + @Test + public void setServerFQDNTest() { + setServerFQDN(); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_IP_ADDRESS)); + assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN)); + } + + @Test + public void setClientIPAddressTest() { + when(httpServletRequest.getHeader("X-Forwarded-For")).thenReturn("127.0.0.2"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.2", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNoHeaderTest() { + when(httpServletRequest.getRemoteAddr()).thenReturn("127.0.0.1"); + setClientIPAddress(httpServletRequest); + + assertEquals("127.0.0.1", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setClientIPAddressNullTest() { + setClientIPAddress(null); + + assertEquals("", MDC.get(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS)); + } + + @Test + public void setEntryTimeStampTest() { + setEntryTimeStamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + } + + @Test + public void setLogTimestampTest() { + setLogTimestamp(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP)); + } + + @Test + public void setInstanceIDTest() { + setInstanceID(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); + } + + @Test + public void getPropertyTest() { + System.setProperty("partnerName", "partnerName"); + + String partnerName = getProperty("partnerName"); + assertEquals("partnerName", partnerName); + } + + @Test + public void getPropertyNullTest() { + String partnerName = getProperty("partner"); + assertEquals(null, partnerName); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java new file mode 100644 index 00000000..6f6a0ff1 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/MetricLogClientFilterTest.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.slf4j.MDC; + +@RunWith(MockitoJUnitRunner.class) +public class MetricLogClientFilterTest { + @Mock + private ClientRequestContext clientRequest; + + @Spy + @InjectMocks + private MetricLogClientFilter metricLogClientFilter; + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupHeadersTest() { + MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); + doReturn("0a908a5d-e774-4558-96ff-6edcbba65483").when(metricLogClientFilter).extractRequestID(); + metricLogClientFilter.setupHeaders(clientRequest, headers); + + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.HEADER_REQUEST_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.TRANSACTION_ID)); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", headers.getFirst(Constants.HttpHeaders.ECOMP_REQUEST_ID)); + } + + @Test + public void setupMDCTest() throws URISyntaxException { + // TODO ingest change from upstream + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, "SO"); + URI uri = new URI("onap/so/serviceInstances"); + doReturn(uri).when(clientRequest).getUri(); + + metricLogClientFilter.setupMDC(clientRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertEquals("SO", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNotNull(ONAPLogConstants.MDCs.SERVICE_NAME); + assertNotNull(ONAPLogConstants.MDCs.SERVER_FQDN); + assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + } + + @Test + public void setupMDCNoTargetEntityTest() throws URISyntaxException { + URI uri = new URI("onap/so/serviceInstances"); + doReturn(uri).when(clientRequest).getUri(); + + metricLogClientFilter.setupMDC(clientRequest); + + assertEquals("onap/so/serviceInstances", MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME)); + assertEquals("Unknown-Target-Entity", MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY)); + assertEquals("INPROGRESS", MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNotNull(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + } + + @Test + public void extractRequestIDTest() { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "0a908a5d-e774-4558-96ff-6edcbba65483"); + String requestId = metricLogClientFilter.extractRequestID(); + assertEquals("0a908a5d-e774-4558-96ff-6edcbba65483", requestId); + } + + @Test + public void extractRequestIDNullTest() throws URISyntaxException { + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String requestId = metricLogClientFilter.extractRequestID(); + assertNotNull(requestId); + assertNotNull(ONAPLogConstants.MDCs.LOG_TIMESTAMP); + assertNotNull(ONAPLogConstants.MDCs.ELAPSED_TIME); + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java new file mode 100644 index 00000000..c2446a3f --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/PayloadLoggingClientFilterTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.net.URISyntaxException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class PayloadLoggingClientFilterTest { + + @Mock + private ClientRequestContext requestContext; + + @Spy + @InjectMocks + private PayloadLoggingClientFilter payloadLoggingClientFilter; + + @Test + public void formatMethodTest() throws IOException, URISyntaxException { + when(requestContext.getHeaderString("X-HTTP-Method-Override")).thenReturn("filter"); + when(requestContext.getMethod()).thenReturn("filtered"); + String method = payloadLoggingClientFilter.formatMethod(requestContext); + + assertEquals("filtered (overridden to filter)", method); + } + + @Test + public void formatMethodNullHeaderTest() throws IOException, URISyntaxException { + when(requestContext.getMethod()).thenReturn("filtered"); + String method = payloadLoggingClientFilter.formatMethod(requestContext); + + assertEquals("filtered", method); + } + + @Test + public void getHeadersTest() { + MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(); + headers.add(Constants.HttpHeaders.ONAP_PARTNER_NAME, "SO"); + headers.add("Authorization", "Test"); + + String printHeaders = payloadLoggingClientFilter.getHeaders(headers); + + assertEquals("{Authorization=[***REDACTED***], X-ONAP-PartnerName=[SO]}", printHeaders); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java new file mode 100644 index 00000000..e2c5da9c --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleJaxrsHeadersMapTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; + +public class SimpleJaxrsHeadersMapTest { + + private String invocationId = "4d31fe02-4918-4975-942f-fe51a44e6a9b"; + + @Test + public void convertMultivaluedMapToHashMap() { + MultivaluedMap<String, String> headers = new MultivaluedHashMap<>(); + headers.add(ONAPLogConstants.Headers.INVOCATION_ID, invocationId); + SimpleMap result = new SimpleJaxrsHeadersMap(headers); + assertEquals(invocationId, result.get(ONAPLogConstants.Headers.INVOCATION_ID)); + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java new file mode 100644 index 00000000..fff67768 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/filter/base/SimpleServletHeadersMapTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - Logging + * ================================================================================ + * Copyright (C) 2019 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.onap.logging.filter.base; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; +import javax.servlet.http.HttpServletRequest; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class SimpleServletHeadersMapTest { + + @Mock + private HttpServletRequest request; + + @Spy + @InjectMocks + private SimpleServletHeadersMap map; + + @Test + public void getTest() { + when(request.getHeader("testHeader")).thenReturn("testResult"); + String result = map.get("testHeader"); + + assertEquals("testResult", result); + } + +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java new file mode 100644 index 00000000..9549eaa9 --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogAdapterTest.java @@ -0,0 +1,437 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; + +import javax.xml.bind.DatatypeConverter; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; +import static org.hamcrest.core.IsSame.sameInstance; +import static org.hamcrest.core.StringEndsWith.endsWith; +import static org.hamcrest.number.OrderingComparison.lessThan; + +/** + * Tests for {@link ONAPLogAdapter}. + */ +public class ONAPLogAdapterTest { + + /** + * Ensure that MDCs are cleared after each testcase. + */ + @AfterMethod + public void resetMDCs() { + MDC.clear(); + } + + /** + * Test nullcheck. + */ + @Test + public void testCheckNotNull() { + + ONAPLogAdapter.checkNotNull(""); + + try { + ONAPLogAdapter.checkNotNull(null); + Assert.fail("Should throw NullPointerException"); + } + catch (final NullPointerException e) { + + } + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToEmpty() { + assertThat(ONAPLogAdapter.defaultToEmpty("123"), is("123")); + assertThat(ONAPLogAdapter.defaultToEmpty(Integer.valueOf(1984)), is("1984")); + assertThat(ONAPLogAdapter.defaultToEmpty(null), is("")); + } + + /** + * Test defaulting of nulls. + */ + @Test + public void testDefaultToUUID() { + assertThat(ONAPLogAdapter.defaultToUUID("123"), is("123")); + UUID.fromString(ONAPLogAdapter.defaultToUUID(null)); + } + + /** + * Test ENTERING. + */ + @Test + public void testEntering() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + http.setRequestURI("uri123"); + http.setServerName("local123"); + http.setRemoteAddr("remote123"); + http.addHeader("X-ONAP-RequestID", "request123"); + http.addHeader("X-InvocationID", "invocation123"); + http.addHeader("X-ONAP-PartnerName", "partner123"); + + try { + adapter.getServiceDescriptor().setServiceName("uri123"); + adapter.entering(http); + final Map<String, String> mdcs = MDC.getCopyOfContextMap(); + assertThat(mdcs.get("RequestID"), is("request123")); + assertThat(mdcs.get("PartnerName"), is("partner123")); + assertThat(mdcs.get("ServiceName"), is("uri123")); + assertThat(mdcs.get("ServerFQDN"), is("local123")); + assertThat(mdcs.get("ClientIPAddress"), is("remote123")); + + // Timestamp format and value: + + final String invokeTimestampString = mdcs.get("InvokeTimestamp"); + assertThat(invokeTimestampString, notNullValue()); + assertThat(invokeTimestampString, endsWith("Z")); + final long invokeTimestamp = DatatypeConverter.parseDateTime(invokeTimestampString).getTimeInMillis(); + assertThat(Math.abs(System.currentTimeMillis() - invokeTimestamp), lessThan(5000L)); + } + finally { + MDC.clear(); + } + } + + /** + * Test ENTERING with an EMPTY_STRING serviceName. + */ + @Test + public void testEnteringWithEMPTY_STRING_serviceName() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + http.setRequestURI("uri123"); + http.setServerName("local123"); + http.setRemoteAddr("remote123"); + http.addHeader("X-ONAP-RequestID", "request123"); + http.addHeader("X-InvocationID", "invocation123"); + http.addHeader("X-ONAP-PartnerName", "partner123"); + + try { + // an empty string should kick in setting the actual service name (treated same as null) + adapter.getServiceDescriptor().setServiceName(""); + adapter.entering(http); + final Map<String, String> mdcs = MDC.getCopyOfContextMap(); + assertThat(mdcs.get("RequestID"), is("request123")); + assertThat(mdcs.get("PartnerName"), is("partner123")); + assertThat(mdcs.get("ServiceName"), is("uri123")); + assertThat(mdcs.get("ServerFQDN"), is("local123")); + assertThat(mdcs.get("ClientIPAddress"), is("remote123")); + + // Timestamp format and value: + + final String invokeTimestampString = mdcs.get("InvokeTimestamp"); + assertThat(invokeTimestampString, notNullValue()); + assertThat(invokeTimestampString, endsWith("Z")); + final long invokeTimestamp = DatatypeConverter.parseDateTime(invokeTimestampString).getTimeInMillis(); + assertThat(Math.abs(System.currentTimeMillis() - invokeTimestamp), lessThan(5000L)); + } + finally { + MDC.clear(); + } + } + + @Test + public void testSetServiceDescriptor() { + final ONAPLogAdapter.ServiceDescriptor override = new ONAPLogAdapter.ServiceDescriptor(); + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final ONAPLogAdapter.ServiceDescriptor before = adapter.getServiceDescriptor(); + adapter.setServiceDescriptor(override); + final ONAPLogAdapter.ServiceDescriptor after = adapter.getServiceDescriptor(); + assertThat(after, not(sameInstance(before))); + assertThat(after, is(override)); + } + + @Test + public void testSetResponseDescriptor() { + final ONAPLogAdapter.ResponseDescriptor override = new ONAPLogAdapter.ResponseDescriptor(); + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final ONAPLogAdapter.ResponseDescriptor before = adapter.getResponseDescriptor(); + adapter.setResponseDescriptor(override); + final ONAPLogAdapter.ResponseDescriptor after = adapter.getResponseDescriptor(); + assertThat(after, not(sameInstance(before))); + assertThat(after, is(override)); + } + + @Test + public void testUnwrap() { + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + assertThat(adapter.unwrap(), is(logger)); + } + + /** + * Test EXITING. + */ + @Test + public void testExiting() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + try { + MDC.put("somekey", "somevalue"); + assertThat(MDC.get("somekey"), is("somevalue")); + adapter.exiting(); + assertThat(MDC.get("somekey"), nullValue()); + } + finally { + MDC.clear(); + } + } + + /** + * Test INVOKE. + */ + @Test + public void testInvokeSyncAsyncNull() { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final UUID syncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(syncUUID, notNullValue()); + + final UUID asyncUUID = adapter.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(asyncUUID, notNullValue()); + + final UUID agnosticUUID = adapter.invoke((ONAPLogConstants.InvocationMode)null); + assertThat(agnosticUUID, notNullValue()); + + } + + /** + * Test INVOKE, with RequestAdapter. + */ + @Test + public void testInvokeWithAdapter() throws Exception { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final Map<String, String> headers = new HashMap<>(); + final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() { + @Override + public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) { + headers.put(name, value); + return this; + } + }; + + try { + final UUID uuid = adapter.invoke(builder, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + assertThat(uuid, notNullValue()); + assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString())); + assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true)); + assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true)); + } + finally { + MDC.clear(); + } + } + + /** + * Test INVOKE, with RequestAdapter. + */ + @Test + public void testInvokeWithAdapterAndNull() throws Exception { + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + + final Map<String, String> headers = new HashMap<>(); + final ONAPLogAdapter.RequestBuilder builder = new ONAPLogAdapter.RequestBuilder<ONAPLogAdapter.RequestBuilder>() { + @Override + public ONAPLogAdapter.RequestBuilder setHeader(final String name, final String value) { + headers.put(name, value); + return this; + } + }; + + try { + final UUID uuid = adapter.invoke(builder); + assertThat(uuid, notNullValue()); + assertThat(headers.get(ONAPLogConstants.Headers.INVOCATION_ID), is(uuid.toString())); + assertThat(headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME), is(true)); + assertThat(headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID), is(true)); + } + finally { + MDC.clear(); + } + } + + @Test + public void testHttpServletRequestAdapter() { + + final UUID uuid = UUID.randomUUID(); + final MockHttpServletRequest request = new MockHttpServletRequest(); + request.addHeader("uuid", uuid.toString()); + request.setRequestURI("/ctx0"); + request.setServerName("srv0"); + + final ONAPLogAdapter.HttpServletRequestAdapter adapter + = new ONAPLogAdapter.HttpServletRequestAdapter(request); + assertThat(adapter.getHeader("uuid"), is(uuid.toString())); + assertThat(adapter.getRequestURI(), is("/ctx0")); + assertThat(adapter.getServerAddress(), is("srv0")); + } + + @Test + public void testServiceDescriptor() { + final String uuid = UUID.randomUUID().toString(); + + final ONAPLogAdapter.ServiceDescriptor adapter + = new ONAPLogAdapter.ServiceDescriptor(); + adapter.setServiceUUID(uuid); + adapter.setServiceName("name0"); + + assertThat(MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID), nullValue()); + + adapter.setMDCs(); + + assertThat(MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME), is("name0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.INSTANCE_UUID), is(uuid)); + } + + @Test + public void testResponseDescriptor() { + final String uuid = UUID.randomUUID().toString(); + + final ONAPLogAdapter.ResponseDescriptor adapter + = new ONAPLogAdapter.ResponseDescriptor(); + adapter.setResponseCode("code0"); + adapter.setResponseDescription("desc0"); + adapter.setResponseSeverity(Level.INFO); + adapter.setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETE); + + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_SEVERITY), nullValue()); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), nullValue()); + + adapter.setMDCs(); + + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_CODE), is("code0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION), is("desc0")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_SEVERITY), is("INFO")); + assertThat(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE), is("COMPLETE")); + } + + /** + * Exercise the contract, for a caller that's happy to have their + * service name automatically derived. (This validates nothing + * and achieves nothing; it's just to provide an example of minimal usage). + */ + @Test + public void testContract() { + + // Note no wrapper around HttpServletRequest, which will work for + // most invocations (since they come via HTTP), but otherwise + // can implement your own RequestAdapter. + + final Logger logger = LoggerFactory.getLogger(this.getClass()); + final ONAPLogAdapter adapter = new ONAPLogAdapter(logger); + final MockHttpServletRequest http = new MockHttpServletRequest(); + + // Immediately log ENTERING marker, with global MDCs. + + adapter.entering(http); + try { + + // Generate (and log) an invocationID, then use it to + // invoke another component. + + final RESTClient client = new RESTClient(); // implements ONAPLogAdapter.RequestBuilder<RESTClient>. + adapter.invoke(client, ONAPLogConstants.InvocationMode.SYNCHRONOUS); + final RESTRequest request = null; // TODO: build real request. + final RESTResponse response = client.execute(request); // TODO: handle real response. + + // Set response details prior to #exiting. + // (Obviously there'd be errorhandling, etc. IRL). + + adapter.getResponseDescriptor() + .setResponseCode((String)null) + .setResponseSeverity(Level.INFO) + .setResponseStatus(ONAPLogConstants.ResponseStatus.COMPLETE); + } + finally { + + // Return, logging EXIT marker, with response MDCs. + + adapter.exiting(); + } + } + + /** + * Dummy class, for example code. + */ + static class RESTClient implements ONAPLogAdapter.RequestBuilder<RESTClient> { + + @Override + public RESTClient setHeader(final String name, final String value) { + return null; + } + + RESTResponse execute(RESTRequest request) { + return null; + } + } + + /** + * Dummy class, for example code. + */ + static class RESTRequest { + + } + + /** + * Dummy class, for example code. + */ + static class RESTResponse { + + } +} diff --git a/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java new file mode 100644 index 00000000..9a46f05b --- /dev/null +++ b/aai-els-onap-logging/src/test/java/org/onap/logging/ref/slf4j/ONAPLogConstantsTest.java @@ -0,0 +1,132 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.logging + * ================================================================================ + * Copyright © 2018 Amdocs + * 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.onap.logging.ref.slf4j; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsInstanceOf.instanceOf; + +/** + * Tests for {@link ONAPLogConstants}. + */ +public class ONAPLogConstantsTest { + + @Test + public void testConstructors() throws Exception { + assertInaccessibleConstructor(ONAPLogConstants.class); + assertInaccessibleConstructor(ONAPLogConstants.MDCs.class); + assertInaccessibleConstructor(ONAPLogConstants.Markers.class); + assertInaccessibleConstructor(ONAPLogConstants.Headers.class); + } + + @Test + public void testConstructorUnsupported() throws Exception { + try { + Constructor<?> c = ONAPLogConstants.class.getDeclaredConstructors()[0]; + c.setAccessible(true); + c.newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final InvocationTargetException e) { + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + } + + @Test + public void testHeaders() { + assertThat(ONAPLogConstants.Headers.REQUEST_ID, is("X-ONAP-RequestID")); + assertThat(ONAPLogConstants.Headers.PARTNER_NAME, is("X-ONAP-PartnerName")); + } + + @Test + public void testMarkers() { + assertThat(ONAPLogConstants.Markers.ENTRY.toString(), is("ENTRY")); + assertThat(ONAPLogConstants.Markers.EXIT.toString(), is("EXIT")); + assertThat(ONAPLogConstants.Markers.INVOKE.toString(), is("INVOKE")); + assertThat(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS.toString(), is("INVOKE [ ASYNCHRONOUS ]")); + assertThat(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS.toString(), is("INVOKE [ SYNCHRONOUS ]")); + } + + @Test + public void testInvocationMode() { + assertThat(ONAPLogConstants.InvocationMode.SYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_SYNCHRONOUS)); + assertThat(ONAPLogConstants.InvocationMode.ASYNCHRONOUS.getMarker(), + is(ONAPLogConstants.Markers.INVOKE_ASYNCHRONOUS)); + } + + @Test + public void testInvocationModeToString() { + assertThat(ONAPLogConstants.InvocationMode.SYNCHRONOUS.toString(), + is("SYNCHRONOUS")); + } + + @Test + public void testResponseStatus() { + assertThat(ONAPLogConstants.ResponseStatus.COMPLETE.toString(), is("COMPLETE")); + assertThat(ONAPLogConstants.ResponseStatus.ERROR.toString(), is("ERROR")); + } + + @Test + public void testMDCs() { + + assertThat(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS.toString(), is("ClientIPAddress")); + assertThat(ONAPLogConstants.MDCs.SERVER_FQDN.toString(), is("ServerFQDN")); + + assertThat(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP.toString(), is("EntryTimestamp")); + assertThat(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP.toString(), is("InvokeTimestamp")); + + assertThat(ONAPLogConstants.MDCs.REQUEST_ID.toString(), is("RequestID")); + assertThat(ONAPLogConstants.MDCs.INVOCATION_ID.toString(), is("InvocationID")); + assertThat(ONAPLogConstants.MDCs.PARTNER_NAME.toString(), is("PartnerName")); + assertThat(ONAPLogConstants.MDCs.INSTANCE_UUID.toString(), is("InstanceID")); + assertThat(ONAPLogConstants.MDCs.SERVICE_NAME.toString(), is("ServiceName")); + assertThat(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME.toString(), is("TargetServiceName")); + + } + + static void assertInaccessibleConstructor(final Class<?> c) throws Exception { + try { + c.getDeclaredConstructors()[0].newInstance(); + Assert.fail("Should fail for hidden constructor."); + } + catch (final IllegalAccessException e) { + + } + + try { + final Constructor<?> constructor = c.getDeclaredConstructors()[0]; + constructor.setAccessible(true); + constructor.newInstance(); + Assert.fail("Should fail even when invoked."); + } + catch (final InvocationTargetException e) { + assertThat(e.getCause(), instanceOf(UnsupportedOperationException.class)); + } + } +} |