diff options
Diffstat (limited to 'vid-app-common/src/test/java')
5 files changed, 321 insertions, 94 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java deleted file mode 100644 index 75b84b2db..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.onap.vid.asdc.rest; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.vid.testUtils.TestUtils; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ProcessingException; -import javax.ws.rs.client.Client; -import java.net.URI; -import java.util.UUID; -import java.util.function.Consumer; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.testng.AssertJUnit.fail; - -public class RestfulAsdcClientTest { - - @DataProvider - public static Object[][] javaxExceptions() { - - return new Object[][] { - {NotFoundException.class, (Consumer<Client>) javaxClientMock -> - when(javaxClientMock.target(any(URI.class))).thenThrow( - new NotFoundException("HTTP 404 Not Found"))}, - {ProcessingException.class, (Consumer<Client>) javaxClientMock -> - when(javaxClientMock.target(any(URI.class))).thenThrow( - new ProcessingException("java.net.ConnectException: Connection refused: connect"))}, - }; - } - - - @Test(dataProvider = "javaxExceptions") - public void whenJavaxClientThrowException_thenExceptionRethrown(Class<? extends Throwable> expectedType, Consumer<Client> setupMocks) throws Exception { - /* - Call chain is like: - this test -> RestfulAsdcClient -> javax's Client - - In this test, *RestfulAsdcClient* is under test (actual implementation is used), while javax's Client is - mocked to return pseudo-responses or - better - throw exceptions. - */ - - // prepare mocks - TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); - Client javaxClientMock = mocks.getFakeClient(); - - // prepare real RestfulAsdcClient (Under test) - RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(javaxClientMock, new URI("")) - .auth("") - .build(); - - /// TEST: - setupMocks.accept(javaxClientMock); - - try { - restfulAsdcClient.getServiceToscaModel(UUID.randomUUID()); - } catch (Exception e) { - assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType)); - return; //OK - } - - fail("exception shall rethrown by getServiceToscaModel once javax client throw exception "); - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java new file mode 100644 index 000000000..2ef337424 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.asdc.rest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.xebialabs.restito.semantics.Call; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.testUtils.StubServerUtil; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.Optional; +import java.util.UUID; + +import static com.xebialabs.restito.semantics.Action.ok; +import static com.xebialabs.restito.semantics.Action.stringContent; +import static org.apache.http.client.config.RequestConfig.custom; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertTrue; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; + + +public class SdcRestClientITTest { + private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + private static final String[] SUPPORTED_SSL_VERSIONS = {"TLSv1", "TLSv1.2"}; + private static StubServerUtil stubServer; + private static SdcRestClient sdcRestClient; + + @BeforeClass + public static void setUpClass() throws GeneralSecurityException { + stubServer = new StubServerUtil(); + stubServer.runSecuredServer(); + SyncRestClient syncRestClient = new SyncRestClient(createNaiveHttpClient()); + String serverUrl = stubServer.constructTargetUrl("https", ""); + sdcRestClient = new SdcRestClient(serverUrl, "", syncRestClient); + } + + @AfterClass + public static void tearDown() { + stubServer.stopServer(); + } + + @Test + public void shouldDownloadToscaArtifactUsingSecuredEndpoint() throws AsdcCatalogException, IOException { + UUID uuid = UUID.randomUUID(); + String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/toscaModel", uuid); + + stubServer.prepareGetCall( + expectedEndpoint, stringContent("sampleFileContent"), "sampleFileContent", ok(), "application/octet-stream"); + + + Path serviceToscaModel = sdcRestClient.getServiceToscaModel(uuid); + serviceToscaModel.toFile().deleteOnExit(); + + + assertThat(Files.readAllLines(serviceToscaModel), contains("sampleFileContent")); + assertThatRequestHasRequiredHeaders(expectedEndpoint); + } + + @Test + public void shouldGetServiceDetailsUsingSecuredEndpoint() throws AsdcCatalogException, JsonProcessingException { + UUID uuid = UUID.randomUUID(); + String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/metadata", uuid); + Service expectedService = getExpectedService(uuid.toString()); + + + stubServer.prepareGetCall(expectedEndpoint, expectedService, ok()); + + + Service actualService = sdcRestClient.getService(uuid); + + + assertThat(actualService, is(expectedService)); + assertThatRequestHasRequiredHeaders(expectedEndpoint); + } + + private void assertThatRequestHasRequiredHeaders(String expectedEndpoint) { + Optional<Call> first = stubServer + .getServerCalls() + .stream() + .filter(x -> x.getUri().contains(expectedEndpoint)) + .findFirst(); + + assertTrue(first.isPresent()); + + assertThat(first.get().getHeaders().keySet(), hasItems(X_ECOMP_INSTANCE_ID.toLowerCase(), REQUEST_ID_HEADER_KEY.toLowerCase())); + assertThat(first.get().getHeaders().get(REQUEST_ID_HEADER_KEY.toLowerCase()).get(0), matchesPattern(UUID_REGEX)); + } + + private Service getExpectedService(String stringId) { + return new Service(stringId, stringId, + "sampleCategory", "sampleVersion", + "sampleName", "sampleDistStatus", + "sampleToscaUrl", Service.LifecycleState.CERTIFIED, Collections.emptyList(), Collections.emptyList()); + } + + + private static CloseableHttpClient createNaiveHttpClient() throws GeneralSecurityException { + final SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(); + + final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, SUPPORTED_SSL_VERSIONS, + null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("https", socketFactory) + .build(); + + return HttpClientBuilder.create() + .setDefaultRequestConfig(custom().setConnectionRequestTimeout(10000).build()) + .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) + .setSSLSocketFactory(socketFactory).build(); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java new file mode 100644 index 000000000..c1d6ab78a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.asdc.rest; + +import io.joshworks.restclient.http.HttpResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.client.SyncRestClient; + +import java.io.InputStream; +import java.nio.file.Path; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMapOf; +import static org.mockito.Matchers.matches; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SdcRestClientTest { + + private static final String SAMPLE_SERVICE_NAME = "sampleService"; + private static final String SAMPLE_BASE_URL = "baseUrl"; + private static final String SAMPLE_AUTH = "sampleAuth"; + private static final String METADATA_URL_REGEX = ".*sdc/v1/catalog/services/%s/metadata"; + private static final String MODEL_URL_REGEX = ".*sdc/v1/catalog/services/%s/toscaModel"; + + + @Mock + private SyncRestClient mockedSyncRestClient; + + @Mock + private HttpResponse<Object> httpResponse; + + @Mock + private HttpResponse<InputStream> httpStreamResponse; + + @Mock + private InputStream inputStream; + + private UUID randomId; + + private Service sampleService; + + private SdcRestClient restClient; + + + @Before + public void setUp() { + randomId = UUID.randomUUID(); + sampleService = createTestService(); + restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient); + } + + + @Test + public void shouldReturnServiceForGivenUUID() throws AsdcCatalogException { + String url = String.format(METADATA_URL_REGEX, randomId); + when(mockedSyncRestClient.get(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class), any())).thenReturn(httpResponse); + when(httpResponse.getBody()).thenReturn(sampleService); + + Service service = restClient.getService(randomId); + + + assertThat(service, is(sampleService)); + } + + @Test(expected = AsdcCatalogException.class) + public void shouldRaiseAsdcExceptionWhenClientFails() throws AsdcCatalogException { + String url = String.format(METADATA_URL_REGEX, randomId); + when(mockedSyncRestClient.get(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class), any())).thenThrow(new RuntimeException()); + + restClient.getService(randomId); + } + + + @Test + public void shouldProperlyDownloadAndCopyToscaArtifact() throws AsdcCatalogException { + String url = String.format(MODEL_URL_REGEX, randomId); + when(mockedSyncRestClient.getStream(matches(url), any(), any())).thenReturn(httpStreamResponse); + when(httpStreamResponse.getBody()).thenReturn(inputStream); + + + Path serviceToscaModel = restClient.getServiceToscaModel(randomId); + + + assertThat(serviceToscaModel, notNullValue()); + assertThat(serviceToscaModel.toFile().isFile(), is(true)); + + serviceToscaModel.toFile().deleteOnExit(); + } + + @Test(expected = AsdcCatalogException.class) + public void shouldRaiseAsdcExceptionWhenDownloadFails() throws AsdcCatalogException { + String url = String.format(MODEL_URL_REGEX, randomId); + when(mockedSyncRestClient.getStream(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class))).thenThrow(new RuntimeException()); + + + restClient.getServiceToscaModel(randomId); + } + + + private Service createTestService() { + Service service = new Service(); + service.setInvariantUUID(randomId.toString()); + service.setUuid(randomId.toString()); + service.setName(SAMPLE_SERVICE_NAME); + return service; + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java index da2600eaf..909975fb8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java @@ -2,9 +2,13 @@ package org.onap.vid.mso.rest; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.reflect.FieldUtils; -import org.mockito.*; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.asdc.rest.RestfulAsdcClient; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; import org.onap.vid.mso.RestMsoImplementation; @@ -27,10 +31,13 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.UUID.randomUUID; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.mock; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.matchesPattern; public class OutgoingRequestIdTest { @@ -42,7 +49,6 @@ public class OutgoingRequestIdTest { @InjectMocks private AAIRestInterface aaiRestInterface; - private RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(mock(Client.class), null).build(); @Captor private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor; @@ -58,23 +64,6 @@ public class OutgoingRequestIdTest { } @DataProvider - public Object[][] sdcMethods() { - return Stream.<ThrowingConsumer<RestfulAsdcClient>>of( - client -> client.getService(randomUUID()), - client -> client.getServiceToscaModel(randomUUID()) - ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); - } - - @Test(dataProvider = "sdcMethods") - public void sdc(Consumer<RestfulAsdcClient> f) throws Exception { - final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restfulAsdcClient); - - f.accept(restfulAsdcClient); - - verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder()); - } - - @DataProvider public Object[][] msoMethods() { return Stream.<ThrowingConsumer<RestMsoImplementation>>of( diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java index e84655f7e..f7ffd9a9c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java @@ -23,9 +23,12 @@ package org.onap.vid.testUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.xebialabs.restito.semantics.Action; +import com.xebialabs.restito.semantics.Call; import com.xebialabs.restito.semantics.Condition; import com.xebialabs.restito.server.StubServer; +import java.util.List; + import static com.xebialabs.restito.builder.stub.StubHttp.whenHttp; import static com.xebialabs.restito.semantics.Action.contentType; import static com.xebialabs.restito.semantics.Action.stringContent; @@ -48,6 +51,10 @@ public class StubServerUtil { stubServer.run(); } + public void runSecuredServer(){ + stubServer.secured().run(); + } + public void stopServer() { stubServer.stop(); } @@ -57,10 +64,15 @@ public class StubServerUtil { return String.format("%s://localhost:%s/%s", protocol, stubServer.getPort(), relativePath); } - public void prepareGetCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { + public void prepareGetCall(String path, Action actionToReturn,Object returnObj, Action expectedAction, String contentType) throws JsonProcessingException { whenHttp(stubServer) .match(Condition.get(path)) - .then(expectedAction, jsonContent(returnObj), contentType(APPLICATION_JSON)); + .then(expectedAction, actionToReturn, contentType(contentType)); + } + + + public void prepareGetCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { + prepareGetCall(path, jsonContent(returnObj),returnObj, expectedAction, APPLICATION_JSON); } public void prepareDeleteCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { @@ -83,6 +95,10 @@ public class StubServerUtil { .then(expectedStatus, jsonContent(returnObj), contentType(APPLICATION_JSON)); } + public List<Call> getServerCalls() { + return stubServer.getCalls(); + } + private Action jsonContent(Object returnObj) throws JsonProcessingException { return stringContent(objectMapper.writeValueAsString(returnObj)); } |