From 666b4d7a3b758ebec900f96a6aafe5c1a9ad2093 Mon Sep 17 00:00:00 2001 From: "Arul.Nambi" Date: Thu, 14 Sep 2017 13:44:07 -0400 Subject: Renaming openecomp to onap Issue-ID: AAI-208 Change-Id: I852fda30e0b44e73da8ae3e4748b49c663e544d0 Signed-off-by: Arul.Nambi --- .../aai/restclient/client/OperationResultTest.java | 106 +++++++ .../aai/restclient/client/RestfulClientTest.java | 340 +++++++++++++++++++++ .../enums/RestAuthenticationModeTest.java | 56 ++++ .../org/onap/aai/restclient/rest/HttpUtilTest.java | 74 +++++ .../aai/restclient/rest/RestClientBuilderTest.java | 273 +++++++++++++++++ .../restclient/client/OperationResultTest.java | 105 ------- .../restclient/client/RestfulClientTest.java | 338 -------------------- .../enums/RestAuthenticationModeTest.java | 55 ---- .../openecomp/restclient/rest/HttpUtilTest.java | 73 ----- .../restclient/rest/RestClientBuilderTest.java | 272 ----------------- 10 files changed, 849 insertions(+), 843 deletions(-) create mode 100644 src/test/java/org/onap/aai/restclient/client/OperationResultTest.java create mode 100644 src/test/java/org/onap/aai/restclient/client/RestfulClientTest.java create mode 100644 src/test/java/org/onap/aai/restclient/enums/RestAuthenticationModeTest.java create mode 100644 src/test/java/org/onap/aai/restclient/rest/HttpUtilTest.java create mode 100644 src/test/java/org/onap/aai/restclient/rest/RestClientBuilderTest.java delete mode 100644 src/test/java/org/openecomp/restclient/client/OperationResultTest.java delete mode 100644 src/test/java/org/openecomp/restclient/client/RestfulClientTest.java delete mode 100644 src/test/java/org/openecomp/restclient/enums/RestAuthenticationModeTest.java delete mode 100644 src/test/java/org/openecomp/restclient/rest/HttpUtilTest.java delete mode 100644 src/test/java/org/openecomp/restclient/rest/RestClientBuilderTest.java (limited to 'src/test/java') diff --git a/src/test/java/org/onap/aai/restclient/client/OperationResultTest.java b/src/test/java/org/onap/aai/restclient/client/OperationResultTest.java new file mode 100644 index 0000000..6f18f9a --- /dev/null +++ b/src/test/java/org/onap/aai/restclient/client/OperationResultTest.java @@ -0,0 +1,106 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restclient.client; + +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.junit.Assert.assertTrue; + +import javax.ws.rs.core.MultivaluedMap; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.restclient.client.OperationResult; + +import com.sun.jersey.core.util.MultivaluedMapImpl; + +public class OperationResultTest { + + /** + * Test case initialization + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + } + + @Test + public void validateConstruction() { + + OperationResult opResult = new OperationResult(); + assertEquals(opResult.getNumRetries(),0); + assertFalse(opResult.isFromCache()); + assertFalse(opResult.wasSuccessful()); + opResult.setResultCode(612); + assertFalse(opResult.wasSuccessful()); + assertNull(opResult.getHeaders()); + + opResult = new OperationResult(204,"no content found"); + assertEquals(opResult.getResultCode(),204); + assertEquals(opResult.getResult(),"no content found"); + assertTrue(opResult.wasSuccessful()); + + MultivaluedMap multiMap = new MultivaluedMapImpl(); + multiMap.add("p1","v1"); + multiMap.add("p2","v2"); + opResult.setHeaders(multiMap); + assertNotNull(opResult.getHeaders()); + assertEquals(opResult.getHeaders().size(), 2); + + } + + @Test + public void validateAccesors() { + + OperationResult opResult = new OperationResult(); + + opResult.setFailureCause("failure"); + opResult.setFromCache(false); + opResult.setNumRetries(101); + opResult.setRequestedLink("http://localhost:1234"); + opResult.setResult("result"); + opResult.setResultCode(555); + + assertEquals(opResult.getFailureCause(), "failure"); + assertFalse(opResult.isFromCache()); + assertEquals(opResult.getNumRetries(),101); + assertEquals(opResult.getRequestedLink(),"http://localhost:1234"); + assertEquals(opResult.getResult(), "result"); + assertEquals(opResult.getResultCode(),555); + + opResult.setResult(212, "mostly successful"); + assertEquals(opResult.getResultCode(),212); + assertEquals(opResult.getResult(), "mostly successful"); + + assertTrue(opResult.toString().contains("OperationResult")); + + opResult.setFailureCause(511, "things melting"); + assertEquals(opResult.getResultCode(),511); + assertEquals(opResult.getFailureCause(), "things melting"); + + } + +} diff --git a/src/test/java/org/onap/aai/restclient/client/RestfulClientTest.java b/src/test/java/org/onap/aai/restclient/client/RestfulClientTest.java new file mode 100644 index 0000000..0e5c84e --- /dev/null +++ b/src/test/java/org/onap/aai/restclient/client/RestfulClientTest.java @@ -0,0 +1,340 @@ +/* + * ============LICENSE_START=========================================================================================== + * Copyright (c) 2017 AT&T Intellectual Property. + * Copyright (c) 2017 Amdocs + * All rights reserved. + * ===================================================================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * ============LICENSE_END================================================== =========================================== + * + * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. + */ +package org.onap.aai.restclient.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.restclient.client.RestClient; +import org.onap.aai.restclient.enums.RestAuthenticationMode; +import org.onap.aai.restclient.rest.RestClientBuilder; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.WebResource.Builder; +import com.sun.jersey.core.util.MultivaluedMapImpl; + +public class RestfulClientTest { + + private static final String TEST_URL = "http://localhost:9000/aai/v7"; + + private final MultivaluedMapImpl emptyMap = new MultivaluedMapImpl(); + + private RestClientBuilder mockClientBuilder; + private Client mockedClient; + private WebResource mockedWebResource; + private Builder mockedBuilder; + private ClientResponse mockedClientResponse; + + /** + * Test case initialization + * + * @throws Exception the exception + */ + @SuppressWarnings("unchecked") + @Before + public void init() throws Exception { + mockedClientResponse = Mockito.mock(ClientResponse.class); + setResponseStatus(Response.Status.OK); + Mockito.when(mockedClientResponse.getHeaders()).thenReturn(emptyMap); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("hello"); + + mockedBuilder = Mockito.mock(Builder.class); + Mockito.when(mockedBuilder.get(Mockito.any(Class.class))).thenReturn(mockedClientResponse); + Mockito.when(mockedBuilder.post(Mockito.any(Class.class))).thenReturn(mockedClientResponse); + Mockito.when(mockedBuilder.put(Mockito.any(Class.class))).thenReturn(mockedClientResponse); + Mockito.when(mockedBuilder.delete(Mockito.any(Class.class))).thenReturn(mockedClientResponse); + Mockito.when(mockedBuilder.head()).thenReturn(mockedClientResponse); + + mockedWebResource = Mockito.mock(WebResource.class); + Mockito.when(mockedWebResource.accept(Mockito.anyVararg())).thenReturn(mockedBuilder); + + mockedClient = Mockito.mock(Client.class); + Mockito.when(mockedClient.resource(Mockito.anyString())).thenReturn(mockedWebResource); + + mockClientBuilder = Mockito.mock(RestClientBuilder.class); + Mockito.when(mockClientBuilder.getClient()).thenReturn(mockedClient); + } + + @Test + public void validateConstructors() { + RestClient restClient = new RestClient(); + assertNotNull(restClient); + restClient = new RestClient(mockClientBuilder); + assertNotNull(restClient); + } + + @Test + public void validateBasicClientConstruction() throws Exception { + Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.HTTP_NOAUTH) + .connectTimeoutMs(1000).readTimeoutMs(500).getClient(); + assertNotNull(client); + } + + @Test + public void validateClientWithSslBasicAuthConstruction() throws Exception { + Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC) + .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthPassword("password").basicAuthUsername("username") + .getClient(); + assertNotNull(client); + } + + @Test + public void validateClientWithSslCertConstruction() throws Exception { + // This test covers the standard SSL settings, i.e. no validation + assertNotNull(buildClient()); + + RestClient restClient = new RestClient(mockClientBuilder); + + // Test with validation enabled + Client client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000) + .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").validateServerCertChain(true) + .validateServerHostname(true).getClient(); + assertNotNull(client); + + // Test with a trust store + client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000) + .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").trustStore("truststore") + .getClient(); + assertNotNull(client); + } + + @Test + public void validateSuccessfulPut() throws Exception { + RestClient restClient = buildClient(); + + OperationResult result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + // Repeat the PUT operation, this time with a return code of 204 + setResponseToNoContent(); + result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); + assertNull(result.getResult()); + assertNull(result.getFailureCause()); + } + + @Test + public void validateSuccessfulPost() throws Exception { + RestClient restClient = buildClient(); + + OperationResult result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + // Repeat the POST operation, this time with a return code of 204 + setResponseToNoContent(); + result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); + assertNull(result.getResult()); + assertNull(result.getFailureCause()); + } + + @Test + public void validateSuccessfulGet() throws Exception { + OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + } + + @Test + public void validateSuccessfulGetWithBasicAuth() throws Exception { + RestClient restClient = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC) + .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthUsername("username").basicAuthUsername("password"); + + OperationResult result = restClient.get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + } + + @Test + public void validateResourceNotFoundGet() throws Exception { + setResponseStatus(Response.Status.NOT_FOUND); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("RNF"); + + OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode()); + assertNull(result.getResult()); + assertNotNull(result.getFailureCause()); + } + + @Test + public void validateHealthCheck() throws Exception { + boolean targetServiceHealthy = + buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); + + assertEquals(true, targetServiceHealthy); + } + + @Test + public void validateHealthCheckFailureWith403() throws Exception { + Mockito.when(mockedClientResponse.getStatus()).thenReturn(Response.Status.FORBIDDEN.getStatusCode()); + + boolean targetServiceHealthy = + buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); + + assertEquals(false, targetServiceHealthy); + } + + @Test + public void validateHealthCheckFailureWithThrownException() throws Exception { + Mockito.when(mockedBuilder.get(Mockito.any(Class.class))).thenThrow(new IllegalArgumentException("error")); + + boolean targetServiceHealthy = + buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); + + assertEquals(false, targetServiceHealthy); + } + + @Test + public void validateSuccessfulGetWithRetries() throws Exception { + Mockito.when(mockedClientResponse.getStatus()).thenReturn(408).thenReturn(Response.Status.OK.getStatusCode()); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error").thenReturn("ok"); + + OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + } + + @Test + public void validateFailedGetWithRetriesCausedByResourceNotFound() throws Exception { + setResponseStatus(Response.Status.NOT_FOUND); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error").thenReturn("ok"); + + OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode()); + assertNull(result.getResult()); + assertNotNull(result.getFailureCause()); + + } + + @Test + public void validateFailedGetAfterMaxRetries() throws Exception { + setResponseStatus(Response.Status.INTERNAL_SERVER_ERROR); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error"); + + OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); + + assertEquals(504, result.getResultCode()); + assertNull(result.getResult()); + assertNotNull(result.getFailureCause()); + + } + + @Test + public void validateSuccessfulDelete() throws Exception { + RestClient restClient = buildClient(); + + OperationResult result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + // Repeat the DELETE operation, this time with a return code of 204 + setResponseToNoContent(); + result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); + assertNull(result.getResult()); + assertNull(result.getFailureCause()); + } + + + @Test + public void validateSuccessfulHead() throws Exception { + OperationResult result = buildClient().head(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + } + + @Test + public void validateSuccessfulPatch() throws Exception { + Mockito.when(mockedBuilder.header("X-HTTP-Method-Override", "PATCH")).thenReturn(mockedBuilder); + OperationResult result = buildClient().patch(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, + MediaType.APPLICATION_JSON_TYPE); + + assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); + assertNotNull(result.getResult()); + assertNull(result.getFailureCause()); + + } + + /** + * Specify the status code of the response object returned by the mocked client + * + * @param status object storing the status code to mock in the ClientResponse + */ + private void setResponseStatus(Status status) { + Mockito.when(mockedClientResponse.getStatus()).thenReturn(status.getStatusCode()); + } + + /** + * Set the mocked client to return a response of "204 No Content" + */ + private void setResponseToNoContent() { + setResponseStatus(Response.Status.NO_CONTENT); + // The Jersey client throws an exception when getEntity() is called following a 204 response + UniformInterfaceException uniformInterfaceException = new UniformInterfaceException(mockedClientResponse); + Mockito.when(mockedClientResponse.getEntity(String.class)).thenThrow(uniformInterfaceException); + } + + /** + * @return a mocked Rest Client object using standard SSL settings + */ + private RestClient buildClient() { + return new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_CERT) + .connectTimeoutMs(1000).readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password"); + } + +} diff --git a/src/test/java/org/onap/aai/restclient/enums/RestAuthenticationModeTest.java b/src/test/java/org/onap/aai/restclient/enums/RestAuthenticationModeTest.java new file mode 100644 index 0000000..c95431c --- /dev/null +++ b/src/test/java/org/onap/aai/restclient/enums/RestAuthenticationModeTest.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restclient.enums; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.restclient.enums.RestAuthenticationMode; + +public class RestAuthenticationModeTest { + + /** + * Test case initialization + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + } + + @Test + public void validateEnumMappings() { + + assertEquals(RestAuthenticationMode.getRestAuthenticationMode(null), RestAuthenticationMode.UNKNOWN_MODE); + assertEquals(RestAuthenticationMode.getRestAuthenticationMode("OAuth"), RestAuthenticationMode.UNKNOWN_MODE); + assertEquals(RestAuthenticationMode.getRestAuthenticationMode("SSL_BASIC"), RestAuthenticationMode.SSL_BASIC); + assertEquals(RestAuthenticationMode.getRestAuthenticationMode("SSL_CERT"), RestAuthenticationMode.SSL_CERT); + assertEquals(RestAuthenticationMode.getRestAuthenticationMode("HTTP_NOAUTH"), RestAuthenticationMode.HTTP_NOAUTH); + + assertEquals(RestAuthenticationMode.SSL_BASIC.getAuthenticationModeLabel(),"SSL_BASIC"); + + + } + +} diff --git a/src/test/java/org/onap/aai/restclient/rest/HttpUtilTest.java b/src/test/java/org/onap/aai/restclient/rest/HttpUtilTest.java new file mode 100644 index 0000000..7e9291c --- /dev/null +++ b/src/test/java/org/onap/aai/restclient/rest/HttpUtilTest.java @@ -0,0 +1,74 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restclient.rest; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.restclient.rest.HttpUtil; + +public class HttpUtilTest { + + /** + * Test case initialization + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + } + + @Test + public void validateAccesors() { + + assertFalse(HttpUtil.isHttpResponseClassInformational(-1)); + assertFalse(HttpUtil.isHttpResponseClassInformational(99)); + assertTrue(HttpUtil.isHttpResponseClassInformational(183)); + assertFalse(HttpUtil.isHttpResponseClassInformational(200)); + + assertFalse(HttpUtil.isHttpResponseClassSuccess(199)); + assertTrue(HttpUtil.isHttpResponseClassSuccess(202)); + assertFalse(HttpUtil.isHttpResponseClassSuccess(300)); + + assertFalse(HttpUtil.isHttpResponseClassRedirection(299)); + assertTrue(HttpUtil.isHttpResponseClassRedirection(307)); + assertFalse(HttpUtil.isHttpResponseClassRedirection(401)); + + assertFalse(HttpUtil.isHttpResponseClassClientError(399)); + assertTrue(HttpUtil.isHttpResponseClassClientError(404)); + assertFalse(HttpUtil.isHttpResponseClassClientError(555)); + + assertFalse(HttpUtil.isHttpResponseClassServerError(499)); + assertTrue(HttpUtil.isHttpResponseClassServerError(504)); + assertFalse(HttpUtil.isHttpResponseClassServerError(662)); + + int[] successCodes = { 201, 202, 205, 299 }; + + assertTrue(HttpUtil.isHttpResponseInList(201, successCodes)); + assertFalse(HttpUtil.isHttpResponseInList(301, successCodes)); + + } + +} diff --git a/src/test/java/org/onap/aai/restclient/rest/RestClientBuilderTest.java b/src/test/java/org/onap/aai/restclient/rest/RestClientBuilderTest.java new file mode 100644 index 0000000..013f817 --- /dev/null +++ b/src/test/java/org/onap/aai/restclient/rest/RestClientBuilderTest.java @@ -0,0 +1,273 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 Amdocs + * ================================================================================ + * 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.restclient.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.restclient.enums.RestAuthenticationMode; +import org.onap.aai.restclient.rest.RestClientBuilder; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.client.urlconnection.HTTPSProperties; + +/** + * This suite of tests is intended to exercise the functionality of the generice REST client + * builder. + */ +public class RestClientBuilderTest { + + /** + * Test case initialization + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + } + + private String generateAuthorizationHeaderValue(String username, String password) { + String usernameAndPassword = username + ":" + password; + return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()); + } + + @Test + public void validateAccesors() { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + // test defaults + assertEquals(restClientBuilder.isValidateServerHostname(), RestClientBuilder.DEFAULT_VALIDATE_SERVER_HOST); + assertEquals(restClientBuilder.isValidateServerCertChain(), RestClientBuilder.DEFAULT_VALIDATE_CERT_CHAIN); + assertEquals(restClientBuilder.getClientCertFileName(), RestClientBuilder.DEFAULT_CLIENT_CERT_FILENAME); + assertEquals(restClientBuilder.getClientCertPassword(), RestClientBuilder.DEFAULT_CERT_PASSWORD); + assertEquals(restClientBuilder.getTruststoreFilename(), RestClientBuilder.DEFAULT_TRUST_STORE_FILENAME); + assertEquals(restClientBuilder.getConnectTimeoutInMs(), RestClientBuilder.DEFAULT_CONNECT_TIMEOUT_MS); + assertEquals(restClientBuilder.getReadTimeoutInMs(), RestClientBuilder.DEFAULT_READ_TIMEOUT_MS); + assertEquals(restClientBuilder.getAuthenticationMode(), RestClientBuilder.DEFAULT_AUTH_MODE); + assertEquals(restClientBuilder.getBasicAuthUsername(), RestClientBuilder.DEFAULT_BASIC_AUTH_USERNAME); + assertEquals(restClientBuilder.getBasicAuthPassword(), RestClientBuilder.DEFAULT_BASIC_AUTH_PASSWORD); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); + restClientBuilder.setBasicAuthPassword("password"); + restClientBuilder.setBasicAuthUsername("username"); + restClientBuilder.setClientCertFileName("filename"); + restClientBuilder.setClientCertPassword("password"); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setTruststoreFilename("truststore"); + restClientBuilder.setValidateServerCertChain(true); + restClientBuilder.setValidateServerHostname(true); + + assertEquals(restClientBuilder.isValidateServerHostname(), true); + assertEquals(restClientBuilder.isValidateServerCertChain(), true); + assertEquals(restClientBuilder.getClientCertFileName(), "filename"); + assertEquals(restClientBuilder.getClientCertPassword(), "password"); + assertEquals(restClientBuilder.getTruststoreFilename(), "truststore"); + assertEquals(restClientBuilder.getConnectTimeoutInMs(), 12345); + assertEquals(restClientBuilder.getReadTimeoutInMs(), 54321); + assertEquals(restClientBuilder.getAuthenticationMode(), RestAuthenticationMode.UNKNOWN_MODE); + assertEquals(restClientBuilder.getBasicAuthUsername(), "username"); + assertEquals(restClientBuilder.getBasicAuthPassword(), "password"); + + assertEquals(restClientBuilder.getBasicAuthenticationCredentials(), + generateAuthorizationHeaderValue("username", "password")); + + assertTrue(restClientBuilder.toString().contains("RestClientBuilder")); + + } + + @Test + public void validateNoAuthClientCreation() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.HTTP_NOAUTH); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + + Client client = restClientBuilder.getClient(); + assertNotNull(client); + assertNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); + } + + + @Test + public void validateUnknownModeCreateNoAuthClient() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + + Client client = restClientBuilder.getClient(); + assertNotNull(client); + assertNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); + } + + @Test + public void validateBasicAuthSslClient() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_BASIC); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setBasicAuthUsername("username"); + restClientBuilder.setBasicAuthPassword("password"); + + Client client = restClientBuilder.getClient(); + + Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); + HTTPSProperties sslProps = null; + if ( sslPropertiesObj instanceof HTTPSProperties ) { + sslProps = (HTTPSProperties)sslPropertiesObj; + assertNotNull(sslProps.getHostnameVerifier()); + } else { + fail("Unexpected value for https properties object"); + } + + } + + @Test + public void validateSslCertClient_noHostOrCertChainValidation() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setValidateServerCertChain(false); + restClientBuilder.setValidateServerHostname(false); + + Client client = restClientBuilder.getClient(); + + Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); + HTTPSProperties sslProps = null; + if ( sslPropertiesObj instanceof HTTPSProperties ) { + sslProps = (HTTPSProperties)sslPropertiesObj; + assertNotNull(sslProps.getHostnameVerifier()); + } else { + fail("Unexpected value for https properties object"); + } } + + @Test + public void validateSslCertClient_hostOnlyValidation() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setValidateServerCertChain(false); + restClientBuilder.setValidateServerHostname(true); + + Client client = restClientBuilder.getClient(); + + Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); + HTTPSProperties sslProps = null; + if ( sslPropertiesObj instanceof HTTPSProperties ) { + sslProps = (HTTPSProperties)sslPropertiesObj; + assertNull(sslProps.getHostnameVerifier()); + } else { + fail("Unexpected value for https properties object"); + } + } + + @Test + public void validateSslCertClient_certChainOnlyValidation() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setValidateServerCertChain(true); + restClientBuilder.setValidateServerHostname(false); + restClientBuilder.setTruststoreFilename("truststore"); + restClientBuilder.setClientCertPassword(null); + + Client client = restClientBuilder.getClient(); + + Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); + HTTPSProperties sslProps = null; + if ( sslPropertiesObj instanceof HTTPSProperties ) { + sslProps = (HTTPSProperties)sslPropertiesObj; + assertNotNull(sslProps.getHostnameVerifier()); + } else { + fail("Unexpected value for https properties object"); + } + } + + @Test + public void validateSslCertClient_withHostAndCertChainValidation() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setValidateServerCertChain(true); + restClientBuilder.setValidateServerHostname(true); + restClientBuilder.setClientCertPassword("password"); + restClientBuilder.setTruststoreFilename("truststore"); + + Client client = restClientBuilder.getClient(); + + Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); + HTTPSProperties sslProps = null; + if ( sslPropertiesObj instanceof HTTPSProperties ) { + sslProps = (HTTPSProperties)sslPropertiesObj; + assertNull(sslProps.getHostnameVerifier()); + } else { + fail("Unexpected value for https properties object"); + } } + + @Test (expected=IllegalArgumentException.class) + public void validateSslCertClient_illegalArgumentExceptionWhenTruststoreIsNull() throws Exception { + + RestClientBuilder restClientBuilder = new RestClientBuilder(); + + restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restClientBuilder.setConnectTimeoutInMs(12345); + restClientBuilder.setReadTimeoutInMs(54321); + restClientBuilder.setValidateServerCertChain(true); + restClientBuilder.setValidateServerHostname(true); + restClientBuilder.setTruststoreFilename(null); + + /* + * Creating the client in this scenario will cause an IllegalArgumentException caused by the + * truststore being null + */ + Client client = restClientBuilder.getClient(); + + } + + +} diff --git a/src/test/java/org/openecomp/restclient/client/OperationResultTest.java b/src/test/java/org/openecomp/restclient/client/OperationResultTest.java deleted file mode 100644 index 77e6e29..0000000 --- a/src/test/java/org/openecomp/restclient/client/OperationResultTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.restclient.client; - -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.junit.Assert.assertTrue; - -import javax.ws.rs.core.MultivaluedMap; - -import org.junit.Before; -import org.junit.Test; - -import com.sun.jersey.core.util.MultivaluedMapImpl; - -public class OperationResultTest { - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - } - - @Test - public void validateConstruction() { - - OperationResult opResult = new OperationResult(); - assertEquals(opResult.getNumRetries(),0); - assertFalse(opResult.isFromCache()); - assertFalse(opResult.wasSuccessful()); - opResult.setResultCode(612); - assertFalse(opResult.wasSuccessful()); - assertNull(opResult.getHeaders()); - - opResult = new OperationResult(204,"no content found"); - assertEquals(opResult.getResultCode(),204); - assertEquals(opResult.getResult(),"no content found"); - assertTrue(opResult.wasSuccessful()); - - MultivaluedMap multiMap = new MultivaluedMapImpl(); - multiMap.add("p1","v1"); - multiMap.add("p2","v2"); - opResult.setHeaders(multiMap); - assertNotNull(opResult.getHeaders()); - assertEquals(opResult.getHeaders().size(), 2); - - } - - @Test - public void validateAccesors() { - - OperationResult opResult = new OperationResult(); - - opResult.setFailureCause("failure"); - opResult.setFromCache(false); - opResult.setNumRetries(101); - opResult.setRequestedLink("http://localhost:1234"); - opResult.setResult("result"); - opResult.setResultCode(555); - - assertEquals(opResult.getFailureCause(), "failure"); - assertFalse(opResult.isFromCache()); - assertEquals(opResult.getNumRetries(),101); - assertEquals(opResult.getRequestedLink(),"http://localhost:1234"); - assertEquals(opResult.getResult(), "result"); - assertEquals(opResult.getResultCode(),555); - - opResult.setResult(212, "mostly successful"); - assertEquals(opResult.getResultCode(),212); - assertEquals(opResult.getResult(), "mostly successful"); - - assertTrue(opResult.toString().contains("OperationResult")); - - opResult.setFailureCause(511, "things melting"); - assertEquals(opResult.getResultCode(),511); - assertEquals(opResult.getFailureCause(), "things melting"); - - } - -} diff --git a/src/test/java/org/openecomp/restclient/client/RestfulClientTest.java b/src/test/java/org/openecomp/restclient/client/RestfulClientTest.java deleted file mode 100644 index 784aa91..0000000 --- a/src/test/java/org/openecomp/restclient/client/RestfulClientTest.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * ============LICENSE_START=========================================================================================== - * Copyright (c) 2017 AT&T Intellectual Property. - * Copyright (c) 2017 Amdocs - * All rights reserved. - * ===================================================================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * ============LICENSE_END================================================== =========================================== - * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. - */ -package org.openecomp.restclient.client; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.restclient.enums.RestAuthenticationMode; -import org.openecomp.restclient.rest.RestClientBuilder; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.UniformInterfaceException; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; -import com.sun.jersey.core.util.MultivaluedMapImpl; - -public class RestfulClientTest { - - private static final String TEST_URL = "http://localhost:9000/aai/v7"; - - private final MultivaluedMapImpl emptyMap = new MultivaluedMapImpl(); - - private RestClientBuilder mockClientBuilder; - private Client mockedClient; - private WebResource mockedWebResource; - private Builder mockedBuilder; - private ClientResponse mockedClientResponse; - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @SuppressWarnings("unchecked") - @Before - public void init() throws Exception { - mockedClientResponse = Mockito.mock(ClientResponse.class); - setResponseStatus(Response.Status.OK); - Mockito.when(mockedClientResponse.getHeaders()).thenReturn(emptyMap); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("hello"); - - mockedBuilder = Mockito.mock(Builder.class); - Mockito.when(mockedBuilder.get(Mockito.any(Class.class))).thenReturn(mockedClientResponse); - Mockito.when(mockedBuilder.post(Mockito.any(Class.class))).thenReturn(mockedClientResponse); - Mockito.when(mockedBuilder.put(Mockito.any(Class.class))).thenReturn(mockedClientResponse); - Mockito.when(mockedBuilder.delete(Mockito.any(Class.class))).thenReturn(mockedClientResponse); - Mockito.when(mockedBuilder.head()).thenReturn(mockedClientResponse); - - mockedWebResource = Mockito.mock(WebResource.class); - Mockito.when(mockedWebResource.accept(Mockito.anyVararg())).thenReturn(mockedBuilder); - - mockedClient = Mockito.mock(Client.class); - Mockito.when(mockedClient.resource(Mockito.anyString())).thenReturn(mockedWebResource); - - mockClientBuilder = Mockito.mock(RestClientBuilder.class); - Mockito.when(mockClientBuilder.getClient()).thenReturn(mockedClient); - } - - @Test - public void validateConstructors() { - RestClient restClient = new RestClient(); - assertNotNull(restClient); - restClient = new RestClient(mockClientBuilder); - assertNotNull(restClient); - } - - @Test - public void validateBasicClientConstruction() throws Exception { - Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.HTTP_NOAUTH) - .connectTimeoutMs(1000).readTimeoutMs(500).getClient(); - assertNotNull(client); - } - - @Test - public void validateClientWithSslBasicAuthConstruction() throws Exception { - Client client = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC) - .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthPassword("password").basicAuthUsername("username") - .getClient(); - assertNotNull(client); - } - - @Test - public void validateClientWithSslCertConstruction() throws Exception { - // This test covers the standard SSL settings, i.e. no validation - assertNotNull(buildClient()); - - RestClient restClient = new RestClient(mockClientBuilder); - - // Test with validation enabled - Client client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000) - .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").validateServerCertChain(true) - .validateServerHostname(true).getClient(); - assertNotNull(client); - - // Test with a trust store - client = restClient.authenticationMode(RestAuthenticationMode.SSL_CERT).connectTimeoutMs(1000) - .readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password").trustStore("truststore") - .getClient(); - assertNotNull(client); - } - - @Test - public void validateSuccessfulPut() throws Exception { - RestClient restClient = buildClient(); - - OperationResult result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - // Repeat the PUT operation, this time with a return code of 204 - setResponseToNoContent(); - result = restClient.put(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); - assertNull(result.getResult()); - assertNull(result.getFailureCause()); - } - - @Test - public void validateSuccessfulPost() throws Exception { - RestClient restClient = buildClient(); - - OperationResult result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - // Repeat the POST operation, this time with a return code of 204 - setResponseToNoContent(); - result = restClient.post(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); - assertNull(result.getResult()); - assertNull(result.getFailureCause()); - } - - @Test - public void validateSuccessfulGet() throws Exception { - OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - } - - @Test - public void validateSuccessfulGetWithBasicAuth() throws Exception { - RestClient restClient = new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_BASIC) - .connectTimeoutMs(1000).readTimeoutMs(500).basicAuthUsername("username").basicAuthUsername("password"); - - OperationResult result = restClient.get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - } - - @Test - public void validateResourceNotFoundGet() throws Exception { - setResponseStatus(Response.Status.NOT_FOUND); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("RNF"); - - OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode()); - assertNull(result.getResult()); - assertNotNull(result.getFailureCause()); - } - - @Test - public void validateHealthCheck() throws Exception { - boolean targetServiceHealthy = - buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); - - assertEquals(true, targetServiceHealthy); - } - - @Test - public void validateHealthCheckFailureWith403() throws Exception { - Mockito.when(mockedClientResponse.getStatus()).thenReturn(Response.Status.FORBIDDEN.getStatusCode()); - - boolean targetServiceHealthy = - buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); - - assertEquals(false, targetServiceHealthy); - } - - @Test - public void validateHealthCheckFailureWithThrownException() throws Exception { - Mockito.when(mockedBuilder.get(Mockito.any(Class.class))).thenThrow(new IllegalArgumentException("error")); - - boolean targetServiceHealthy = - buildClient().healthCheck("http://localhost:9000/aai/util/echo", "startSerice", "targetService"); - - assertEquals(false, targetServiceHealthy); - } - - @Test - public void validateSuccessfulGetWithRetries() throws Exception { - Mockito.when(mockedClientResponse.getStatus()).thenReturn(408).thenReturn(Response.Status.OK.getStatusCode()); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error").thenReturn("ok"); - - OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - } - - @Test - public void validateFailedGetWithRetriesCausedByResourceNotFound() throws Exception { - setResponseStatus(Response.Status.NOT_FOUND); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error").thenReturn("ok"); - - OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), result.getResultCode()); - assertNull(result.getResult()); - assertNotNull(result.getFailureCause()); - - } - - @Test - public void validateFailedGetAfterMaxRetries() throws Exception { - setResponseStatus(Response.Status.INTERNAL_SERVER_ERROR); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenReturn("error"); - - OperationResult result = buildClient().get(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE, 3); - - assertEquals(504, result.getResultCode()); - assertNull(result.getResult()); - assertNotNull(result.getFailureCause()); - - } - - @Test - public void validateSuccessfulDelete() throws Exception { - RestClient restClient = buildClient(); - - OperationResult result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - // Repeat the DELETE operation, this time with a return code of 204 - setResponseToNoContent(); - result = restClient.delete(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), result.getResultCode()); - assertNull(result.getResult()); - assertNull(result.getFailureCause()); - } - - - @Test - public void validateSuccessfulHead() throws Exception { - OperationResult result = buildClient().head(TEST_URL, emptyMap, MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - } - - @Test - public void validateSuccessfulPatch() throws Exception { - Mockito.when(mockedBuilder.header("X-HTTP-Method-Override", "PATCH")).thenReturn(mockedBuilder); - OperationResult result = buildClient().patch(TEST_URL, "", emptyMap, MediaType.APPLICATION_JSON_TYPE, - MediaType.APPLICATION_JSON_TYPE); - - assertEquals(Response.Status.OK.getStatusCode(), result.getResultCode()); - assertNotNull(result.getResult()); - assertNull(result.getFailureCause()); - - } - - /** - * Specify the status code of the response object returned by the mocked client - * - * @param status object storing the status code to mock in the ClientResponse - */ - private void setResponseStatus(Status status) { - Mockito.when(mockedClientResponse.getStatus()).thenReturn(status.getStatusCode()); - } - - /** - * Set the mocked client to return a response of "204 No Content" - */ - private void setResponseToNoContent() { - setResponseStatus(Response.Status.NO_CONTENT); - // The Jersey client throws an exception when getEntity() is called following a 204 response - UniformInterfaceException uniformInterfaceException = new UniformInterfaceException(mockedClientResponse); - Mockito.when(mockedClientResponse.getEntity(String.class)).thenThrow(uniformInterfaceException); - } - - /** - * @return a mocked Rest Client object using standard SSL settings - */ - private RestClient buildClient() { - return new RestClient(mockClientBuilder).authenticationMode(RestAuthenticationMode.SSL_CERT) - .connectTimeoutMs(1000).readTimeoutMs(500).clientCertFile("cert").clientCertPassword("password"); - } - -} diff --git a/src/test/java/org/openecomp/restclient/enums/RestAuthenticationModeTest.java b/src/test/java/org/openecomp/restclient/enums/RestAuthenticationModeTest.java deleted file mode 100644 index ebdddbf..0000000 --- a/src/test/java/org/openecomp/restclient/enums/RestAuthenticationModeTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.restclient.enums; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; - -public class RestAuthenticationModeTest { - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - } - - @Test - public void validateEnumMappings() { - - assertEquals(RestAuthenticationMode.getRestAuthenticationMode(null), RestAuthenticationMode.UNKNOWN_MODE); - assertEquals(RestAuthenticationMode.getRestAuthenticationMode("OAuth"), RestAuthenticationMode.UNKNOWN_MODE); - assertEquals(RestAuthenticationMode.getRestAuthenticationMode("SSL_BASIC"), RestAuthenticationMode.SSL_BASIC); - assertEquals(RestAuthenticationMode.getRestAuthenticationMode("SSL_CERT"), RestAuthenticationMode.SSL_CERT); - assertEquals(RestAuthenticationMode.getRestAuthenticationMode("HTTP_NOAUTH"), RestAuthenticationMode.HTTP_NOAUTH); - - assertEquals(RestAuthenticationMode.SSL_BASIC.getAuthenticationModeLabel(),"SSL_BASIC"); - - - } - -} diff --git a/src/test/java/org/openecomp/restclient/rest/HttpUtilTest.java b/src/test/java/org/openecomp/restclient/rest/HttpUtilTest.java deleted file mode 100644 index 9eb0362..0000000 --- a/src/test/java/org/openecomp/restclient/rest/HttpUtilTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.restclient.rest; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; - -public class HttpUtilTest { - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - } - - @Test - public void validateAccesors() { - - assertFalse(HttpUtil.isHttpResponseClassInformational(-1)); - assertFalse(HttpUtil.isHttpResponseClassInformational(99)); - assertTrue(HttpUtil.isHttpResponseClassInformational(183)); - assertFalse(HttpUtil.isHttpResponseClassInformational(200)); - - assertFalse(HttpUtil.isHttpResponseClassSuccess(199)); - assertTrue(HttpUtil.isHttpResponseClassSuccess(202)); - assertFalse(HttpUtil.isHttpResponseClassSuccess(300)); - - assertFalse(HttpUtil.isHttpResponseClassRedirection(299)); - assertTrue(HttpUtil.isHttpResponseClassRedirection(307)); - assertFalse(HttpUtil.isHttpResponseClassRedirection(401)); - - assertFalse(HttpUtil.isHttpResponseClassClientError(399)); - assertTrue(HttpUtil.isHttpResponseClassClientError(404)); - assertFalse(HttpUtil.isHttpResponseClassClientError(555)); - - assertFalse(HttpUtil.isHttpResponseClassServerError(499)); - assertTrue(HttpUtil.isHttpResponseClassServerError(504)); - assertFalse(HttpUtil.isHttpResponseClassServerError(662)); - - int[] successCodes = { 201, 202, 205, 299 }; - - assertTrue(HttpUtil.isHttpResponseInList(201, successCodes)); - assertFalse(HttpUtil.isHttpResponseInList(301, successCodes)); - - } - -} diff --git a/src/test/java/org/openecomp/restclient/rest/RestClientBuilderTest.java b/src/test/java/org/openecomp/restclient/rest/RestClientBuilderTest.java deleted file mode 100644 index 1481c06..0000000 --- a/src/test/java/org/openecomp/restclient/rest/RestClientBuilderTest.java +++ /dev/null @@ -1,272 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.openecomp.restclient.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.restclient.enums.RestAuthenticationMode; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.client.urlconnection.HTTPSProperties; - -/** - * This suite of tests is intended to exercise the functionality of the generice REST client - * builder. - */ -public class RestClientBuilderTest { - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - } - - private String generateAuthorizationHeaderValue(String username, String password) { - String usernameAndPassword = username + ":" + password; - return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()); - } - - @Test - public void validateAccesors() { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - // test defaults - assertEquals(restClientBuilder.isValidateServerHostname(), RestClientBuilder.DEFAULT_VALIDATE_SERVER_HOST); - assertEquals(restClientBuilder.isValidateServerCertChain(), RestClientBuilder.DEFAULT_VALIDATE_CERT_CHAIN); - assertEquals(restClientBuilder.getClientCertFileName(), RestClientBuilder.DEFAULT_CLIENT_CERT_FILENAME); - assertEquals(restClientBuilder.getClientCertPassword(), RestClientBuilder.DEFAULT_CERT_PASSWORD); - assertEquals(restClientBuilder.getTruststoreFilename(), RestClientBuilder.DEFAULT_TRUST_STORE_FILENAME); - assertEquals(restClientBuilder.getConnectTimeoutInMs(), RestClientBuilder.DEFAULT_CONNECT_TIMEOUT_MS); - assertEquals(restClientBuilder.getReadTimeoutInMs(), RestClientBuilder.DEFAULT_READ_TIMEOUT_MS); - assertEquals(restClientBuilder.getAuthenticationMode(), RestClientBuilder.DEFAULT_AUTH_MODE); - assertEquals(restClientBuilder.getBasicAuthUsername(), RestClientBuilder.DEFAULT_BASIC_AUTH_USERNAME); - assertEquals(restClientBuilder.getBasicAuthPassword(), RestClientBuilder.DEFAULT_BASIC_AUTH_PASSWORD); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); - restClientBuilder.setBasicAuthPassword("password"); - restClientBuilder.setBasicAuthUsername("username"); - restClientBuilder.setClientCertFileName("filename"); - restClientBuilder.setClientCertPassword("password"); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setTruststoreFilename("truststore"); - restClientBuilder.setValidateServerCertChain(true); - restClientBuilder.setValidateServerHostname(true); - - assertEquals(restClientBuilder.isValidateServerHostname(), true); - assertEquals(restClientBuilder.isValidateServerCertChain(), true); - assertEquals(restClientBuilder.getClientCertFileName(), "filename"); - assertEquals(restClientBuilder.getClientCertPassword(), "password"); - assertEquals(restClientBuilder.getTruststoreFilename(), "truststore"); - assertEquals(restClientBuilder.getConnectTimeoutInMs(), 12345); - assertEquals(restClientBuilder.getReadTimeoutInMs(), 54321); - assertEquals(restClientBuilder.getAuthenticationMode(), RestAuthenticationMode.UNKNOWN_MODE); - assertEquals(restClientBuilder.getBasicAuthUsername(), "username"); - assertEquals(restClientBuilder.getBasicAuthPassword(), "password"); - - assertEquals(restClientBuilder.getBasicAuthenticationCredentials(), - generateAuthorizationHeaderValue("username", "password")); - - assertTrue(restClientBuilder.toString().contains("RestClientBuilder")); - - } - - @Test - public void validateNoAuthClientCreation() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.HTTP_NOAUTH); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - - Client client = restClientBuilder.getClient(); - assertNotNull(client); - assertNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); - } - - - @Test - public void validateUnknownModeCreateNoAuthClient() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - - Client client = restClientBuilder.getClient(); - assertNotNull(client); - assertNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); - } - - @Test - public void validateBasicAuthSslClient() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_BASIC); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setBasicAuthUsername("username"); - restClientBuilder.setBasicAuthPassword("password"); - - Client client = restClientBuilder.getClient(); - - Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); - HTTPSProperties sslProps = null; - if ( sslPropertiesObj instanceof HTTPSProperties ) { - sslProps = (HTTPSProperties)sslPropertiesObj; - assertNotNull(sslProps.getHostnameVerifier()); - } else { - fail("Unexpected value for https properties object"); - } - - } - - @Test - public void validateSslCertClient_noHostOrCertChainValidation() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setValidateServerCertChain(false); - restClientBuilder.setValidateServerHostname(false); - - Client client = restClientBuilder.getClient(); - - Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); - HTTPSProperties sslProps = null; - if ( sslPropertiesObj instanceof HTTPSProperties ) { - sslProps = (HTTPSProperties)sslPropertiesObj; - assertNotNull(sslProps.getHostnameVerifier()); - } else { - fail("Unexpected value for https properties object"); - } } - - @Test - public void validateSslCertClient_hostOnlyValidation() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setValidateServerCertChain(false); - restClientBuilder.setValidateServerHostname(true); - - Client client = restClientBuilder.getClient(); - - Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); - HTTPSProperties sslProps = null; - if ( sslPropertiesObj instanceof HTTPSProperties ) { - sslProps = (HTTPSProperties)sslPropertiesObj; - assertNull(sslProps.getHostnameVerifier()); - } else { - fail("Unexpected value for https properties object"); - } - } - - @Test - public void validateSslCertClient_certChainOnlyValidation() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setValidateServerCertChain(true); - restClientBuilder.setValidateServerHostname(false); - restClientBuilder.setTruststoreFilename("truststore"); - restClientBuilder.setClientCertPassword(null); - - Client client = restClientBuilder.getClient(); - - Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); - HTTPSProperties sslProps = null; - if ( sslPropertiesObj instanceof HTTPSProperties ) { - sslProps = (HTTPSProperties)sslPropertiesObj; - assertNotNull(sslProps.getHostnameVerifier()); - } else { - fail("Unexpected value for https properties object"); - } - } - - @Test - public void validateSslCertClient_withHostAndCertChainValidation() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setValidateServerCertChain(true); - restClientBuilder.setValidateServerHostname(true); - restClientBuilder.setClientCertPassword("password"); - restClientBuilder.setTruststoreFilename("truststore"); - - Client client = restClientBuilder.getClient(); - - Object sslPropertiesObj = client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES); - HTTPSProperties sslProps = null; - if ( sslPropertiesObj instanceof HTTPSProperties ) { - sslProps = (HTTPSProperties)sslPropertiesObj; - assertNull(sslProps.getHostnameVerifier()); - } else { - fail("Unexpected value for https properties object"); - } } - - @Test (expected=IllegalArgumentException.class) - public void validateSslCertClient_illegalArgumentExceptionWhenTruststoreIsNull() throws Exception { - - RestClientBuilder restClientBuilder = new RestClientBuilder(); - - restClientBuilder.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - restClientBuilder.setConnectTimeoutInMs(12345); - restClientBuilder.setReadTimeoutInMs(54321); - restClientBuilder.setValidateServerCertChain(true); - restClientBuilder.setValidateServerHostname(true); - restClientBuilder.setTruststoreFilename(null); - - /* - * Creating the client in this scenario will cause an IllegalArgumentException caused by the - * truststore being null - */ - Client client = restClientBuilder.getClient(); - - } - - -} -- cgit 1.2.3-korg