summaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test
diff options
context:
space:
mode:
authorAlexey Sandler <alexey.sandler@intl.att.com>2019-10-31 09:42:12 +0200
committerAlexey Sandler <alexey.sandler@intl.att.com>2019-10-31 13:03:18 +0200
commit5417f56b89f4780b3c43e5430aa38cc1035a2f1c (patch)
treea7f834c0723f782d25a8fe188081878c0b75a421 /vid-app-common/src/test
parent94b51c73b499978aaddbb115de2b0f16f2d4db96 (diff)
register SyncRestClient to work with new MetricLogClient Filter
Issue-ID: VID-253 add API test that checks request headers logged tometrics log Signed-off-by: Alexey Sandler <alexey.sandler@intl.att.com> Change-Id: Ic2bfb99d40482b939ddaa4ba5c694f1042c3dd69 Signed-off-by: Alexey Sandler <alexey.sandler@intl.att.com>
Diffstat (limited to 'vid-app-common/src/test')
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java49
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java8
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java346
3 files changed, 1 insertions, 402 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
index dd05a625e..e4661134e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java
@@ -25,18 +25,12 @@ import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasEntry;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
-import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.refEq;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
-import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY;
-import static org.testng.Assert.assertNotEquals;
-import static org.testng.AssertJUnit.assertEquals;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.joshworks.restclient.http.HttpResponse;
@@ -48,9 +42,7 @@ import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
-import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-import org.mockito.Mockito;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.aai.HttpResponseWithRequestInfo;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
@@ -69,8 +61,6 @@ import org.onap.vid.utils.SystemPropertiesWrapper;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -151,45 +141,6 @@ public class MsoRestClientTest {
}
@Test
- public void whenCreateInstanceTwice_thenRequestIdHeaderIsDifferentEachTime() {
-
- RequestAttributes prevRequestAttributes = RequestContextHolder.getRequestAttributes();
-
- try {
- //given
- Mockito.reset(client);
-
- //mocking syncRestClient
- RequestDetails requestDetails = MsoRestClientTestUtil.generateMockMsoRequest();
- HttpResponse<String> httpResponse = HttpResponse.fallback("testOkResponse");
- when( client.post( anyString() ,anyMap(), any(RequestDetails.class), eq(String.class) ) ).thenReturn(httpResponse);
-
- //when
- //create different ECOMP_REQUEST_ID header in Spring HttpServlet each time
- OutgoingRequestHeadersTest.putRequestInSpringContext();
- restClient.createInstance(requestDetails, "someEndPoint");
-
- OutgoingRequestHeadersTest.putRequestInSpringContext();
- restClient.createInstance(requestDetails, "someEndPoint");
-
- //then
- ArgumentCaptor<Map<String, String>> requestCaptor = ArgumentCaptor.forClass(Map.class);
- verify(client, times(2)).post(anyString(), requestCaptor.capture(), any(RequestDetails.class), eq(String.class));
- assertEquals(2, requestCaptor.getAllValues().size());
- assertNotEquals(requestCaptor.getAllValues().get(0).get(SystemProperties.ECOMP_REQUEST_ID),
- requestCaptor.getAllValues().get(1).get(SystemProperties.ECOMP_REQUEST_ID),
- SystemProperties.ECOMP_REQUEST_ID + " headers are the same");
- assertNotEquals(requestCaptor.getAllValues().get(0).get(ONAP_REQUEST_ID_HEADER_KEY),
- requestCaptor.getAllValues().get(1).get(ONAP_REQUEST_ID_HEADER_KEY),
- ONAP_REQUEST_ID_HEADER_KEY + " headers are the same");
- }
- finally {
- //make sure other test keep go smooth
- RequestContextHolder.setRequestAttributes(prevRequestAttributes);
- }
- }
-
- @Test
public void shouldProperlyCreateVnf() {
// given
RequestDetails requestDetails = MsoRestClientTestUtil.generateMockMsoRequest();
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java
index 123737f4f..9daf9f4b9 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java
@@ -32,8 +32,6 @@ import static com.xebialabs.restito.semantics.Condition.post;
import static com.xebialabs.restito.semantics.Condition.uri;
import static com.xebialabs.restito.semantics.Condition.withHeader;
import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
-import static org.onap.vid.logging.Headers.PARTNER_NAME;
-import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xebialabs.restito.semantics.Action;
@@ -52,7 +50,6 @@ import org.glassfish.grizzly.http.Method;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.json.JSONObject;
import org.junit.Assert;
-import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.changeManagement.RelatedInstanceList;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
import org.onap.vid.changeManagement.WorkflowRequestDetail;
@@ -234,10 +231,7 @@ class MsoRestClientTestUtil implements AutoCloseable {
withHeader(HttpHeaders.AUTHORIZATION),
withHeader(HttpHeaders.ACCEPT),
withHeader(HttpHeaders.CONTENT_TYPE),
- withHeader(MsoRestClientNew.X_FROM_APP_ID),
- withHeader(PARTNER_NAME.getHeaderName(), "VID.VID"),
- withHeader(SystemProperties.ECOMP_REQUEST_ID),
- withHeader(ONAP_REQUEST_ID_HEADER_KEY)
+ withHeader(MsoRestClientNew.X_FROM_APP_ID)
);
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java
deleted file mode 100644
index f03b89722..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java
+++ /dev/null
@@ -1,346 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 - 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.vid.mso.rest;
-
-import static org.apache.commons.io.IOUtils.toInputStream;
-import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
-import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.startsWith;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.allOf;
-import static org.hamcrest.Matchers.hasItem;
-import static org.hamcrest.Matchers.hasToString;
-import static org.hamcrest.Matchers.instanceOf;
-import static org.hamcrest.Matchers.matchesPattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyMap;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.when;
-
-import com.google.common.collect.ImmutableList;
-import io.joshworks.restclient.http.HttpResponse;
-import java.nio.charset.StandardCharsets;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
-import java.util.UUID;
-import java.util.function.Consumer;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.client.Invocation.Builder;
-import javax.ws.rs.core.MultivaluedMap;
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
-import org.mockito.InjectMocks;
-import org.mockito.Matchers;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.vid.aai.util.HttpsAuthClient;
-import org.onap.vid.aai.util.ServletRequestHelper;
-import org.onap.vid.aai.util.SystemPropertyHelper;
-import org.onap.vid.client.SyncRestClient;
-import org.onap.vid.controller.filter.PromiseRequestIdFilter;
-import org.onap.vid.logging.Headers;
-import org.onap.vid.mso.MsoProperties;
-import org.onap.vid.mso.RestMsoImplementation;
-import org.onap.vid.testUtils.TestUtils;
-import org.onap.vid.utils.Logging;
-import org.onap.vid.utils.SystemPropertiesWrapper;
-import org.springframework.http.HttpMethod;
-import org.springframework.mock.web.MockHttpServletRequest;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-
-public class OutgoingRequestHeadersTest {
-
- private static final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter();
-
- @InjectMocks
- private RestMsoImplementation restMsoImplementation;
-
- private MsoRestClientNew msoRestClientNew;
-
- @Mock
- private SystemPropertyHelper systemPropertyHelper;
-
- @Mock
- private SystemPropertiesWrapper systemPropertiesWrapper;
-
- @Mock
- private HttpsAuthClient httpsAuthClient;
-
- @Mock
- private ServletRequestHelper servletRequestHelper;
-
- @Mock
- private Logging loggingService;
-
- @Mock
- SyncRestClient syncRestClient;
-
- @Captor
- private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
-
- @BeforeClass
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- String oneIncomingRequestId = UUID.randomUUID().toString();
- when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(oneIncomingRequestId);
- when(systemPropertiesWrapper.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1vub1ua51uh81ugi1u9d1vuz");
- when(systemPropertiesWrapper.getProperty(SystemProperties.APP_DISPLAY_NAME)).thenReturn("vid");
- //the ctor of MsoRestClientNew require the above lines as preconditions
- msoRestClientNew = new MsoRestClientNew(syncRestClient, "baseUrl",systemPropertiesWrapper);
- }
-
- @BeforeMethod
- private void setup() {
- putRequestInSpringContext();
- }
-
- public static void putRequestInSpringContext() {
- RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(
- (HttpServletRequest) promiseRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
- }
-
- @DataProvider
- public Object[][] msoMethods() {
- return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
- client -> client.GetForObject("/any path", Object.class),
- client -> client.restCall(HttpMethod.DELETE, Object.class, "some payload", "/any path", Optional.of("userId")),
- client -> client.PostForObject("some payload", "/any path", Object.class)
- ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
- }
-
- @Test
- public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
-
- final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
- String randomUserName = randomAlphabetic(10);
-
- restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
- assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
- }
-
- @DataProvider
- public Object[][] msoRestClientNewMethods() {
- return Stream.<ThrowingConsumer<MsoRestClientNew>>of(
- client -> client.createInstance(new Object(), "/any path")
- ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
- }
-
- @Test(dataProvider = "msoRestClientNewMethods")
- public void msoRestClientNewHeadersTest(Consumer<MsoRestClientNew> f) throws Exception {
- Map[] captor = setMocksForMsoRestClientNew();
-
- f.accept(msoRestClientNew);
- Map headers = captor[0];
-
- String ecompRequestId = assertRequestHeaderIsUUID(headers, "X-ECOMP-RequestID");
- String onapRequestID = assertRequestHeaderIsUUID(headers, "X-ONAP-RequestID");
- assertEquals(ecompRequestId, onapRequestID);
-
-
- String invocationId1 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
- assertThat((String) headers.get("Authorization"), startsWith("Basic "));
- assertThat(headers.get("X-ONAP-PartnerName"), is("VID.VID"));
-
- //verify requestId is same in next call but invocationId is different
-
- //given
- captor = setMocksForMsoRestClientNew();
-
- //when
- f.accept(msoRestClientNew);
- headers = captor[0];
-
- //then
- assertEquals(headers.get("X-ONAP-RequestID"), onapRequestID);
- String invocationId2 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
- assertNotEquals(invocationId1, invocationId2);
-
- }
-
- private Map[] setMocksForMsoRestClientNew() {
- reset(syncRestClient);
- HttpResponse<String> httpResponse = mock(HttpResponse.class);
- String expectedResponse = "myResponse";
- when(httpResponse.getStatus()).thenReturn(202);
- when(httpResponse.getBody()).thenReturn(expectedResponse);
- when(httpResponse.getRawBody()).thenReturn(toInputStream(expectedResponse, StandardCharsets.UTF_8));
- final Map[] headersCapture = new Map[1];
- when(syncRestClient.post(anyString(), anyMap(), any(), eq(String.class))).thenAnswer(
- invocation -> {
- headersCapture[0] = (Map)invocation.getArguments()[1];
- return httpResponse;
- });
-
- return headersCapture;
- }
-
-// @Test(dataProvider = "schedulerMethods")
-// public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
-//
-// This test os not feasible in the wat acheduler is implemented today,
-// as Scheduler's client is rewritten in every call.
-//
-// :-(
-//
-// }
-
- private String verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
- final String requestIdHeader = "x-ecomp-requestid";
- return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader);
- }
-
- private String assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) {
- Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName);
- return assertRequestHeaderIsUUID(headerName, headerValue);
- }
-
- private String assertRequestHeaderIsUUID(Map headers, String headerName) {
- return assertRequestHeaderIsUUID(headerName, headers.get(headerName));
- }
-
- private String assertRequestHeaderIsUUID(String headerName, Object headerValue) {
- final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
- assertThat("header '" + headerName + "' should be a uuid", headerValue,
- allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
- return (String)headerValue;
- }
-
- private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) {
- assertThat(
- captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()),
- is("VID.VID")
- );
- }
-
- private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) {
- // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
- // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
-
- Object requestId;
- // The 'verify()' will capture the request id. If no match -- AssertionError will
- // catch for a second chance -- another 'verify()'.
- try {
- try {
- ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
- Mockito.verify(fakeBuilder)
- .header(
- Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
- argumentCaptor.capture()
- );
- requestId = argumentCaptor.getValue();
-
- } catch (AssertionError e) {
- Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
-
- final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
- final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
-
- assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
- requestId = headersMap.getFirst(thisRequestIdHeader);
- }
- } catch (AssertionError e) {
- throw new AssertionError("header not captured: " + headerName, e);
- }
- return requestId;
- }
-
- private String getFromSetCaseInsensitive(Set<String> set, String key) {
- return set.stream()
- .filter(anotherString -> anotherString.equalsIgnoreCase(key))
- .findFirst()
- .orElse(key);
- }
-
- private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
- TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
- Client fakeClient = mocks.getFakeClient();
-
- FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
-
- return mocks;
- }
-
- private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
- TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
- Client fakeClient = mocks.getFakeClient();
-
- FieldUtils.writeField(instance, "client", fakeClient, true);
-
- return mocks;
- }
-
- @FunctionalInterface
- public interface ThrowingConsumer<T> extends Consumer<T> {
- @Override
- default void accept(T t) {
- try {
- acceptThrows(t);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- void acceptThrows(T t) throws Exception;
- }
-
- private class HeadersVerifier {
-
- private String firstRequestId;
- private String firstInvocationId;
-
-
- HeadersVerifier verifyFirstCall(Builder fakeBuilder) {
- firstRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
- assertEquals(firstRequestId, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID"));
- firstInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
- verifyXOnapPartnerNameHeaderWasAdded(fakeBuilder);
- return this;
- }
-
- void verifySecondCall(Builder fakeBuilder) {
- String secondRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
- assertEquals(firstRequestId, secondRequestId);
-
- Object secondInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
- assertNotEquals(firstInvocationId, secondInvocationId);
- }
- }
-}