aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test
diff options
context:
space:
mode:
authorvempo <vitaliy.emporopulo@amdocs.com>2018-07-31 18:50:14 +0300
committerAvi Gaffa <avi.gaffa@amdocs.com>2018-08-05 12:15:49 +0000
commit1b01b984901d5f69d5e421e459d62a6d03292444 (patch)
tree2e172e9c4ba8b19a286b89d93270629a5b768a89 /openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test
parentd05277df22ddde79458cd853f98e7ab3a4d98913 (diff)
Simplified logging code for servlets
Added and simplified unit tests, organized imports, refactored for simplicity and reuse. Change-Id: I4c4837447329528ae855f2e8d1a1f4b883617f33 Issue-ID: SDC-1580 Signed-off-by: vempo <vitaliy.emporopulo@amdocs.com>
Diffstat (limited to 'openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test')
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/AuditTrackerTest.java153
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ContextTrackerTest.java165
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/HttpHeaderTest.java119
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java206
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatterTest.java43
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/HttpHeaderTest.java97
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilterTest.java244
-rw-r--r--openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilterTest.java302
8 files changed, 516 insertions, 813 deletions
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/AuditTrackerTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/AuditTrackerTest.java
new file mode 100644
index 0000000000..1bd13a9dfd
--- /dev/null
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/AuditTrackerTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
+package org.openecomp.sdc.logging.servlet;
+
+import static junit.framework.TestCase.assertEquals;
+import static junit.framework.TestCase.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import javax.servlet.http.HttpServletRequest;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.openecomp.sdc.logging.api.AuditData;
+import org.openecomp.sdc.logging.api.Logger;
+import org.openecomp.sdc.logging.api.StatusCode;
+
+/**
+ * Test initialization and of audit tracker and log invocation.
+ *
+ * @author evitaliy
+ * @since 01 Aug 2018
+ */
+public class AuditTrackerTest {
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenLoggerNull() {
+ new AuditTracker((Logger) null);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenResourceTypeNull() {
+ new AuditTracker((Class<?>) null);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void throwExceptionWhenPreRequestCalledMoreThanOnce() {
+ AuditTracker tracker = new AuditTracker(mock(Logger.class));
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ tracker.preRequest(request);
+ tracker.preRequest(request);
+ }
+
+ @Test(expected = IllegalStateException.class)
+ public void throwExceptionWhenRreRequestNeverCalled() {
+ AuditTracker tracker = new AuditTracker(mock(Logger.class));
+ tracker.postRequest(mock(RequestProcessingResult.class));
+ }
+
+ @Test
+ public void nothingHappensWhenAuditDisabled() {
+
+ Logger logger = mock(Logger.class);
+ when(logger.isAuditEnabled()).thenReturn(false);
+
+ AuditTracker tracker = new AuditTracker(logger);
+ tracker.preRequest(mock(HttpServletRequest.class));
+ tracker.postRequest(mock(RequestProcessingResult.class));
+
+ verify(logger, never()).audit(any(AuditData.class));
+ }
+
+ @Test
+ public void reportedTimePositive() {
+
+ Logger logger = mock(Logger.class);
+ when(logger.isAuditEnabled()).thenReturn(true);
+
+ AuditTracker tracker = new AuditTracker(logger);
+ tracker.preRequest(mock(HttpServletRequest.class));
+ tracker.postRequest(mock(RequestProcessingResult.class));
+
+ ArgumentCaptor<AuditData> auditDataCaptor = ArgumentCaptor.forClass(AuditData.class);
+ verify(logger).audit(auditDataCaptor.capture());
+ assertTrue(auditDataCaptor.getValue().getEndTime() > 0);
+ }
+
+ @Test
+ public void interpretedRequestResultsPassedDownToAudit() {
+
+ Logger logger = mock(Logger.class);
+ when(logger.isAuditEnabled()).thenReturn(true);
+
+ AuditTracker tracker = new AuditTracker(logger);
+ tracker.preRequest(mock(HttpServletRequest.class));
+
+ final StubRequestProcessingResult result = new StubRequestProcessingResult();
+ tracker.postRequest(result);
+
+ ArgumentCaptor<AuditData> auditDataCaptor = ArgumentCaptor.forClass(AuditData.class);
+ verify(logger).audit(auditDataCaptor.capture());
+
+ AuditData capturedAuditData = auditDataCaptor.getValue();
+ assertEquals(Integer.toString(result.getStatus()), capturedAuditData.getResponseCode());
+ assertEquals(result.getStatusCode(), capturedAuditData.getStatusCode());
+ assertEquals(result.getStatusPhrase(), capturedAuditData.getResponseDescription());
+ }
+
+ @Test
+ public void clientIpAddressPassedDownToAudit() {
+
+ Logger logger = mock(Logger.class);
+ when(logger.isAuditEnabled()).thenReturn(true);
+
+ final String address = "196.50.30.122";
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getRemoteAddr()).thenReturn(address);
+
+ AuditTracker tracker = new AuditTracker(logger);
+ tracker.preRequest(request);
+ tracker.postRequest(mock(RequestProcessingResult.class));
+
+ ArgumentCaptor<AuditData> auditDataCaptor = ArgumentCaptor.forClass(AuditData.class);
+ verify(logger).audit(auditDataCaptor.capture());
+
+ AuditData capturedAuditData = auditDataCaptor.getValue();
+ assertEquals(address, capturedAuditData.getClientIpAddress());
+ }
+
+ private static class StubRequestProcessingResult implements RequestProcessingResult {
+
+ @Override
+ public int getStatus() {
+ return 505;
+ }
+
+ @Override
+ public StatusCode getStatusCode() {
+ return StatusCode.ERROR;
+ }
+
+ @Override
+ public String getStatusPhrase() {
+ return "Test request failed";
+ }
+ }
+} \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ContextTrackerTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ContextTrackerTest.java
new file mode 100644
index 0000000000..a247d119c8
--- /dev/null
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ContextTrackerTest.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
+package org.openecomp.sdc.logging.servlet;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.powermock.api.mockito.PowerMockito.mock;
+import static org.powermock.api.mockito.PowerMockito.mockStatic;
+import static org.powermock.api.mockito.PowerMockito.verifyStatic;
+import static org.powermock.api.mockito.PowerMockito.when;
+
+import javax.servlet.http.HttpServletRequest;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.openecomp.sdc.logging.api.ContextData;
+import org.openecomp.sdc.logging.api.LoggingContext;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+/**
+ * Populating context from request data.
+ *
+ * @author evitaliy
+ * @since 01 Aug 2018
+ */
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(LoggingContext.class)
+public class ContextTrackerTest {
+
+ private static final String X_REQUEST_ID = "X-REQUEST-ID";
+ private static final HttpHeader REQUEST_ID_HEADER = new HttpHeader(new String[] {X_REQUEST_ID});
+
+ private static final String X_PARTNER_NAME = "X-PARTNER-NAME";
+ private static final HttpHeader PARTNER_NAME_HEADER = new HttpHeader(new String[] {X_PARTNER_NAME});
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenPartnerNamesNull() {
+ new ContextTracker(null, REQUEST_ID_HEADER);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenRequestIdsNull() {
+ new ContextTracker(PARTNER_NAME_HEADER, null);
+ }
+
+ @Test
+ public void requestIdCopiedWhenGiven() {
+
+ mockStatic(LoggingContext.class);
+
+ final String requestId = "request-id-for-unit-testing";
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getHeader(X_REQUEST_ID)).thenReturn(requestId);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.preRequest(request);
+
+ ArgumentCaptor<ContextData> contextDataCaptor = ArgumentCaptor.forClass(ContextData.class);
+ verifyStatic(LoggingContext.class);
+
+ LoggingContext.put(contextDataCaptor.capture());
+
+ assertEquals(requestId, contextDataCaptor.getValue().getRequestId());
+ }
+
+ @Test
+ public void requestIdGeneratedWhenNotGiven() {
+
+ mockStatic(LoggingContext.class);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.preRequest(mock(HttpServletRequest.class));
+
+ ArgumentCaptor<ContextData> contextDataCaptor = ArgumentCaptor.forClass(ContextData.class);
+ verifyStatic(LoggingContext.class);
+
+ LoggingContext.put(contextDataCaptor.capture());
+
+ String requestId = contextDataCaptor.getValue().getRequestId();
+ assertNotNull(requestId);
+ assertFalse(requestId.isEmpty());
+ }
+
+ @Test
+ public void partnerNameCopiedWhenGiven() {
+
+ mockStatic(LoggingContext.class);
+
+ final String partner = "partner-name-for-unit-testing";
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getHeader(X_PARTNER_NAME)).thenReturn(partner);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.preRequest(request);
+
+ ArgumentCaptor<ContextData> contextDataCaptor = ArgumentCaptor.forClass(ContextData.class);
+ verifyStatic(LoggingContext.class);
+
+ LoggingContext.put(contextDataCaptor.capture());
+
+ assertEquals(partner, contextDataCaptor.getValue().getPartnerName());
+ }
+
+ @Test
+ public void partnerNameAbsentWhenNotGiven() {
+
+ mockStatic(LoggingContext.class);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.preRequest(mock(HttpServletRequest.class));
+
+ ArgumentCaptor<ContextData> contextDataCaptor = ArgumentCaptor.forClass(ContextData.class);
+ verifyStatic(LoggingContext.class);
+
+ LoggingContext.put(contextDataCaptor.capture());
+
+ assertNull(contextDataCaptor.getValue().getPartnerName());
+ }
+
+ @Test
+ public void serviceNameGenerated() {
+
+ mockStatic(LoggingContext.class);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.preRequest(mock(HttpServletRequest.class));
+
+ ArgumentCaptor<ContextData> contextDataCaptor = ArgumentCaptor.forClass(ContextData.class);
+ verifyStatic(LoggingContext.class);
+
+ LoggingContext.put(contextDataCaptor.capture());
+
+ assertNotNull(contextDataCaptor.getValue().getServiceName());
+ }
+
+ @Test
+ public void contextClearedWhenRequestFinished() {
+
+ mockStatic(LoggingContext.class);
+
+ ContextTracker tracker = new ContextTracker(PARTNER_NAME_HEADER, REQUEST_ID_HEADER);
+ tracker.postRequest(mock(RequestProcessingResult.class));
+
+ verifyStatic(LoggingContext.class);
+ LoggingContext.clear();
+ }
+}
+
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/HttpHeaderTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/HttpHeaderTest.java
new file mode 100644
index 0000000000..5cbd0c0d76
--- /dev/null
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/HttpHeaderTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
+package org.openecomp.sdc.logging.servlet;
+
+import static junit.framework.TestCase.assertTrue;
+import static org.junit.Assert.assertFalse;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import org.junit.Test;
+
+/**
+ * Unit tests multiple-option headers.
+ *
+ * @author evitaliy
+ * @since 31 Jul 2018
+ */
+public class HttpHeaderTest {
+
+ private static final Supplier<? extends Throwable> VALUE_EXPECTED = () -> new AssertionError("Value expected");
+ private static final Function<String, String> NULL_WHEN_NAME_NOT_B = k -> "B".equals(k) ? "Value" : null;
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenInputArrayNull() {
+ new HttpHeader((String[]) null);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void throwExceptionWhenInputListNull() {
+ new HttpHeader((List<String>) null);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void throwExceptionWhenInputArrayEmpty() {
+ new HttpHeader(new String[0]);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void throwExceptionWhenInputListEmpty() {
+ new HttpHeader(Collections.emptyList());
+ }
+
+ @Test
+ public void valueNotReturnedWhenNameInArrayNotRequested() {
+ HttpHeader header = new HttpHeader(new String[] {"A"});
+ assertFalse(header.getAny(NULL_WHEN_NAME_NOT_B).isPresent());
+ }
+
+ @Test
+ public void valueNotReturnedWhenNameInListNotRequested() {
+ HttpHeader header = new HttpHeader(Collections.singletonList("A"));
+ assertFalse(header.getAny(NULL_WHEN_NAME_NOT_B).isPresent());
+ }
+
+ @Test
+ public void valueReturnedWhenSinglePossibleHeaderInArrayMatches() {
+ HttpHeader header = new HttpHeader(new String[] {"B"});
+ assertTrue(header.getAny(NULL_WHEN_NAME_NOT_B).isPresent());
+ }
+
+ @Test
+ public void valueReturnedWhenSinglePossibleHeaderInListMatches() {
+ HttpHeader header = new HttpHeader(Collections.singletonList("B"));
+ assertTrue(header.getAny(NULL_WHEN_NAME_NOT_B).isPresent());
+ }
+
+ @Test
+ public void valueReturnedWhenLastHeaderInArrayMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(new String[] {"A", "B"});
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+
+ @Test
+ public void valueReturnedWhenLastHeaderInListMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(Arrays.asList("A", "B"));
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+
+ @Test
+ public void valueReturnedWhenFirstHeaderInArrayMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(new String[] {"B", "A"});
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+
+ @Test
+ public void valueReturnedWhenFirstHeaderInListMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(Arrays.asList("B", "A"));
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+
+ @Test
+ public void valueReturnedWhenMiddleHeaderInArrayMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(new String[] {"A", "B", "C"});
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+
+ @Test
+ public void valueReturnedWhenMiddleHeaderInListMatches() throws Throwable {
+ HttpHeader header = new HttpHeader(Arrays.asList("A", "B", "C"));
+ header.getAny(NULL_WHEN_NAME_NOT_B).orElseThrow(VALUE_EXPECTED);
+ }
+} \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java
deleted file mode 100644
index 1ba418f317..0000000000
--- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Copyright © 2016-2018 European Support Limited
- *
- * 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.
- */
-
-package org.openecomp.sdc.logging.servlet;
-
-import org.easymock.EasyMock;
-import org.junit.After;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.logging.api.ContextData;
-import org.openecomp.sdc.logging.api.LoggingContext;
-import org.powermock.api.easymock.PowerMock;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import javax.servlet.FilterChain;
-import javax.servlet.FilterConfig;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.util.UUID;
-
-import static org.easymock.EasyMock.anyObject;
-import static org.openecomp.sdc.logging.LoggingConstants.DEFAULT_PARTNER_NAME_HEADER;
-import static org.openecomp.sdc.logging.LoggingConstants.DEFAULT_REQUEST_ID_HEADER;
-import static org.openecomp.sdc.logging.servlet.LoggingFilter.PARTNER_NAME_HEADERS_PARAM;
-import static org.openecomp.sdc.logging.servlet.LoggingFilter.REQUEST_ID_HEADERS_PARAM;
-
-/**
- * Unit-tests logging filter for initialization and data retrieval.
- *
- * @author evitaliy
- * @since 17 Aug 2016
- */
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(LoggingContext.class)
-public class LoggingFilterTest {
-
- private static final String RANDOM_REQUEST_URI = UUID.randomUUID().toString();
- private static final String RANDOM_REQUEST_ID = UUID.randomUUID().toString();
- private static final String RANDOM_PARTNER_NAME = UUID.randomUUID().toString();
-
- @Rule
- public TestName testName = new TestName();
-
- /**
- * Verify all mocks after each test.
- */
- @After
- public void verifyMocks() {
-
- try {
- PowerMock.verifyAll();
- } catch (AssertionError e) {
- throw new AssertionError("Expectations failed in " + testName.getMethodName() + "()", e);
- }
- }
-
-
- @Test
- public void filterPopulatesValuesWhenNoInitParamsAndNoHeaders() throws IOException, ServletException {
-
- mockLoggingContext();
- LoggingFilter loggingFilter = new LoggingFilter();
- loggingFilter.init(mockFilterConfig(null, null));
- loggingFilter.doFilter(new MockRequestBuilder().build(), mockResponse(), mockChain());
- }
-
- @Test
- public void filterPopulatesValuesWhenNoInitParamsAndExistingHeaders() throws IOException, ServletException {
-
- mockLoggingContext();
-
- LoggingFilter loggingFilter = new LoggingFilter();
- loggingFilter.init(mockFilterConfig(null, null));
-
- HttpServletRequest mockRequest = new MockRequestBuilder().partnerName(RANDOM_PARTNER_NAME)
- .requestId(RANDOM_REQUEST_ID).build();
- loggingFilter.doFilter(mockRequest, mockResponse(), mockChain());
- }
-
- @Test
- public void filterPopulatesValuesWhenCustomInitParamsAndNoHeaders() throws IOException, ServletException {
-
- mockLoggingContext();
-
- final String requestIdHeader = "x-request";
- final String partnerNameHeader = "x-partner";
-
- LoggingFilter loggingFilter = new LoggingFilter();
- FilterConfig mockConfig = mockFilterConfig(requestIdHeader, partnerNameHeader);
- loggingFilter.init(mockConfig);
-
- HttpServletRequest mockRequest = new MockRequestBuilder().requestIdHeader(requestIdHeader)
- .partnerNameHeader(partnerNameHeader).build();
- loggingFilter.doFilter(mockRequest, mockResponse(), mockChain());
- }
-
- @Test
- public void filterPopulatesValuesWhenCustomInitParamsAndExistingHeaders() throws IOException, ServletException {
-
- mockLoggingContext();
-
- final String requestIdHeader = "x-request-id";
- final String partnerNameHeader = "x-partner-name";
-
- LoggingFilter loggingFilter = new LoggingFilter();
- FilterConfig mockConfig = mockFilterConfig(requestIdHeader, partnerNameHeader);
- loggingFilter.init(mockConfig);
-
- HttpServletRequest mockRequest = new MockRequestBuilder()
- .partnerNameHeader(partnerNameHeader).partnerName(RANDOM_PARTNER_NAME)
- .requestIdHeader(requestIdHeader).requestId(RANDOM_REQUEST_ID).build();
- loggingFilter.doFilter(mockRequest, mockResponse(), mockChain());
- }
-
- private FilterConfig mockFilterConfig(String requestIdHeader, String partnerNameHeader) {
- FilterConfig config = EasyMock.mock(FilterConfig.class);
- EasyMock.expect(config.getInitParameter(REQUEST_ID_HEADERS_PARAM)).andReturn(requestIdHeader);
- EasyMock.expect(config.getInitParameter(PARTNER_NAME_HEADERS_PARAM)).andReturn(partnerNameHeader);
- EasyMock.replay(config);
- return config;
- }
-
- private FilterChain mockChain() throws IOException, ServletException {
- FilterChain chain = EasyMock.mock(FilterChain.class);
- chain.doFilter(anyObject(ServletRequest.class), anyObject(ServletResponse.class));
- EasyMock.expectLastCall().once();
- EasyMock.replay(chain);
- return chain;
- }
-
- private ServletResponse mockResponse() {
- HttpServletResponse servletResponse = EasyMock.mock(HttpServletResponse.class);
- EasyMock.replay(servletResponse);
- return servletResponse;
- }
-
- private void mockLoggingContext() {
-
- PowerMock.mockStatic(LoggingContext.class);
-
- LoggingContext.clear();
- EasyMock.expectLastCall().times(2);
-
- LoggingContext.put(anyObject(ContextData.class));
- EasyMock.expectLastCall().once();
-
- PowerMock.replay(LoggingContext.class);
- }
-
- private static class MockRequestBuilder {
-
- private String requestIdHeader = DEFAULT_REQUEST_ID_HEADER;
- private String partnerNameHeader = DEFAULT_PARTNER_NAME_HEADER;
- private String requestId = null;
- private String partnerName = null;
-
- MockRequestBuilder requestIdHeader(String h) {
- this.requestIdHeader = h;
- return this;
- }
-
- MockRequestBuilder requestId(String id) {
- this.requestId = id;
- return this;
- }
-
- MockRequestBuilder partnerNameHeader(String h) {
- this.partnerNameHeader = h;
- return this;
- }
-
- MockRequestBuilder partnerName(String name) {
- this.partnerName = name;
- return this;
- }
-
- HttpServletRequest build() {
- HttpServletRequest mockRequest = EasyMock.mock(HttpServletRequest.class);
- EasyMock.expect(mockRequest.getRequestURI()).andReturn(RANDOM_REQUEST_URI);
- EasyMock.expect(mockRequest.getHeader(requestIdHeader)).andReturn(requestId);
- EasyMock.expect(mockRequest.getHeader(partnerNameHeader)).andReturn(partnerName);
- EasyMock.replay(mockRequest);
- return mockRequest;
- }
- }
-}
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatterTest.java
new file mode 100644
index 0000000000..87fb6f789c
--- /dev/null
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatterTest.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright © 2016-2018 European Support Limited
+ *
+ * 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.
+ */
+
+package org.openecomp.sdc.logging.servlet;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import javax.servlet.http.HttpServletRequest;
+import org.junit.Test;
+
+/**
+ * Service name formatting.
+ *
+ * @author evitaliy
+ * @since 01 Aug 2018
+ */
+public class ServiceNameFormatterTest {
+
+ @Test
+ public void includesMethodAndUri() {
+ final String method = "ABC";
+ final String uri = "/a/b/c";
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getRequestURI()).thenReturn(uri);
+ when(request.getMethod()).thenReturn(method);
+ assertEquals(method + ": " + uri, ServiceNameFormatter.format(request));
+ }
+} \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/HttpHeaderTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/HttpHeaderTest.java
deleted file mode 100644
index ad7be95cec..0000000000
--- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/HttpHeaderTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright © 2016-2018 European Support Limited
- *
- * 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.
- */
-
-package org.openecomp.sdc.logging.servlet.jaxrs;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import java.util.function.Function;
-import org.junit.Test;
-import org.openecomp.sdc.logging.servlet.HttpHeader;
-
-/**
- * Unit tests multiple-option headers.
- *
- * @author evitaliy
- * @since 25 Mar 2018
- */
-public class HttpHeaderTest {
-
- private static final String KEY_FIRST = "First";
- private static final String KEY_SECOND = "Second";
-
- @Test
- public void valueReturnedWhenSinglePossibleHeader() {
-
- final String key = "Head";
- final String value = "1234";
-
- Function<String, String> reader = createReader(key, value);
- HttpHeader header = new HttpHeader(key);
- assertEquals(value, header.getAny(reader));
- }
-
- @Test
- public void nullReturnedWhenSingleNoMatchingHeader() {
-
- final String key = "Head";
-
- Function<String, String> reader = createReader(key, null);
- HttpHeader header = new HttpHeader(key);
- assertNull(header.getAny(reader));
- }
-
- @Test
- public void nullReturnedWhenNoneHeaderMatches() {
- Function<String, String> reader = createReader("None", "Value");
- HttpHeader header = new HttpHeader("A", "B", "C");
- assertNull(header.getAny(reader));
- }
-
- @Test
- public void valueReturnedWhenLastHeaderMatches() {
-
- final String lastKey = "Last";
- final String value = "1234";
-
- Function<String, String> reader = createReader(lastKey, value);
- HttpHeader header = new HttpHeader(KEY_FIRST, KEY_SECOND, lastKey);
- assertEquals(value, header.getAny(reader));
- }
-
- @Test
- public void valueReturnedWhenFirstHeaderMatches() {
-
- final String value = "1234";
- Function<String, String> reader = createReader(KEY_FIRST, value);
- HttpHeader header = new HttpHeader(KEY_FIRST, KEY_SECOND, "Third");
- assertEquals(value, header.getAny(reader));
- }
-
- @Test
- public void valueReturnedWhenMiddleHeaderMatches() {
-
- final String value = "1234";
- Function<String, String> reader = createReader(KEY_SECOND, value);
- HttpHeader header = new HttpHeader(KEY_FIRST, KEY_SECOND, "Third");
- assertEquals(value, header.getAny(reader));
- }
-
- private Function<String, String> createReader(String key, String value) {
- return h -> h.equals(key) ? value : null;
- }
-} \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilterTest.java
index 4098809e42..aa77dea53a 100644
--- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilterTest.java
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilterTest.java
@@ -16,25 +16,18 @@
package org.openecomp.sdc.logging.servlet.jaxrs;
-import static org.easymock.EasyMock.anyObject;
-import static org.easymock.EasyMock.anyString;
-import static org.openecomp.sdc.logging.servlet.jaxrs.LoggingRequestFilter.START_TIME_KEY;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.logging.servlet.jaxrs.LoggingRequestFilter.LOGGING_TRACKER_KEY;
-import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
-import org.easymock.EasyMock;
-import org.junit.After;
-import org.junit.Rule;
+import javax.ws.rs.container.ResourceInfo;
import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.logging.LoggingConstants;
-import org.openecomp.sdc.logging.api.ContextData;
-import org.openecomp.sdc.logging.api.LoggingContext;
-import org.powermock.api.easymock.PowerMock;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
+import org.openecomp.sdc.logging.servlet.Tracker;
/**
@@ -43,222 +36,25 @@ import org.powermock.modules.junit4.PowerMockRunner;
* @author evitaliy
* @since 19 Mar 2018
*/
-@RunWith(PowerMockRunner.class)
-@PrepareForTest({LoggingContext.class, ContextData.class})
public class LoggingRequestFilterTest {
- private static final String REQUEST_URI = "/test";
- private static final String REQUEST_METHOD = "GET";
- private static final String RANDOM_REQUEST_ID = UUID.randomUUID().toString();
- private static final String RANDOM_PARTNER_NAME = UUID.randomUUID().toString();
-
- @Rule
- public TestName testName = new TestName();
-
- /**
- * Verify all mocks after each test.
- */
- @After
- public void verifyMocks() {
-
- try {
- PowerMock.verifyAll();
- } catch (AssertionError e) {
- throw new AssertionError("Expectations failed in " + testName.getMethodName() + "()", e);
- }
- }
-
- @Test
- public void serviceNamePopulatedWhenThereIsMatchingResource() {
-
- mockContextDataBuilder(null, null, LoggingRequestFilter.formatServiceName(REQUEST_METHOD, REQUEST_URI));
- mockLoggingContext();
-
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setHttpRequest(mockHttpRequest(true));
-
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(null),
- new PartnerHeader(null)));
- }
-
- @Test
- public void serviceNameDoesNotIncludeHttpMethodWhenHttpMethodDisabled() {
-
- mockContextDataBuilder(null, null, REQUEST_URI);
- mockLoggingContext();
-
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setHttpMethodInServiceName(false);
- filter.setHttpRequest(mockHttpRequest(false));
-
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(null),
- new PartnerHeader(null)));
- }
-
- @Test
- public void partnerNamePopulatedWhenPresentInDefaultHeader() {
-
- mockContextDataBuilder(null, RANDOM_PARTNER_NAME,
- LoggingRequestFilter.formatServiceName(REQUEST_METHOD, REQUEST_URI));
- mockLoggingContext();
-
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setHttpRequest(mockHttpRequest(true));
-
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(null),
- new PartnerHeader(RANDOM_PARTNER_NAME)));
- }
-
- @Test
- public void partnerNamePopulatedWhenPresentInCustomHeader() {
-
- final String partnerHeader = "x-partner-header";
- mockContextDataBuilder(null, RANDOM_PARTNER_NAME,
- LoggingRequestFilter.formatServiceName(REQUEST_METHOD, REQUEST_URI));
- mockLoggingContext();
-
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setHttpRequest(mockHttpRequest(true));
- filter.setPartnerNameHeaders(partnerHeader);
-
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(null),
- new PartnerHeader(partnerHeader, RANDOM_PARTNER_NAME)));
- }
-
@Test
- public void requestIdPopulatedWhenPresentInDefaultHeader() {
-
- mockContextDataBuilder(RANDOM_REQUEST_ID, null,
- LoggingRequestFilter.formatServiceName(REQUEST_METHOD, REQUEST_URI));
- mockLoggingContext();
-
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setHttpRequest(mockHttpRequest(true));
-
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(RANDOM_REQUEST_ID),
- new PartnerHeader(null)));
- }
-
- @Test
- public void requestIdPopulatedWhenPresentInCustomHeader() {
-
- final String requestIdHeader = "x-request-id";
- mockContextDataBuilder(RANDOM_REQUEST_ID, null,
- LoggingRequestFilter.formatServiceName(REQUEST_METHOD, REQUEST_URI));
- mockLoggingContext();
+ public void trackerPushedOntoRequestContext() {
- LoggingRequestFilter filter = new LoggingRequestFilter();
- filter.setRequestIdHeaders(requestIdHeader);
- filter.setHttpRequest(mockHttpRequest(true));
+ LoggingRequestFilter requestFilter = new LoggingRequestFilter();
+ requestFilter.setHttpRequest(mock(HttpServletRequest.class));
- filter.filter(mockContainerRequestContext(
- new RequestIdHeader(requestIdHeader, RANDOM_REQUEST_ID),
- new PartnerHeader(null)));
- }
-
- private HttpServletRequest mockHttpRequest(boolean includeMethod) {
-
- HttpServletRequest servletRequest = EasyMock.mock(HttpServletRequest.class);
- EasyMock.expect(servletRequest.getRequestURI()).andReturn(REQUEST_URI);
-
- if (includeMethod) {
- EasyMock.expect(servletRequest.getMethod()).andReturn(REQUEST_METHOD);
- }
-
- EasyMock.replay(servletRequest);
- return servletRequest;
- }
-
- private ContainerRequestContext mockContainerRequestContext(Header... headers) {
-
- ContainerRequestContext requestContext = EasyMock.mock(ContainerRequestContext.class);
-
- for (Header h : headers) {
- EasyMock.expect(requestContext.getHeaderString(h.key)).andReturn(h.value);
- }
-
- requestContext.setProperty(EasyMock.eq(START_TIME_KEY), EasyMock.anyLong());
- EasyMock.expectLastCall();
-
- EasyMock.replay(requestContext);
- return requestContext;
- }
-
- private void mockContextDataBuilder(String requestId, String partnerName, String serviceName) {
-
- ContextData.ContextDataBuilder mockBuilder = EasyMock.mock(ContextData.ContextDataBuilder.class);
-
- if (requestId != null) {
- EasyMock.expect(mockBuilder.requestId(requestId)).andReturn(mockBuilder);
- } else {
- EasyMock.expect(mockBuilder.requestId(anyString())).andReturn(mockBuilder);
- }
-
- EasyMock.expect(mockBuilder.serviceName(serviceName)).andReturn(mockBuilder);
-
- if (partnerName != null) {
- EasyMock.expect(mockBuilder.partnerName(partnerName)).andReturn(mockBuilder);
- }
-
- EasyMock.expect(mockBuilder.build()).andReturn(EasyMock.mock(ContextData.class));
- EasyMock.replay(mockBuilder);
+ ResourceInfo resourceInfo = mock(ResourceInfo.class);
+ when(resourceInfo.getResourceMethod()).thenReturn(Resource.class.getDeclaredMethods()[0]);
+ requestFilter.setResource(resourceInfo);
- PowerMock.mockStatic(ContextData.class);
-
- ContextData.builder();
- PowerMock.expectLastCall().andReturn(mockBuilder);
-
- PowerMock.replay(ContextData.class);
- }
-
- private void mockLoggingContext() {
-
- PowerMock.mockStatic(LoggingContext.class);
-
- LoggingContext.clear();
- EasyMock.expectLastCall();
-
- LoggingContext.put(anyObject(ContextData.class));
- EasyMock.expectLastCall();
-
- PowerMock.replay(LoggingContext.class);
- }
-
- private abstract static class Header {
-
- private final String key;
- private final String value;
-
- private Header(String key, String value) {
- this.key = key;
- this.value = value;
- }
+ ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
+ requestFilter.filter(requestContext);
+ verify(requestContext).setProperty(eq(LOGGING_TRACKER_KEY), any(Tracker.class));
}
- private static class PartnerHeader extends Header {
-
- private PartnerHeader(String value) {
- super(LoggingConstants.DEFAULT_PARTNER_NAME_HEADER, value);
- }
-
- private PartnerHeader(String key, String value) {
- super(key, value);
- }
- }
-
- private static class RequestIdHeader extends Header {
-
- private RequestIdHeader(String value) {
- super(LoggingConstants.DEFAULT_REQUEST_ID_HEADER, value);
- }
-
- private RequestIdHeader(String key, String value) {
- super(key, value);
- }
+ private interface Resource {
+ @SuppressWarnings("unused")
+ void method();
}
} \ No newline at end of file
diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilterTest.java
index 710cf12b7e..336840be58 100644
--- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilterTest.java
+++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilterTest.java
@@ -16,35 +16,18 @@
package org.openecomp.sdc.logging.servlet.jaxrs;
-import static org.easymock.EasyMock.anyObject;
-import static org.easymock.EasyMock.anyString;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.openecomp.sdc.logging.servlet.jaxrs.LoggingRequestFilter.LOGGING_TRACKER_KEY;
-import java.lang.reflect.Method;
-import java.util.Comparator;
-import java.util.Objects;
-import java.util.function.Consumer;
-import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ResourceInfo;
-import javax.ws.rs.core.Response;
-import org.easymock.EasyMock;
-import org.easymock.LogicalOperator;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.TestName;
-import org.junit.runner.RunWith;
-import org.openecomp.sdc.logging.api.AuditData;
-import org.openecomp.sdc.logging.api.Logger;
-import org.openecomp.sdc.logging.api.LoggerFactory;
-import org.openecomp.sdc.logging.api.LoggingContext;
-import org.openecomp.sdc.logging.api.StatusCode;
-import org.powermock.api.easymock.PowerMock;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
+import org.openecomp.sdc.logging.servlet.RequestProcessingResult;
+import org.openecomp.sdc.logging.servlet.Tracker;
/**
* Unit testing JAX-RS response filter.
@@ -52,277 +35,24 @@ import org.powermock.modules.junit4.PowerMockRunner;
* @author evitaliy
* @since 19 Mar 2018
*/
-@RunWith(PowerMockRunner.class)
public class LoggingResponseFilterTest {
- private static final Class RESOURCE_TYPE = Resource.class;
- private static final Method RESOURCE_METHOD = Resource.class.getDeclaredMethods()[0];
-
- @Rule
- public TestName testName = new TestName();
-
- @Before
- public void prepareLoggingContext() {
- mockLoggingContext();
- }
-
- /**
- * Verify all mocks after each test.
- */
- @After
- public void verifyMocks() {
-
- try {
- PowerMock.verifyAll();
- } catch (AssertionError e) {
- throw new AssertionError("Expectations failed in " + testName.getMethodName() + "()", e);
- }
- }
-
@Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void noAuditWhenNoMatchingResource() {
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockFilterLogger(logger -> {
- logger.debug(anyString());
- EasyMock.expectLastCall();
- });
- PowerMock.replay(LoggerFactory.class);
-
- LoggingResponseFilter responseFilter = new LoggingResponseFilter();
- responseFilter.filter(mockDisabledRequestContext(), mockDisabledResponseContext());
+ public void noExceptionsWhenTrackerNotPassed() {
+ new LoggingResponseFilter().filter(mock(ContainerRequestContext.class), mock(ContainerResponseContext.class));
}
@Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void noAuditWhenNullResource() {
+ public void postRequestWhenTrackerPassed() {
- PowerMock.mockStatic(LoggerFactory.class);
- mockFilterLogger(logger -> {
- logger.debug(anyString());
- EasyMock.expectLastCall();
- });
- PowerMock.replay(LoggerFactory.class);
+ Tracker tracker = mock(Tracker.class);
- LoggingResponseFilter responseFilter = new LoggingResponseFilter();
- responseFilter.setResource(null);
- responseFilter.filter(mockDisabledRequestContext(), mockDisabledResponseContext());
- }
-
- @Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void noAuditWhenAuditDisabled() {
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockFilterLogger();
- mockResourceLogger(false, AuditData.builder().build());
- PowerMock.replay(LoggerFactory.class);
+ ContainerRequestContext requestContext = mock(ContainerRequestContext.class);
+ when(requestContext.getProperty(LOGGING_TRACKER_KEY)).thenReturn(tracker);
LoggingResponseFilter responseFilter = new LoggingResponseFilter();
- responseFilter.setResource(mockResource());
- responseFilter.filter(mockDisabledRequestContext(), mockDisabledResponseContext());
- }
-
- @Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void startTimeReadWhenPresentInRequestContext() {
-
- final String clientIp = "IP1";
- final long startTime = 12345L;
- final Response.Status ok = Response.Status.OK;
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockResourceLogger(true, buildAuditData(startTime, clientIp, ok, StatusCode.COMPLETE));
- mockFilterLogger();
- PowerMock.replay(LoggerFactory.class);
-
- LoggingResponseFilter filter = new LoggingResponseFilter();
- filter.setResource(mockResource());
- filter.setHttpRequest(mockHttpRequest(clientIp));
-
- filter.filter(mockRequestContext(startTime), mockResponseContext(ok));
- }
-
- @Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void startTimeZeroWhenNotPresentInRequestContext() {
-
- final String clientIp = "IP2";
- final Response.Status ok = Response.Status.OK;
-
- AuditData expectedAuditData = buildAuditData(0, clientIp, ok, StatusCode.COMPLETE);
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockResourceLogger(true, expectedAuditData);
- mockFilterLogger(logger -> {
- logger.error(anyString(), anyObject(Object[].class));
- EasyMock.expectLastCall();
- });
- PowerMock.replay(LoggerFactory.class);
-
- LoggingResponseFilter filter = new LoggingResponseFilter();
- filter.setResource(mockResource());
- filter.setHttpRequest(mockHttpRequest(clientIp));
-
- filter.filter(mockRequestContext(null), mockResponseContext(ok));
- }
-
- @Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void startTimeZeroWhenIncorrectObjectType() {
-
- final String clientIp = "IP3";
- final Response.Status accepted = Response.Status.ACCEPTED;
-
- AuditData expectedAuditData = buildAuditData(0, clientIp, accepted, StatusCode.COMPLETE);
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockFilterLogger(logger -> {
- logger.error(anyString(), anyString(), anyString(), anyObject());
- EasyMock.expectLastCall();
- });
- mockResourceLogger(true, expectedAuditData);
- PowerMock.replay(LoggerFactory.class);
-
- LoggingResponseFilter filter = new LoggingResponseFilter();
- filter.setResource(mockResource());
- filter.setHttpRequest(mockHttpRequest(clientIp));
-
- filter.filter(mockRequestContext("string object"), mockResponseContext(accepted));
- }
-
- @Test
- @PrepareForTest({LoggingContext.class, LoggerFactory.class})
- public void statusErrorWhenHttpResponseGreaterThan399() {
-
- final Response.Status error = Response.Status.BAD_REQUEST;
- final String clientIp = "IP13";
- final long startTime = 88668603L;
-
- AuditData expectedAuditData = buildAuditData(startTime, clientIp, error, StatusCode.ERROR);
-
- PowerMock.mockStatic(LoggerFactory.class);
- mockResourceLogger(true, expectedAuditData);
- mockFilterLogger();
- PowerMock.replay(LoggerFactory.class);
-
- LoggingResponseFilter filter = new LoggingResponseFilter();
- filter.setResource(mockResource());
- filter.setHttpRequest(mockHttpRequest(clientIp));
-
- filter.filter(mockRequestContext(startTime), mockResponseContext(error));
- }
-
- private AuditData buildAuditData(long startTime, String clientIp, Response.Status responseStatus,
- StatusCode status) {
- return AuditData.builder().startTime(startTime).responseCode(Integer.toString(responseStatus.getStatusCode()))
- .responseDescription(responseStatus.getReasonPhrase()).clientIpAddress(clientIp)
- .statusCode(status).build();
- }
-
- private void mockResourceLogger(boolean enabled, AuditData auditData) {
-
- Logger resourceLogger = EasyMock.mock(Logger.class);
-
- EasyMock.expect(resourceLogger.isAuditEnabled()).andReturn(enabled).atLeastOnce();
-
- if (enabled) {
- resourceLogger.audit(EasyMock.cmp(auditData, new AuditDataComparator(), LogicalOperator.EQUAL));
- EasyMock.expectLastCall();
- }
-
- EasyMock.replay(resourceLogger);
-
- LoggerFactory.getLogger(RESOURCE_TYPE);
- PowerMock.expectLastCall().andReturn(resourceLogger);
- }
-
- @SafeVarargs
- private final void mockFilterLogger(Consumer<Logger>... expectations) {
-
- Logger filterLogger = EasyMock.mock(Logger.class);
-
- for (Consumer<Logger> expect : expectations) {
- expect.accept(filterLogger);
- }
-
- EasyMock.replay(filterLogger);
-
- LoggerFactory.getLogger(LoggingResponseFilter.class);
- PowerMock.expectLastCall().andReturn(filterLogger);
- }
-
- private void mockLoggingContext() {
- PowerMock.mockStatic(LoggingContext.class);
- LoggingContext.clear();
- EasyMock.expectLastCall();
- PowerMock.replay(LoggingContext.class);
- }
-
- private ContainerRequestContext mockDisabledRequestContext() {
- ContainerRequestContext requestContext = EasyMock.mock(ContainerRequestContext.class);
- EasyMock.replay(requestContext);
- return requestContext;
- }
-
- private ContainerResponseContext mockDisabledResponseContext() {
- ContainerResponseContext responseContext = EasyMock.mock(ContainerResponseContext.class);
- EasyMock.replay(responseContext);
- return responseContext;
- }
-
- private HttpServletRequest mockHttpRequest(String clientIp) {
- HttpServletRequest servletRequest = EasyMock.mock(HttpServletRequest.class);
- EasyMock.expect(servletRequest.getRemoteAddr()).andReturn(clientIp);
- EasyMock.replay(servletRequest);
- return servletRequest;
- }
-
- private ContainerRequestContext mockRequestContext(Object startTime) {
- ContainerRequestContext requestContext = EasyMock.mock(ContainerRequestContext.class);
- EasyMock.expect(requestContext.getProperty(LoggingRequestFilter.START_TIME_KEY)).andReturn(startTime);
- EasyMock.replay(requestContext);
- return requestContext;
- }
-
- private ContainerResponseContext mockResponseContext(Response.StatusType statusInfo) {
- ContainerResponseContext responseContext = EasyMock.mock(ContainerResponseContext.class);
- EasyMock.expect(responseContext.getStatusInfo()).andReturn(statusInfo);
- EasyMock.replay(responseContext);
- return responseContext;
- }
-
- private ResourceInfo mockResource() {
- ResourceInfo resource = EasyMock.mock(ResourceInfo.class);
- //noinspection unchecked
- EasyMock.expect(resource.getResourceClass()).andReturn(RESOURCE_TYPE).anyTimes();
- EasyMock.expect(resource.getResourceMethod()).andReturn(RESOURCE_METHOD).anyTimes();
- EasyMock.replay(resource);
- return resource;
- }
-
- private static class AuditDataComparator implements Comparator<AuditData> {
-
- @Override
- public int compare(AuditData one, AuditData two) {
-
- // don't compare end time as it changes
- if (Objects.equals(one.getClientIpAddress(), two.getClientIpAddress())
- && Objects.equals(one.getResponseCode(), two.getResponseCode())
- && Objects.equals(one.getResponseDescription(), two.getResponseDescription())
- && one.getStartTime() == two.getStartTime()
- && Objects.equals(one.getStatusCode(), two.getStatusCode())) {
-
- return 0;
- }
-
- return -1;
- }
- }
+ responseFilter.filter(requestContext, mock(ContainerResponseContext.class));
- interface Resource {
- @SuppressWarnings("unused")
- void method();
+ verify(tracker, times(1)).postRequest(any(RequestProcessingResult.class));
}
} \ No newline at end of file